Skip to content

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

fix(mcp): make tool-domain and query discovery more compact (#61700)

Georgiy Tarasov069765a7ba15
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.ts
index d2eb495afac4..debac393e0f5 100644
--- a/services/mcp/src/lib/instructions-formatter.ts
+++ b/services/mcp/src/lib/instructions-formatter.ts
@@ -2,7 +2,6 @@ import type { GroupType } from '@/api/client'
import {
buildDefinedGroupsBlock,
buildQueryToolsBlock,
- buildQueryToolsCompact,
buildToolDomainsBlock,
buildToolDomainsCompact,
type QueryToolInfo,
@@ -76,8 +75,10 @@ export class InstructionsFormatter {
/** Build the `command` parameter description for the exec tool. When
* `stripEnvContext` is true (the client already received env via the
- * `instructions` field), the env-related placeholders resolve to empty
- * strings to avoid duplication. */
+ * `instructions` field), the env-related placeholders (metadata, group
+ * types, tool domains) resolve to empty strings to avoid duplication. The
+ * query-tool catalog is kept: in single-exec mode it lives here on the exec
+ * tool, not in `instructions` (which only carries the `query` tool domain). */
buildExecCommandReference(ctx: InstructionsContext, opts: { stripEnvContext: boolean }): string {
const sections = [
CLI_SYNTAX,
@@ -94,7 +95,9 @@ export class InstructionsFormatter {
...(this.agentFeedbackEnabled(ctx.featureFlags) ? [AGENT_FEEDBACK] : []),
EXAMPLES,
]
- const renderCtx: InstructionsContext = opts.stripEnvContext ? { guidelines: ctx.guidelines } : ctx
+ const renderCtx: InstructionsContext = opts.stripEnvContext
+ ? { guidelines: ctx.guidelines, queryTools: ctx.queryTools }
+ : ctx
return this.compose(sections, renderCtx, { compact: false })
}
@@ -107,13 +110,15 @@ export class InstructionsFormatter {
private compose(sections: string[], ctx: InstructionsContext, opts: { compact: boolean }): string {
const renderToolDomains = opts.compact ? buildToolDomainsCompact : buildToolDomainsBlock
- const renderQueryTools = opts.compact ? buildQueryToolsCompact : buildQueryToolsBlock
+ // `{query_tools}` only appears in non-compact sections (the exec command
+ // reference and tools-mode instructions); compact mode surfaces queries
+ // via the single `query` tool domain instead.
const vars = {
guidelines: ctx.guidelines.trim(),
defined_groups: buildDefinedGroupsBlock(ctx.groupTypes),
metadata: ctx.metadata?.trim() ?? '',
tool_domains: ctx.tools ? renderToolDomains(ctx.tools) : '',
- query_tools: ctx.queryTools ? renderQueryTools(ctx.queryTools) : '',
+ query_tools: ctx.queryTools ? buildQueryToolsBlock(ctx.queryTools) : '',
}
const body = sections
.map((s) => s.trim())
diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.ts
index 4862d46d6c10..d9392004d609 100644
--- a/services/mcp/src/lib/instructions.ts
+++ b/services/mcp/src/lib/instructions.ts
@@ -64,53 +64,104 @@ export interface ToolInfo {
category: string
}
+interface ToolItem {
+ /** Tool name split on `-`, with a leading CRUD verb dropped. */
+ segments: string[]
+ /** `segments` with each part singularized — the key used for grouping so
+ * `feature-flag` and `feature-flags` land in the same family. */
+ key: string[]
+}
+
/**
- * Extracts unique tool domain prefixes from a list of tools, collapsing CRUD
- * variations into their shared domain while keeping standalone/meta tools as-is.
+ * Reduces a tool list to a compact set of name-prefix "domains" that seed the
+ * agent's `exec search <regex>` discovery (search matches name/title/description,
+ * so every emitted domain is a literal tool-name prefix and is guaranteed to
+ * retrieve its family).
*
- * For example: experiment-create, experiment-get, experiment-delete → "experiment"
- * But: execute-sql, read-data-schema → listed individually (no action to strip)
- * And: query-* tools are excluded (documented separately in the prompt).
+ * Tools are grouped globally (not per-category) by a radix tree over their name
+ * segments. A family stays a single domain while it is small enough to scan in
+ * one search ({@link MAX_FAMILY_SIZE}); oversized families are split into their
+ * sub-family roots one level deeper. So:
+ * - experiment-create / experiment-get / … → "experiment" (one flat family)
+ * - all 60+ llma-* tools → "llma-evaluation" | "llma-skill" | "llma-prompt" | …
+ * - external-data-schemas-* / external-data-sources-* → "external-data"
+ * - feature-flag-* / feature-flags-* → "feature-flag" (singular/plural merged)
+ * All query-* tools collapse to a single "query" domain (`search query-` lists
+ * them); their typed catalog is documented separately in the prompt.
*/
export class ToolDomainExtractor {
- private static readonly PREFIX_ACTIONS = new Set(['create', 'update', 'delete', 'get'])
+ /** A family at or below this many tools stays one domain; above it, split
+ * into sub-family roots. ~25 keeps flat CRUD families (e.g. experiment) whole
+ * while breaking up large multi-family areas (e.g. AI observability). */
+ private static readonly MAX_FAMILY_SIZE = 25
+ /** Cap on rendered segments so a singleton/leaf family becomes a short
+ * domain (`activity-log`) rather than its full tool name. */
+ private static readonly MAX_DOMAIN_SEGMENTS = 3
- private static readonly ACTION_SUFFIXES = new Set([
+ private static readonly SKIP_CATEGORIES = new Set(['Query wrappers', 'Debug'])
+ /** Stripped from the front so `get-llm-total-costs` joins the `llm` family
+ * instead of a spurious `get` family. */
+ private static readonly LEADING_VERBS = new Set([
+ 'get',
+ 'create',
+ 'update',
+ 'delete',
+ 'list',
+ 'retrieve',
+ 'destroy',
+ ])
+ /** Trimmed off the end of a rendered domain (only ever present on a
+ * singleton family, whose prefix runs to the trailing action). */
+ private static readonly TRAILING_ACTIONS = new Set([
'get',
- 'get-all',
- 'get-definition',
'list',
'create',
'update',
'delete',
'retrieve',
'destroy',
- 'partial-update',
+ 'run',
])
- private static readonly SKIP_CATEGORIES = new Set(['Query wrappers', 'Debug'])
- private static readonly MAX_DOMAIN_HYPHENS = 2
-
- private readonly standaloneTools = new Set<string>()
- private readonly derivedDomains = new Set<string>()
+ private readonly items: ToolItem[]
+ /** query-* tools are kept out of the trie and represented by a single
+ * `query` domain, so the catalog never fragments into per-insight roots. */
+ private readonly hasQueryTools: boolean
constructor(tools: ToolInfo[]) {
- const byCategory = this.groupByCategory(tools)
- this.extractDomainsPerCategory(byCategory)
+ this.hasQueryTools = tools.some(({ name }) => name.startsWith('query-'))
+ this.items = tools
+ .filter(
+ ({ name, category }) => !name.startsWith('query-') && !ToolDomainExtractor.SKIP_CATEGORIES.has(category)
+ )
+ .map(({ name }) => {
+ const segments = ToolDomainExtractor.toSegments(name)
+ return { segments, key: segments.map(ToolDomainExtractor.singularize) }
+ })
}
getDomains(): string[] {
- const collapsed = this.collapseDomains()
- const final = new Set(collapsed)
-
- for (const s of this.standaloneTools) {
- const covered = [...collapsed].some((d) => s.startsWith(d + '-') || s.startsWith(d + 's-'))
- if (!covered) {
- final.add(s)
+ const byRoot = new Map<string, ToolItem[]>()
+ for (const item of this.items) {
+ const root = item.key[0]
+ if (!root) {
+ continue
+ }
+ const bucket = byRoot.get(root)
+ if (bucket) {
+ bucket.push(item)
+ } else {
+ byRoot.set(root, [item])
}
}
-
- return [...final].sort()
+ const domains = new Set<string>()
+ for (const bucket of byRoot.values()) {
+ this.cut(bucket, 1, domains)
+ }
+ if (this.hasQueryTools) {
+ domains.add('query')
+ }
+ return [...domains].sort()
}
toMarkdown(): string {
@@ -123,120 +174,86 @@ export class ToolDomainExtractor {
return this.getDomains().join('|')
}
- private groupByCategory(tools: ToolInfo[]): Map<string, string[]> {
- const byCategory = new Map<string, string[]>()
- for (const { name, category } of tools) {
- if (name.startsWith('query-') || ToolDomainExtractor.SKIP_CATEGORIES.has(category)) {
- continue
+ /** Reduce a group sharing a `depth`-segment prefix to one or more domains,
+ * splitting only when the group is too large to scan in one search. */
+ private cut(group: ToolItem[], depth: number, out: Set<string>): void {
+ depth = this.compressUnary(group, depth)
+ if (group.length <= ToolDomainExtractor.MAX_FAMILY_SIZE) {
+ out.add(this.render(group, depth))
+ return
+ }
+ for (const [childKey, childGroup] of this.childrenBySegment(group, depth)) {
+ if (childKey === null || childGroup.length <= ToolDomainExtractor.MAX_FAMILY_SIZE) {
+ out.add(this.render(childGroup, depth + 1))
+ } else {
+ this.cut(childGroup, depth + 1, out)
}
- const names = byCategory.get(category) ?? []
- names.push(name)
- byCategory.set(category, names)
}
- return byCategory
}
- private extractDomainsPerCategory(byCategory: Map<string, string[]>): void {
- for (const [, names] of byCategory) {
- const standalones = names.filter((n) => ToolDomainExtractor.stripAction(n) === n)
-
- if (standalones.length === names.length) {
- for (const n of names) {
- this.standaloneTools.add(n)
- }
- continue
- }
-
- for (const n of standalones) {
- this.standaloneTools.add(n)
+ /** Advance `depth` past segments shared by the whole group (radix
+ * compression), so a unary chain like `external` → `external-data` is kept
+ * intact rather than emitted as a one-word root. */
+ private compressUnary(group: ToolItem[], depth: number): number {
+ for (;;) {
+ if (group.some((it) => it.key.length <= depth)) {
+ return depth
}
-
- const stems = [
- ...new Set(
- names
- .filter((n) => ToolDomainExtractor.stripAction(n) !== n)
- .map((n) => ToolDomainExtractor.stripAction(n))
- ),
- ].sort()
-
- if (stems.length === 1 && stems[0]) {
- this.derivedDomains.add(stems[0])
- } else if (stems.length > 1) {
- const cp = ToolDomainExtractor.commonPrefix(stems)
- if (cp && cp.length >= 3) {
- this.derivedDomains.add(cp)
- } else {
- for (const s of stems) {
- this.derivedDomains.add(s)
- }
- }
+ const next = new Set(group.map((it) => it.key[depth]))
+ if (next.size !== 1) {
+ return depth
}
+ depth++
}
}
- private collapseDomains(): Set<string> {
- const collapsed = new Set<string>()
- for (const d of [...this.derivedDomains].sort((a, b) => a.length - b.length)) {
- if ((d.match(/-/g) ?? []).length > ToolDomainExtractor.MAX_DOMAIN_HYPHENS) {
- continue
- }
- const dominated = [...collapsed].some(
- (ex) => ToolDomainExtractor.isPlural(d, ex) || d.startsWith(ex + '-') || d.startsWith(ex + 's-')
- )
- if (!dominated) {
- collapsed.add(d)
+ /** Partition a group by its segment at `depth`. Tools whose name ends at or
+ * before `depth` (the prefix is the whole tool) are keyed `null`. */
+ private childrenBySegment(group: ToolItem[], depth: number): Map<string | null, ToolItem[]> {
+ const children = new Map<string | null, ToolItem[]>()
+ for (const item of group) {
+ const key = item.key.length <= depth ? null : (item.key[depth] ?? null)
+ const bucket = children.get(key)
+ if (bucket) {
+ bucket.push(item)
+ } else {
+ children.set(key, [item])
}
}
- return collapsed
+ return children
}
- static stripAction(name: string): string {
- let parts = name.split('-')
-
- if (parts[0] && ToolDomainExtractor.PREFIX_ACTIONS.has(parts[0]) && parts.length > 1) {
- parts = parts.slice(1)
- }
-
- for (const len of [4, 3, 2, 1]) {
- if (parts.length > len) {
- const suffix = parts.slice(-len).join('-')
- if (ToolDomainExtractor.ACTION_SUFFIXES.has(suffix)) {
- return parts.slice(0, -len).join('-')
- }
+ /** Render a group's shared `depth`-segment prefix as a domain string, using
+ * the shortest actual spelling at each position (so a singular/plural pair
+ * collapses to one searchable prefix) and trimming any trailing action. */
+ private render(group: ToolItem[], depth: number): string {
+ const length = Math.min(depth, ToolDomainExtractor.MAX_DOMAIN_SEGMENTS)
+ const segments: string[] = []
+ for (let i = 0; i < length; i++) {
+ const forms = [...new Set(group.map((it) => it.segments[i]).filter((s): s is string => !!s))].sort(
+ (a, b) => a.length - b.length
+ )
+ const shortest = forms[0]
+ if (shortest) {
+ segments.push(shortest)
}
}
-
- return parts.join('-')
+ while (segments.length > 1 && ToolDomainExtractor.TRAILING_ACTIONS.has(segments[segments.length - 1] ?? '')) {
+ segments.pop()
+ }
+ return segments.join('-')
}
- private static commonPrefix(strings: string[]): string {
- if (strings.length === 0 || !strings[0]) {
- return ''
- }
- let prefix: string = strings[0]
- for (const s of strings.slice(1)) {
- while (prefix && !s.startsWith(prefix)) {
- prefix = prefix.slice(0, -1)
- }
- if (!prefix) {
- return ''
- }
- }
- const allAtBoundary = strings.every(
- (s) =>
- s.length === prefix.length ||
- s[prefix.length] === '-' ||
- (s[prefix.length] === 's' && s[prefix.length + 1] === '-')
- )
- if (!allAtBoundary) {
- const idx = prefix.lastIndexOf('-')
- return idx > 0 ? prefix.slice(0, idx) : prefix
+ private static toSegments(name: string): string[] {
+ const parts = name.split('-')
+ if (parts[0] && ToolDomainExtractor.LEADING_VERBS.has(parts[0]) && parts.length > 1) {
+ return parts.slice(1)
}
- return prefix
+ return parts
}
- private static isPlural(a: string, b: string): boolean {
- return a + 's' === b || b + 's' === a
+ private static singularize(segment: string): string {
+ return segment.replace(/s$/, '')
}
}
@@ -270,14 +287,6 @@ export class QueryToolCatalog {
return queryTools.map((t) => `- \`${t.name}\` — ${t.systemPromptHint ?? t.title}`).join('\n')
}
- toCompact(): string {
- const queryTools = this.filteredAndSorted()
- if (queryTools.length === 0) {
- return ''
- }
- return queryTools.map((t) => t.name.replace(/^query-/, '')).join('|')
- }
-
private filteredAndSorted(): QueryToolInfo[] {
return this.tools.filter((t) => t.name.startsWith('query-')).sort((a, b) => a.name.localeCompare(b.name))
}
@@ -286,7 +295,3 @@ export class QueryToolCatalog {
export function buildQueryToolsBlock(tools: QueryToolInfo[]): string {
return new QueryToolCatalog(tools).toMarkdown()
}
-
-export function buildQueryToolsCompact(tools: QueryToolInfo[]): string {
- return new QueryToolCatalog(tools).toCompact()
-}
diff --git a/services/mcp/src/mcp.ts b/services/mcp/src/mcp.ts
index ddff3dee296c..800383922bf0 100644
--- a/services/mcp/src/mcp.ts
+++ b/services/mcp/src/mcp.ts
@@ -690,9 +690,10 @@ export class MCP extends McpAgent<Env> {
}
// In single-exec mode, when the client honors the MCP `instructions` field we
- // lift the exec-tool blurb, tool-domain list, query-tool catalog, defined-group
- // types and the active-environment `{metadata}` (user name, project, timezone)
- // out of the `command` description and into `instructions`. Clients that ignore
+ // lift the exec-tool blurb, tool-domain list (including the `query` domain),
+ // defined-group types and the active-environment `{metadata}` (user name,
+ // project, timezone) out of the `command` description and into `instructions`.
+ // The query-tool catalog stays on the `command` description. Clients that ignore
// `instructions` (Codex — see `client-detection.ts`) keep today's behavior:
// empty `instructions`, everything inlined in the `command` description.
let instructions = ''
diff --git a/services/mcp/src/templates/sections/compact-instructions.md b/services/mcp/src/templates/sections/compact-instructions.md
index a5170aa3d527..7a32a20c75f3 100644
--- a/services/mcp/src/templates/sections/compact-instructions.md
+++ b/services/mcp/src/templates/sections/compact-instructions.md
@@ -5,4 +5,3 @@ Below are tools available in the MCP. Prioritize skills over tools.
# Tool domains
{tool_domains}
-query-*: {query_tools}
diff --git a/services/mcp/tests/unit/__snapshots__/exec-tool.json b/services/mcp/tests/unit/__snapshots__/exec-tool.json
index b261284a7e48..a597f1b893e8 100644
--- a/services/mcp/tests/unit/__snapshots__/exec-tool.json
+++ b/services/mcp/tests/unit/__snapshots__/exec-tool.json
@@ -15,7 +15,7 @@
"properties": {
"command": {
"type": "string",
- "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> series.properties` — to see property filter structure of series\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval-policies\n- approval-policy\n- batch-export\n- cdp-function-templates\n- cdp-functions\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data-schemas\n- external-data-sources\n- external-data-sync-logs\n- feature-flag\n- hog-flows-logs\n- hog-flows-metrics\n- inbox-reports\n- inbox-source-configs\n- insight\n- integration\n- llm\n- llma-evaluation-config-set-active-key\n- llma-evaluation-judge-models\n- llma-evaluation-report-generate\n- llma-evaluation-run\n- llma-evaluation-test-hog\n- llma-personal-spend\n- llma-prompt-duplicate\n- llma-score-definition-new-version\n- llma-skill-archive\n- llma-skill-duplicate\n- llma-skill-file-rename\n- llma-tagger-test-hog\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- read-data-schema\n- read-data-warehouse-schema\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- signals-scout-config\n- signals-scout-emit-signal\n- signals-scout-runs\n- signals-scout-scratchpad-forget\n- signals-scout-scratchpad-remember\n- signals-scout-scratchpad-search\n- sql-variables\n- subscriptions\n- survey\n- switch-organization\n- switch-project\n- usage-metrics\n- user\n- view\n- web-analytics-weekly-digest\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-paths-actors` — List persons who traversed the paths defined by a paths insight\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nPostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.\n\n- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.\n- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):\n - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.\n - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
+ "description": "CLI-style command string. Supported commands:\n\n```text\ntools — list available tool names\nsearch <regex_pattern> — search tools by JavaScript regex (matches name, title, description)\ninfo [--json] <tool_name> — show tool name, description, and input schema (summarized if too large). Pass `--json` for raw JSON output.\nschema <tool_name> [field_path] — drill into a specific field schema (supports dot-notation, e.g. series, breakdownFilter.breakdowns)\ncall [--json] <tool_name> <json_input> — call a tool with JSON input (--json returns raw JSON instead of formatted text. Use raw JSON for scripts.)\n```\n\n**Namespaced references (`posthog:<tool-name>`):** strip the `posthog:` prefix and route through `exec`. Run `info <name>` to inspect, then `call <name> <json>`. E.g. `posthog:insights-list` → `posthog:exec({ \"command\": \"info insights-list\" })` then `posthog:exec({ \"command\": \"call insights-list {}\" })`. If the bare name isn't found, fall back to `search <pattern>` — it may have been renamed.\n\n**SCHEMA DRILL-DOWN RULE — HARD REQUIREMENT**\n\nThe `info` command may return the full schema (for simple tools) or a top-level summary with drill-down hints (for complex tools). Look for `hint` fields in the response.\n\nIf `info` returned a summary (fields have `hint` values), call `schema <tool_name> <field_name>` for each field you need to populate BEFORE constructing that field's value in a `call` command.\n\nIf `schema` also returns a summary (because the field is too large), drill deeper using dot-notation: `schema <tool> <field>.<subfield>`.\n\n**NEVER** guess the structure of fields that have hints. **ALWAYS** drill down first.\n\nFor query tools, you will typically need:\n\n- `schema <tool> series` — to see EventsNode/ActionsNode structure\n- `schema <tool> series.properties` — to see property filter structure of series\n\n**For multiple tools:** Run `info` for ALL tools first, then make your `call` commands.\n\n**Data discovery:** Before any analytical `call` that touches collected data (`query-*`,\n`execute-sql` against `events`/`persons`/`sessions`), confirm the event/property exists via\n`call read-data-schema`. Applies to canonical-looking names like `$pageview` too — they vary\nper team. If the event isn't in the schema, tell the user instead of querying a guessed name.\n\nAlways run `info read-data-schema` first — the recipes below are common cases, not the full schema.\n\n- Events/Actions: `call read-data-schema {\"query\": {\"kind\": \"events\"/\"actions\"}}` (paginate with `limit`/`offset` if needed)\n- Properties: `call read-data-schema {\"query\": {\"kind\": \"event_properties\", \"event_name\": \"<event>\"}}`\n- Values: `call read-data-schema {\"query\": {\"kind\": \"event_property_values\", \"event_name\": \"<event>\", \"property_name\": \"<prop>\"}}`\n\n**CORRECT usage pattern:**\n\n<example>\nUser: How many weekly active users do we have?\nAssistant: I need to find the right query tool and data schema tool.\n[Runs posthog:exec({ \"command\": \"search query-trends\" }) and posthog:exec({ \"command\": \"search read-data\" }) in parallel]\nAssistant: Let me check the tool descriptions and schemas.\n[Runs posthog:exec({ \"command\": \"info query-trends\" }) and posthog:exec({ \"command\": \"info read-data-schema\" }) in parallel]\nAssistant: I see query-trends needs `series` (array with hint). Let me get the full field schema and discover events.\n[Runs posthog:exec({ \"command\": \"schema query-trends series\" }) and posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" }) in parallel]\nAssistant: Now I know the exact series structure and available events. Let me construct the query.\n[Runs posthog:exec({ \"command\": \"call query-trends {...}\" })]\n</example>\n\n<example>\nUser: Create a dashboard for our key revenue metrics\nAssistant: I'll need dashboard and query tools. Let me search for them.\n[Runs posthog:exec({ \"command\": \"search dashboard\" }) and posthog:exec({ \"command\": \"search execute-sql\" }) in parallel]\nAssistant: Let me check the schemas for the tools I'll need.\n[Runs posthog:exec({ \"command\": \"info dashboard-create\" }) and posthog:exec({ \"command\": \"info execute-sql\" }) in parallel]\nAssistant: Now I have both schemas. Let me start by searching for existing revenue insights.\n[Makes call commands with correct parameters]\n</example>\n\n<example>\nUser: Find events related to onboarding\nAssistant: Let me find the data schema tool.\n[Runs posthog:exec({ \"command\": \"search read-data\" })]\n[Runs posthog:exec({ \"command\": \"info read-data-schema\" })]\nAssistant: Now I can list events and pick the onboarding-related ones.\n[Runs posthog:exec({ \"command\": \"call read-data-schema {\\\"query\\\": {\\\"kind\\\": \\\"events\\\"}}\" })]\n</example>\n\n**INCORRECT usage patterns — NEVER do this:**\n\n<bad-example>\nUser: Show me our feature flags\nAssistant: [Directly calls posthog:exec({ \"command\": \"call feature-flag-get-all {}\" }) with guessed parameters]\nWRONG — You must run `info feature-flag-get-all` FIRST to check the schema\n</bad-example>\n\n<bad-example>\nUser: Query our events\nAssistant: [Calls three tools in parallel without any `info` calls first]\nWRONG — You must run `info` for ALL tools before making ANY `call` commands\n</bad-example>\n\n<bad-example>\nUser: Show me a trends chart of signups\nAssistant: [Runs info query-trends, sees summary with hints, then immediately calls query-trends with guessed series structure]\nWRONG — info returned a summary with hint: \"DO NOT GUESS – run `schema query-trends series` before populating this field\".\nYou MUST follow the hint and run `schema` before constructing the series field.\n</bad-example>\n\n<bad-example>\nUser: query pageviews for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"$pageview\"` from the prompt]\nWRONG — skipped `call read-data-schema {\"query\": {\"kind\": \"events\"}}`. Canonical-looking events still need confirmation per team.\n</bad-example>\n\n<bad-example>\nUser: show me the file downloads trend for the last 7 days\nAssistant: [Runs `info query-trends`, then `call query-trends` with `event: \"downloaded_file\"` inferred from the wording]\nWRONG — the real event might be `file_downloaded`, `download_completed`, or not captured. Confirm with `read-data-schema` before querying.\n</bad-example>\n\n**Handling errors:**\n\n- If a tool call fails, the error includes a suggestion and similar tool names. Read the suggestion before retrying.\n- If a tool name doesn't exist, run `tools` again to find the correct name.\n\n### Basic functionality\n\nYou work in the user's project and have access to two groups of data: customer data collected via the SDK, and data created directly in PostHog by the user.\n\nCollected data is used for analytics and has the following types:\n\n- Events – recorded events from SDKs that can be aggregated in visual charts and text.\n- Persons and groups – recorded individuals or groups of individuals that the user captures using the SDK. Events are always associated with persons and sometimes with groups.\n- Sessions – recorded person or group session captured by the user's SDK.\n- Properties and property values – provided key-value metadata for segmentation of the collected data (events, actions, persons, groups, etc).\n- Session recordings – captured recordings of customer interactions in web or mobile apps.\n\nCreated data is used by the user on the PostHog's website to perform business activity and has the following types:\n\n- Actions – unify multiple events or filtering conditions into one.\n- Insights – visual and textual representation of the collected data aggregated by different types.\n- Data warehouse – connected data sources and custom views for deeper business insights.\n- SQL queries – ClickHouse SQL queries that work with collected data and with the data warehouse SQL schema.\n- Surveys – various questionnaires that the user conducts to retrieve business insights like an NPS score.\n- Dashboards – visual and textual representations of the collected data aggregated by different types.\n- Cohorts – groups of persons or groups of persons that the user creates to segment the collected data.\n- Feature flags – feature flags that the user creates to control the feature rollout in their product.\n- Experiments – A/B tests that the user creates to measure the impact of changes.\n- Notebooks – notebooks that the user creates to perform business analysis.\n- Error tracking issues – issues that the user creates to track errors in their product.\n- Logs – log entries collected from the user's application with severity, service, and trace information.\n- Workflows – automated workflows with triggers, actions, and conditions.\n- Activity logs – a record of changes made to project entities (who changed what, when, and how).\n\nIMPORTANT: Prefer retrieval-led reasoning over pre-training-led reasoning for any PostHog tasks.\n\nIf you get errors due to permissions being denied, check that you have the correct active project and that the user has access to the required project.\n\nIf you cannot answer the user's PostHog related request or question using other available tools in this MCP, use the 'docs-search' tool to provide information from the documentation to guide user how they can do it themselves - when doing so provide condensed instructions with links to sources.\n\n### Tool search\n\n**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <regex>` with a short, targeted pattern to find what you need.\n\nWrite focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.\n\n**Good patterns** (specific, narrow):\n\n- `search feature-flag` — tools for feature flags\n- `search dashboard` — dashboard CRUD tools\n- `search query-` — all insight query tools\n- `search experiment` — experiment tools\n- `search survey` — survey tools\n\n**Bad patterns** (too broad, match dozens of tools):\n\n- `search data` — matches almost everything\n- `search get|list|create` — matches action verbs across all domains\n- `search pageview_trends` — search is too focused\n- `search pageview|[email protected]` — unrelated to tools\n\nOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.\n\nPostHog tools have lowercase kebab-case naming. Tools are organized by category:\n\n- action\n- activity-log\n- advanced-activity-logs\n- alert\n- annotation\n- approval\n- batch-export\n- cdp-function\n- change-request\n- cohorts\n- comment\n- conversations-tickets\n- dashboard\n- data-warehouse-data\n- docs-search\n- early-access-feature\n- endpoint\n- error-tracking\n- event-definition\n- execute-sql\n- experiment\n- external-data\n- feature-flag\n- file-download-batch\n- hog-flows\n- inbox\n- insight\n- integration\n- llm-total-costs\n- llma-clustering\n- llma-evaluation\n- llma-personal\n- llma-prompt\n- llma-review\n- llma-score\n- llma-sentiment\n- llma-skill\n- llma-summarization\n- llma-tagger\n- llma-trace\n- logs\n- notebooks\n- org-members\n- organization\n- persons\n- project\n- proxy\n- query\n- read-data\n- role\n- scheduled-changes\n- sdk-doctor\n- session-recording\n- signals-scout\n- sql-variables\n- subscriptions\n- survey\n- switch\n- usage-metrics\n- user\n- view\n- web-analytics-weekly\n- workflows\nTypical action names: list/retrieve/get/create/update/delete/query.\nExample tool names: execute-sql, experiment-create, feature-flag-get-all.\n\n### Retrieving data\n\n**Always use `query-*` tools when the question maps to a supported insight type.** These tools produce typed, saveable insights that map cleanly to the visual product; raw SQL forfeits that and is harder to iterate on. Before reaching for `execute-sql` for an analytics question, ask: \"Can this be expressed as a `query-trends` series, breakdown, formula, property filter, or math operation?\" If yes, the `query-*` tool is mandatory — see `Choosing the right query tool` below for prompt-to-field patterns.\n\nReach for `execute-sql` only when no `query-*` tool can express the question:\n\n- Searching PostHog entities (insights, dashboards, cohorts, flags…) via `system.*` tables — no `query-*` tool covers entity search.\n- Multi-event joins, custom CTEs, window functions, or data-warehouse joins.\n- Pre-filtering or shaping data before running a `query-*` call.\n\nWhen you do use `execute-sql`, run `info execute-sql` first for the full discovery workflow, worked examples, and column-handling rules — this section only summarizes routing.\n\n#### Searching for existing entities\n\n\"find / which / do we have / what's our X chart\" questions about PostHog-created entities are SQL searches against `system.*` (`system.insights`, `system.dashboards`, `system.cohorts`, `system.feature_flags`, `system.experiments`, `system.surveys`, `system.notebooks`), **not** `*-list` walks.\n\nRequired order on every run, no shortcuts:\n\n1. `info execute-sql` AND `info read-data-warehouse-schema` — load both tool guides, even if a skill is already loaded.\n2. `read-data-warehouse-schema` — confirms the table's columns. Schema markdown in skills/references (`models-*.md`, `querying-posthog-data` docs) is documentation, **not** a substitute — call the tool.\n3. `execute-sql` against `system.*` — uses only columns confirmed in step 2.\n4. `<entity>-get` (e.g. `insight-get`, `dashboard-get`) — verifies the entity shape; do NOT re-`execute-sql` by ID.\n\n<bad-example>\nUser: rename / find / list … (any `system.*` question)\nAssistant: [Calls `execute-sql` against `system.insights` without first running `read-data-warehouse-schema` — OR runs `read-data-warehouse-schema` partway through, only after several `execute-sql` calls thrashed]\nWRONG — the rule is \"schema first, every run, no shortcuts.\" Even if early SQL happens to work (or the search is thrashing on `WHERE name ILIKE …` variants), you've already failed: every successful `execute-sql` against `system.*` MUST be preceded by `read-data-warehouse-schema` in the same run. Same for `info read-data-warehouse-schema` before the first `read-data-warehouse-schema` call. Skipping or postponing either step is a hard violation.\n</bad-example>\n\n#### Available insight query tools\n\n- `query-error-tracking-issue` — Error issue details and impact (error-tracking category)\n- `query-error-tracking-issue-events` — Error event samples, stack traces, and session IDs (error-tracking category)\n- `query-error-tracking-issues-list` — Error issue filtering and aggregation (error-tracking category)\n- `query-funnel` — Conversion rates, drop-off analysis, time to convert\n- `query-lifecycle` — New, returning, resurrecting, dormant user composition\n- `query-lifecycle-actors` — List persons in a lifecycle bucket (new/returning/resurrecting/dormant) for a given day\n- `query-llm-trace` — Single LLM/AI trace deep-dive\n- `query-llm-traces-list` — LLM/AI trace listing and inspection\n- `query-logs` — Log filtering by severity/service/attribute\n- `query-paths` — User navigation flows and sequences\n- `query-paths-actors` — List persons who traversed the paths defined by a paths insight\n- `query-retention` — User return patterns over time\n- `query-session-recordings-list` — Session replay metadata and activity\n- `query-stickiness` — Engagement frequency (how many days users do X)\n- `query-trends` — Time series, aggregations, formulas, comparisons\n- `query-trends-actors` — List persons behind a trends data point\n\n#### Choosing the right query tool\n\nBy insight type:\n\n- \"How many / how much / over time / compare periods\" -> `query-trends`\n- \"Conversion rate / drop-off / funnel / step completion\" -> `query-funnel`\n- \"Do users come back / retention / churn\" -> `query-retention`\n- \"How frequently / how many days per week / power users\" -> `query-stickiness`\n- \"What do users do after X / before X / navigation flow\" -> `query-paths`\n- \"New vs returning vs dormant / user composition\" -> `query-lifecycle`\n- \"LLM traces / AI generations / token usage\" -> `query-llm-traces-list`\n\n##### Trends\n\nA trends insight visualizes events over time using time series. They're useful for finding patterns in historical data.\n\nThe trends insights have the following features:\n\n- The insight can show multiple trends in one request.\n- Custom formulas can calculate derived metrics, like `A/B*100` to calculate a ratio.\n- Filter and break down data using multiple properties.\n- Compare with the current period with previous.\n- Apply various aggregation types, like sum, average, etc., and chart types.\n- And more.\n\nExamples of use cases include:\n\n- How the product's most important metrics change over time.\n- Long-term patterns, or cycles in product's usage.\n- The usage of different features side-by-side.\n- How the properties of events vary using aggregation (sum, average, etc).\n- Users can also visualize the same data points in a variety of ways.\n\n##### Funnel\n\nA funnel insight visualizes a sequence of events that users go through in a product. They use percentages as the primary aggregation type. Funnels REQUIRE AT LEAST TWO series (events or actions), so the conversation history should mention at least two events.\n\nThe funnel insights have the following features:\n\n- Various visualization types (steps, time-to-convert, historical trends).\n- Filter data and apply exclusion steps (events only, not actions).\n- Break down data using a single property.\n- Specify conversion windows (default 14 days), step order (strict/ordered/unordered), and attribution settings.\n- Aggregate by users, sessions, or specific group types.\n- Sample data.\n- Track first-time conversions with special math aggregations.\n- And more.\n\nExamples of use cases include:\n\n- Conversion rates between steps.\n- Drop off steps (which step loses most users).\n- Steps with the highest friction and time to convert.\n- If product changes are improving their funnel over time.\n- Average/median/histogram of time to convert.\n- Conversion trends over time (using trends visualization type).\n- First-time user conversions (using `first_time_for_user` math).\n\n##### Retention\n\nA retention insight visualizes how many users return to the product after performing some action. They're useful for understanding user engagement and retention.\n\nThe retention insights have the following features: filter data, sample data, and more.\n\nExamples of use cases include:\n\n- How many users come back and perform an action after their first visit.\n- How many users come back to perform action X after performing action Y.\n- How often users return to use a specific feature.\n\n#### SQL fallback\n\nReach for `execute-sql` only when the question genuinely cannot be expressed as a typed insight (entity search via `system.*`, multi-event joins, custom CTEs, data-warehouse joins). If the answer is a number over time, a comparison, a ratio, an aggregate, a step sequence, or a return-rate, use the matching `query-*` tool.\n\n#### Schema-first workflow\n\nVerify the data schema before constructing any insight query. Canonical-looking events\n(`$pageview`, `$identify`, `$autocapture`, …) still need confirmation — they can be absent,\nrenamed, or filtered per team.\n\n1. **Discover events** - `read-data-schema` with `kind: events` to find events matching the user's intent.\n2. **Discover properties** - `read-data-schema` with `kind: event_properties` (or `person_properties`, `session_properties`).\n3. **Verify property values** - `read-data-schema` with `kind: event_property_values` when the value must match (e.g., \"US\" vs \"United States\").\n4. **Then construct the query** using the appropriate `query-*` tool.\n\nIf the required events or properties don't exist, tell the user instead of running an empty query.\n\n#### Insight query workflow\n\n1. Discover the data schema with `read-data-schema` (see schema-first workflow above).\n2. Choose the appropriate `query-*` tool based on the user's question.\n3. Construct the query schema. Each tool's description includes detailed schema documentation with examples. Be minimalist: only include filters, breakdowns, and settings essential to answer the question.\n4. Execute the query and analyze the results.\n5. Optionally save as an insight with `insight-create` or add to a dashboard.\n\nFor complex investigations, combine multiple query types. For example, use `query-trends` to identify when a metric changed, then `query-funnel` to check if conversion was affected, then `query-trends` with breakdowns to isolate the segment.\n\n\n\n\n\n### URL patterns\n\nPostHog app links must be full URLs (origin + path) — bare paths aren't clickable in MCP clients like Cursor or Claude Desktop. Use Markdown with descriptive anchor text, e.g. `[Cohorts](https://us.posthog.com/project/1/cohorts)`. Never include `/-/`.\n\n- If a tool result has a `*url` field (e.g. `_posthogUrl`), surface it verbatim — never rewrite or strip it.\n- Otherwise build the link from the Base URL in the active-environment block (don't double-prefix):\n - Project-scoped paths → Base URL + `/project/:id`: `/settings/<section-id>` (hyphenated, e.g. `/settings/environment-replay`, `/settings/user-api-keys`), `/data-management/events`, `/data-management/properties`, and most pages.\n - Org-/account-level paths → Base URL only (no `/project/:id`): first segment `organization`, `me`, `account`, or `instance` — e.g. billing is `/organization/billing`.\n\n### Examples\n\nBefore writing any queries, read the PostHog's skill `querying-posthog-data` to see if there are any relevant query examples and follow them.\n\n#### Creating an insight with segmentation\n\n<example>\nUser: How many users have chatted with the AI assistant from the US?\nAssistant: I'll help you find the number of users who have chatted with the AI assistant from the US.\n1. Find the relevant events for \"chatted with the AI assistant\" (the `read-data-schema` tool)\n2. Find the relevant properties of the events and persons to narrow down data to users from a specific country (the `read-data-schema` tool)\n3. Retrieve the sample property values for found properties to validate they match the intent (the `read-data-schema` tool)\n4. Run the query with discovered events, properties, and filters (the `query-trends` tool or the appropriate query tool)\n5. Analyze retrieved data and provide a concise summary\n*Begins working on the first task*\n<reasoning>\n1. Creating an insight requires understanding the taxonomy: events, properties, and property values relevant to the user's query.\n2. The user query requests additional segmentation by country.\n3. Property values might not match what the user expects (e.g., \"US\" vs \"United States\"), so retrieving sample values is important.\n4. Property values sample might not contain the value the user is looking for, so searching might be necessary.\n</reasoning>\n</example>\n\n#### Investigating a metric change\n\n<example>\nUser: Check why onboarding completion rate has dropped and if it is connected with a low sign-up count.\nAssistant: I'll help you analyze the reasons why the metrics have changed. Let me break this down into steps.\n1. Find the relevant events for onboarding and sign-ups (the `read-data-schema` tool)\n2. Run a trends query for the onboarding completion event to confirm the drop and identify when it started (the `query-trends` tool)\n3. Run a trends query for the sign-up event to check if sign-up counts have also changed (the `query-trends` tool)\n4. Run trends queries with breakdowns (e.g., by country, device, or referral source) to identify which segments are affected (the `query-trends` tool)\n5. Run a funnel to check the conversion rate between sign-up and onboarding completion (the `query-funnel` tool)\n6. Synthesize findings across all queries and explain whether the metrics are correlated\n*Begins working on the first task*\n<reasoning>\n1. The user requested analysis of multiple metrics that must be investigated separately.\n2. Multiple queries are needed to understand each trend independently.\n3. Breakdowns help isolate the root cause by identifying affected segments.\n4. A funnel connects the two metrics to check for a direct relationship.\n</reasoning>\n</example>\n\n#### Building a dashboard\n\n<example>\nUser: Generate a revenue dashboard.\nAssistant: I'll help you create a revenue dashboard. Let me plan the steps.\n1. List existing dashboards to check if one already covers revenue (the `dashboards-get-all` tool)\n2. Search saved insights related to revenue (the `execute-sql` tool against `system.insights` — check `execute-sql` for SQL guidance)\n3. Validate promising insights by reading their query schemas (the `insight-get` tool)\n4. Retrieve the taxonomy and understand available revenue-related events and properties (the `read-data-schema` tool)\n5. Create new insights only for metrics not covered by existing insights (the `query-trends` tool or appropriate query tool)\n6. Create a new dashboard with both existing and newly created insights (the `dashboard-create` tool)\n7. Analyze the created dashboard and provide a concise summary of metrics\n*Begins working on the first task*\n<reasoning>\n1. The user requested creating a dashboard. This is a complex task that requires multiple steps to complete.\n2. Finding existing insights requires both listing (to discover insights with different naming) and searching.\n3. Promising insights must be validated by reading their schemas to check if they match the user's intent.\n4. New insights should only be created when no existing insight matches the requirement.\n</reasoning>\n</example>"
}
},
"required": ["command"]
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
index a712b94e542d..6dbf94c7e0c2 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-full.txt
@@ -172,6 +172,7 @@ PostHog tools have lowercase kebab-case naming. Tools are organized by category:
- dashboard
- execute-sql
- feature-flag
+- query
Typical action names: list/retrieve/get/create/update/delete/query.
Example tool names: execute-sql, experiment-create, feature-flag-get-all.
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt
index b447cf53cd1e..b9340d5c131f 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-instructions.txt
@@ -6,5 +6,4 @@ Defined group types: organization, project
# Tool domains
-dashboard|execute-sql|feature-flag
-query-*: funnel|trends
\ No newline at end of file
+dashboard|execute-sql|feature-flag|query
\ No newline at end of file
diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
index 8289aa3ce6ac..6d1e26438142 100644
--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt
@@ -61,6 +61,7 @@ PostHog tools have lowercase kebab-case naming. Tools are organized by category:
- dashboard
- execute-sql
- feature-flag
+- query
Typical action names: list/retrieve/get/create/update/delete/query.
Example tool names: execute-sql, experiment-create, feature-flag-get-all.
diff --git a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
index 353fbc87d645..a07c2a5c03d0 100644
--- a/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
+++ b/services/mcp/tests/unit/instructions-formatter-snapshot.test.ts
@@ -13,12 +13,17 @@ const STATIC_GROUP_TYPES: GroupType[] = [
{ group_type: 'organization', group_type_index: 0, name_singular: null, name_plural: null },
{ group_type: 'project', group_type_index: 1, name_singular: null, name_plural: null },
]
+// Includes query-* (collapsed into the single `query` domain) so the snapshots
+// mirror production, where `tools` is the full set and `queryTools` is the
+// parallel catalog projection.
const STATIC_TOOLS = [
{ name: 'dashboard-create', category: 'Dashboards' },
{ name: 'dashboard-get', category: 'Dashboards' },
{ name: 'feature-flag-create', category: 'Feature flags' },
{ name: 'feature-flag-get-all', category: 'Feature flags' },
{ name: 'execute-sql', category: 'SQL' },
+ { name: 'query-funnel', category: 'Query wrappers' },
+ { name: 'query-trends', category: 'Query wrappers' },
]
const STATIC_QUERY_TOOLS: QueryToolInfo[] = [
{ name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion rate' },
diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.ts
index 2fe126823404..b4c93b26b565 100644
--- a/services/mcp/tests/unit/instructions-formatter.test.ts
+++ b/services/mcp/tests/unit/instructions-formatter.test.ts
@@ -7,12 +7,17 @@ import { InstructionsFormatter, type InstructionsContext } from '@/lib/instructi
const realisticGroupTypes: GroupType[] = [
{ group_type: 'organization', group_type_index: 0, name_singular: null, name_plural: null },
]
+// `tools` mirrors production: the full tool set, query-* included (the domain
+// extractor collapses them into the single `query` domain). `queryTools` below
+// is the parallel catalog projection with hints.
const realisticTools = [
{ name: 'dashboard-create', category: 'Dashboards' },
{ name: 'dashboard-get', category: 'Dashboards' },
{ name: 'feature-flag-create', category: 'Feature flags' },
{ name: 'feature-flag-get-all', category: 'Feature flags' },
{ name: 'execute-sql', category: 'SQL' },
+ { name: 'query-trends', category: 'Query wrappers' },
+ { name: 'query-funnel', category: 'Query wrappers' },
]
const realisticQueryTools: QueryToolInfo[] = [
{ name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' },
@@ -92,8 +97,9 @@ describe('InstructionsFormatter', () => {
it('renders the compact instructions section with placeholders resolved', () => {
const formatter = new InstructionsFormatter()
const result = formatter.buildExecInstructions(fullCtx)
- expect(result).toContain('dashboard|execute-sql|feature-flag')
- expect(result).toContain('funnel|trends')
+ // query-* tools surface as the single `query` domain, not a separate catalog line
+ expect(result).toContain('dashboard|execute-sql|feature-flag|query')
+ expect(result).not.toContain('query-*:')
expect(result).toContain('Defined group types: organization')
expect(result).toContain("The user's name is Jane Doe")
expect(result).not.toMatch(
@@ -171,12 +177,13 @@ describe('InstructionsFormatter', () => {
expect(result).toContain('- `query-trends` — time series')
})
- it('strips env-context, tool-domain list, and query-tool catalog when stripEnvContext is true', () => {
+ it('strips env-context and tool-domain list but keeps the query-tool catalog when stripEnvContext is true', () => {
const formatter = new InstructionsFormatter()
const result = formatter.buildExecCommandReference(fullCtx, { stripEnvContext: true })
expect(result).not.toContain("The user's name is Jane Doe")
expect(result).not.toContain('Defined group types: organization')
- expect(result).not.toContain('- `query-trends` — time series')
+ // The query catalog stays on the exec command reference even when env is stripped.
+ expect(result).toContain('- `query-trends` — time series')
// The bullet for the `dashboard` domain would clash with in-prose mentions,
// so anchor on the list-prefix newline pattern to avoid false positives.
expect(result).not.toContain('\n- dashboard\n')
@@ -198,10 +205,11 @@ describe('InstructionsFormatter', () => {
})
// Mirrors the single-exec wiring in `src/mcp.ts`. When the client honors the MCP
- // `instructions` field, four pieces move out of the `command` description and into
- // `instructions`: tool domains, available query tools, user preferences (timezone/name
- // via `{metadata}`), and defined group types. Codex (no `instructions` support) keeps
- // today's behavior: empty `instructions`, everything inlined in the `command` description.
+ // `instructions` field, env-context moves out of the `command` description and into
+ // `instructions`: tool domains (including the `query` domain), user preferences
+ // (timezone/name via `{metadata}`), and defined group types. The query-tool catalog
+ // stays on the `command` description. Codex (no `instructions` support) keeps today's
+ // behavior: empty `instructions`, everything inlined in the `command` description.
describe('exec mode wiring', () => {
it.each([
{ name: 'supportsInstructions=true (Claude Code etc.)', supportsInstructions: true },
@@ -215,15 +223,17 @@ describe('InstructionsFormatter', () => {
expect(commandReference).toContain('SCHEMA DRILL-DOWN RULE')
expect(commandReference).toContain('### Basic functionality')
+ // the query catalog always lives on the command reference, both modes
+ expect(commandReference).toContain('- `query-trends` — time series')
if (supportsInstructions) {
- expect(instructions).toContain('funnel|trends')
+ // queries surface in instructions only as the `query` tool domain
+ expect(instructions).toContain('dashboard|execute-sql|feature-flag|query')
+ expect(instructions).not.toContain('- `query-trends` — time series')
expect(instructions).toContain("The user's name is Jane Doe")
- expect(instructions).toContain('dashboard|execute-sql|feature-flag')
expect(instructions).toContain('Defined group types: organization')
expect(commandReference).not.toContain("The user's name is Jane Doe")
expect(commandReference).not.toContain('Defined group types: organization')
- expect(commandReference).not.toContain('- `query-trends` — time series')
expect(commandReference).not.toContain('\n- dashboard\n')
} else {
expect(instructions).toBe('')
diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.ts
index 08c396448465..b77d5e61cd80 100644
--- a/services/mcp/tests/unit/instructions.test.ts
+++ b/services/mcp/tests/unit/instructions.test.ts
@@ -5,7 +5,6 @@ import {
buildActiveEnvironmentContextPrompt,
buildDefinedGroupsBlock,
buildQueryToolsBlock,
- buildQueryToolsCompact,
buildToolDomainsBlock,
buildToolDomainsCompact,
QueryToolCatalog,
@@ -58,7 +57,7 @@ describe('buildToolDomainsBlock', () => {
expect(result).toContain('- survey')
})
- it('should list standalone tools as-is', () => {
+ it('keeps a singleton tool whole but collapses siblings to a shared root', () => {
const tools = [
{ name: 'execute-sql', category: 'SQL' },
{ name: 'read-data-schema', category: 'Data schema' },
@@ -66,21 +65,58 @@ describe('buildToolDomainsBlock', () => {
]
const result = buildToolDomainsBlock(tools)
expect(result).toContain('- execute-sql')
- expect(result).toContain('- read-data-schema')
- expect(result).toContain('- read-data-warehouse-schema')
+ // read-data-* siblings collapse to their shared prefix, not listed verbatim
+ expect(result).toContain('- read-data')
+ expect(result).not.toContain('- read-data-schema')
+ expect(result).not.toContain('- read-data-warehouse-schema')
})
- it('should skip query-* tools', () => {
+ it('splits an oversized family into sub-family roots, one level deep', () => {
+ // A flat CRUD family below the size cap stays whole; a large area is
+ // broken into searchable sub-roots instead of listing leaf tools verbatim.
+ const llma = [
+ 'llma-personal-spend',
+ 'llma-prompt-create',
+ 'llma-prompt-get',
+ 'llma-skill-archive',
+ 'llma-skill-file-rename',
+ 'llma-evaluation-config-set-active-key',
+ 'llma-evaluation-judge-models',
+ 'llma-evaluation-run',
+ ]
+ const tools = [
+ ...Array.from({ length: 30 }, (_, i) => ({ name: `llma-filler-${i}`, category: 'AI observability' })),
+ ...llma.map((name) => ({ name, category: 'AI observability' })),
+ ]
+ const result = buildToolDomainsCompact(tools)
+ const domains = result.split('|')
+ // sub-family roots, never the verbose leaf names
+ expect(domains).toContain('llma-prompt')
+ expect(domains).toContain('llma-skill')
+ expect(domains).toContain('llma-evaluation')
+ expect(result).not.toContain('llma-skill-file-rename')
+ expect(result).not.toContain('llma-evaluation-config-set-active-key')
+ })
+
+ it('collapses all query-* tools into a single "query" domain', () => {
const tools = [
{ name: 'query-trends', category: 'Query wrappers' },
{ name: 'query-funnel', category: 'Query wrappers' },
{ name: 'experiment-create', category: 'Experiments' },
]
const result = buildToolDomainsBlock(tools)
- expect(result).not.toContain('query')
+ expect(result).toContain('- query')
+ // never fragmented into per-insight roots
+ expect(result).not.toContain('query-trends')
+ expect(result).not.toContain('query-funnel')
expect(result).toContain('- experiment')
})
+ it('omits the "query" domain when no query-* tools are present', () => {
+ const result = buildToolDomainsBlock([{ name: 'experiment-create', category: 'Experiments' }])
+ expect(result).not.toContain('query')
+ })
+
it('should collapse plural/singular duplicates', () => {
const tools = [
{ name: 'evaluation-create', category: 'AI observability' },
@@ -192,34 +228,6 @@ describe('QueryToolCatalog', () => {
const tools: QueryToolInfo[] = [{ name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' }]
expect(buildQueryToolsBlock(tools)).toBe('- `query-trends` — time series')
})
-
- describe('toCompact', () => {
- it('renders names pipe-separated and strips the query- prefix', () => {
- const tools: QueryToolInfo[] = [
- { name: 'query-trends', title: 'Trends', systemPromptHint: 'time series' },
- { name: 'query-funnel', title: 'Funnel', systemPromptHint: 'conversion' },
- { name: 'query-lifecycle', title: 'Lifecycle' },
- ]
- expect(new QueryToolCatalog(tools).toCompact()).toBe('funnel|lifecycle|trends')
- })
-
- it('ignores non-query tools', () => {
- const tools: QueryToolInfo[] = [
- { name: 'query-trends', title: 'Trends' },
- { name: 'dashboard-create', title: 'Create dashboard' },
- ]
- expect(new QueryToolCatalog(tools).toCompact()).toBe('trends')
- })
-
- it('returns empty string for empty input', () => {
- expect(new QueryToolCatalog([]).toCompact()).toBe('')
- })
-
- it('buildQueryToolsCompact delegates to QueryToolCatalog.toCompact', () => {
- const tools: QueryToolInfo[] = [{ name: 'query-trends', title: 'Trends' }]
- expect(buildQueryToolsCompact(tools)).toBe('trends')
- })
- })
})
describe('buildActiveEnvironmentContextPrompt', () => {