:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): make exec search forgiving with token ranking (#65987)
Thomas Obermüller6761cea5e288
diff --git a/services/mcp/src/templates/sections/tool-search.md b/services/mcp/src/templates/sections/tool-search.mdindex c9d8dacee4c3..98a3bf1e4fd8 100644--- a/services/mcp/src/templates/sections/tool-search.md+++ b/services/mcp/src/templates/sections/tool-search.md@@ -1,22 +1,25 @@### Tool search-**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.+**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <query>` to find what you need.-Write focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.+`search` understands two kinds of query:-**Good patterns** (specific, narrow):+- **Plain words** (including multiple words / natural language) — ranked by relevance across tool name, title, and description, with name matches weighted highest. `search create dashboard insight` surfaces `dashboard-create` / `insight-create` at the top. Results are capped to the top matches; narrow the query if you see a truncation note.+- **Regex** — a query containing regex metacharacters (`- | ( ) [ ] \ . * + ^ $ ?`) is treated as a single case-insensitive regular expression, matched against name/title/description. Use this for precise, narrow patterns.-- `search feature-flag` — tools for feature flags+**Good queries:**++- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools first+- `search feature-flag` — regex (`-`): tools for feature flags- `search dashboard` — dashboard CRUD tools-- `search query-` — all insight query tools+- `search query-` — regex (`-`): all insight query tools- `search experiment` — experiment tools- `search survey` — survey tools-**Bad patterns** (too broad, match dozens of tools):+**Avoid queries that are too broad** (match dozens of tools):- `search data` — matches almost everything-- `search get|list|create` — matches action verbs across all domains-- `search pageview_trends` — search is too focused+- `search get list create` — action verbs across all domains- `search pageview|[email protected]` — unrelated to toolsOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 8ee01efb09cd..cfccfd517326 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -9,6 +9,7 @@ import { formatResponse } from '@/lib/response'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'import type { ScopeGatedTool } from './toolDefinitions'+import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'import {POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY,POSTHOG_META_KEY,@@ -21,6 +22,10 @@ import {* forcing catastrophic backtracking against tool metadata. */const MAX_SEARCH_PATTERN_LENGTH = 200+/** Ranked (plain-word) search can match loosely on a common token like+ * "create"; cap the returned names so a vague query can't dump the catalog. */+const MAX_RANKED_SEARCH_RESULTS = 25+type ExecSchema = ReturnType<typeof makeExecSchema>export interface ExecInnerCallProperties {@@ -225,7 +230,7 @@ export function createExecTool(case 'search': {if (!rest) {- throw new Error('Usage: search <regex_pattern>')+ throw new Error('Usage: search <words or regex_pattern>')}// Bound the user-supplied pattern length to limit the blast// radius of a pathological (catastrophic-backtracking) regex.@@ -234,18 +239,33 @@ export function createExecTool(`Search pattern too long (${rest.length} chars, max ${MAX_SEARCH_PATTERN_LENGTH}). Use a shorter, more targeted pattern.`)}- let regex: RegExp- try {- regex = new RegExp(rest, 'i')- } catch {- throw new Error(`Invalid regex pattern: "${rest}"`)++ // Route by pattern shape: a pattern with regex metacharacters+ // (e.g. `query-`, `feature-flag`) keeps the original regex+ // predicate; plain words — including multi-word, natural-+ // language queries — use forgiving token ranking.+ let matches: string[]+ let gatedMatches: ScopeGatedTool[]+ let truncatedFrom = 0+ if (isRegexPattern(rest)) {+ try {+ matches = searchToolsRegex(allTools, rest).map((t) => t.name)+ gatedMatches = searchToolsRegex(scopeGatedTools, rest)+ } catch {+ throw new Error(`Invalid regex pattern: "${rest}"`)+ }+ } else {+ const ranked = searchToolsRanked(allTools, rest)+ truncatedFrom = ranked.length > MAX_RANKED_SEARCH_RESULTS ? ranked.length : 0+ matches = ranked.slice(0, MAX_RANKED_SEARCH_RESULTS).map((r) => r.name)+ // Preserve ranked order for gated matches too, then map+ // each name back to its ScopeGatedTool (for missingScopes).+ const gatedByName = new Map(scopeGatedTools.map((t) => [t.name, t]))+ gatedMatches = searchToolsRanked(scopeGatedTools, rest)+ .map((r) => gatedByName.get(r.name))+ .filter((t): t is ScopeGatedTool => t !== undefined)}- const matches = allTools- .filter((t) => regex.test(t.name) || regex.test(t.title) || regex.test(t.description))- .map((t) => t.name)- const gatedMatches = scopeGatedTools.filter(- (t) => regex.test(t.name) || regex.test(t.title) || regex.test(t.description)- )+if (gatedMatches.length > 0) {const requiredScopes = [...new Set(gatedMatches.flatMap((t) => t.missingScopes))].sort()return JSON.stringify({@@ -265,6 +285,13 @@ export function createExecTool(hint: `No tools matched "${rest}". Run "tools" to see all available tool names.`,})}+ if (truncatedFrom > 0) {+ return JSON.stringify({+ matches,+ truncated: true,+ hint: `Showing the top ${MAX_RANKED_SEARCH_RESULTS} of ${truncatedFrom} matches, ranked by relevance. Use a more specific query to narrow the results.`,+ })+ }return JSON.stringify(matches)}diff --git a/services/mcp/src/tools/tool-search.ts b/services/mcp/src/tools/tool-search.tsnew file mode 100644index 000000000000..4f0a252da9e3--- /dev/null+++ b/services/mcp/src/tools/tool-search.ts@@ -0,0 +1,102 @@+/**+ * Tool-search logic for `exec search` (src/tools/exec.ts).+ *+ * Two strategies live here:+ *+ * - searchToolsRegex — the original `exec search` predicate: one+ * case-insensitive RegExp tested against name/title/description.+ * - searchToolsRanked — a forgiving, field-weighted token ranking so+ * multi-word natural-language queries ("create dashboard insight") surface+ * the relevant tools instead of matching nothing.+ *+ * Callers route between them via `isRegexPattern`.+ */++/** Minimal structural shape both searches operate on. The runtime `Tool` and+ * the catalog's `ScopeGatedTool` both satisfy it, so a single signature serves+ * every caller. */+export interface SearchableTool {+ name: string+ title: string+ description: string+}++/** A match in a tool's name outweighs the same token in its title, which in+ * turn outweighs a hit buried in the description. */+const SEARCH_FIELD_WEIGHT = { name: 3, title: 2, description: 1 } as const+export type SearchField = keyof typeof SEARCH_FIELD_WEIGHT++/** Fields in descending weight — a token is counted once, at its highest-weight+ * field, so a name hit doesn't also score for a description mention. */+const ORDERED_FIELDS: readonly SearchField[] = ['name', 'title', 'description']++export interface RankedToolMatch {+ name: string+ /** Distinct query tokens found in any field — the relevance signal a tie+ * breaks on after the weighted score. */+ tokensMatched: number+ /** Field-weighted score; the primary ranking key. */+ score: number+ /** Which fields contributed, for debug/inspection output. */+ fields: SearchField[]+}++/** Regex metacharacters that mark a pattern as a deliberate regex rather than+ * plain words. A pattern containing any of these routes to `searchToolsRegex`+ * (preserving power-user patterns like `query-` or `feature-flag`); everything+ * else routes to `searchToolsRanked`. */+const REGEX_METACHARACTER = /[-|()[\]\\.*+^$?]/++export function isRegexPattern(pattern: string): boolean {+ return REGEX_METACHARACTER.test(pattern)+}++/** The original `exec search` predicate, verbatim: a single case-insensitive+ * RegExp tested against each tool's name, title, and description. Throws if the+ * pattern is not a valid regex — callers surface their own error message. */+export function searchToolsRegex<T extends SearchableTool>(tools: readonly T[], pattern: string): T[] {+ const regex = new RegExp(pattern, 'i')+ return tools.filter((t) => regex.test(t.name) || regex.test(t.title) || regex.test(t.description))+}++/** Forgiving, field-weighted token search. Splits the query on whitespace and+ * ranks each tool by a weighted score over the distinct query tokens it+ * contains, so a multi-word intent like "create dashboard insight" surfaces+ * dashboard-create / insight-create instead of returning nothing. Results are+ * sorted by score, then by distinct token coverage, then by name. */+export function searchToolsRanked<T extends SearchableTool>(tools: readonly T[], query: string): RankedToolMatch[] {+ const tokens = [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))]+ if (tokens.length === 0) {+ return []+ }+ const scored: RankedToolMatch[] = []+ for (const t of tools) {+ const haystack: Record<SearchField, string> = {+ name: t.name.toLowerCase(),+ title: t.title.toLowerCase(),+ description: t.description.toLowerCase(),+ }+ let tokensMatched = 0+ let score = 0+ const fields = new Set<SearchField>()+ for (const token of tokens) {+ // Count each token once, at its highest-weight field, so a token in+ // the name outweighs the same token buried in a description.+ const field = ORDERED_FIELDS.find((f) => haystack[f].includes(token))+ if (field) {+ tokensMatched += 1+ score += SEARCH_FIELD_WEIGHT[field]+ fields.add(field)+ }+ }+ if (tokensMatched > 0) {+ scored.push({ name: t.name, tokensMatched, score, fields: [...fields] })+ }+ }+ // Field-weighted score first: a token in the tool name beats the same token+ // buried in a description, so dashboard-create outranks a tool that merely+ // mentions "create"/"dashboard"/"insight" in prose. Token coverage breaks+ // ties, then name for a stable order.+ scored.sort((a, b) => b.score - a.score || b.tokensMatched - a.tokensMatched || a.name.localeCompare(b.name))+ return scored+}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.txtindex 042eecaf8253..33846bd801bd 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@@ -171,23 +171,26 @@ If you cannot answer the user's PostHog related request or question using other### Tool search-**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.+**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <query>` to find what you need.-Write focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.+`search` understands two kinds of query:-**Good patterns** (specific, narrow):+- **Plain words** (including multiple words / natural language) — ranked by relevance across tool name, title, and description, with name matches weighted highest. `search create dashboard insight` surfaces `dashboard-create` / `insight-create` at the top. Results are capped to the top matches; narrow the query if you see a truncation note.+- **Regex** — a query containing regex metacharacters (`- | ( ) [ ] \ . * + ^ $ ?`) is treated as a single case-insensitive regular expression, matched against name/title/description. Use this for precise, narrow patterns.-- `search feature-flag` — tools for feature flags+**Good queries:**++- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools first+- `search feature-flag` — regex (`-`): tools for feature flags- `search dashboard` — dashboard CRUD tools-- `search query-` — all insight query tools+- `search query-` — regex (`-`): all insight query tools- `search experiment` — experiment tools- `search survey` — survey tools-**Bad patterns** (too broad, match dozens of tools):+**Avoid queries that are too broad** (match dozens of tools):- `search data` — matches almost everything-- `search get|list|create` — matches action verbs across all domains-- `search pageview_trends` — search is too focused+- `search get list create` — action verbs across all domains- `search pageview|[email protected]` — unrelated to toolsOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.diff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txtindex 9cada8e5a43a..48d345ebe2de 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt@@ -35,23 +35,26 @@ If you cannot answer the user's PostHog related request or question using other### Tool search-**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.+**Always prefer `search` over `tools`** — `tools` returns every tool and wastes tokens. Use `search <query>` to find what you need.-Write focused patterns that match 1-5 tools. The regex matches against tool name, title, and description.+`search` understands two kinds of query:-**Good patterns** (specific, narrow):+- **Plain words** (including multiple words / natural language) — ranked by relevance across tool name, title, and description, with name matches weighted highest. `search create dashboard insight` surfaces `dashboard-create` / `insight-create` at the top. Results are capped to the top matches; narrow the query if you see a truncation note.+- **Regex** — a query containing regex metacharacters (`- | ( ) [ ] \ . * + ^ $ ?`) is treated as a single case-insensitive regular expression, matched against name/title/description. Use this for precise, narrow patterns.-- `search feature-flag` — tools for feature flags+**Good queries:**++- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools first+- `search feature-flag` — regex (`-`): tools for feature flags- `search dashboard` — dashboard CRUD tools-- `search query-` — all insight query tools+- `search query-` — regex (`-`): all insight query tools- `search experiment` — experiment tools- `search survey` — survey tools-**Bad patterns** (too broad, match dozens of tools):+**Avoid queries that are too broad** (match dozens of tools):- `search data` — matches almost everything-- `search get|list|create` — matches action verbs across all domains-- `search pageview_trends` — search is too focused+- `search get list create` — action verbs across all domains- `search pageview|[email protected]` — unrelated to toolsOnly fall back to `tools` if you have no idea which domain to search, or if `search` returns no results.diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 2dc29f1e143c..49730906932d 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -781,6 +781,58 @@ describe('exec tool', () => {const result = await exec.handler(mockContext, { command: 'search feature-flag' })expect(JSON.parse(result as string)).toEqual(['feature-flag-get-all'])})++ it('ranks tools for a multi-word plain-language query that a single regex would miss', async () => {+ // /create dashboard insight/i matches no tool literally; routing to+ // ranked search is the whole point of this command.+ const tools = [+ makeMockTool({ name: 'dashboard-create', title: 'Create dashboard' }),+ makeMockTool({ name: 'insight-create', title: 'Create insight' }),+ makeMockTool({ name: 'feature-flag-get-all', title: 'List feature flags' }),+ ]+ const exec = createExec(tools)+ const result = JSON.parse(+ (await exec.handler(mockContext, { command: 'search create dashboard insight' })) as string+ )+ expect(Array.isArray(result)).toBe(true)+ expect(result.slice(0, 2)).toEqual(['dashboard-create', 'insight-create'])+ })++ it('surfaces scope-gated tools for a plain-language query', async () => {+ const exec = createExecTool([makeMockTool()], mockContext, 'desc', 'cmd', undefined, undefined, [+ {+ name: 'experiment-create',+ title: 'Create experiment',+ description: 'Create a new experiment',+ missingScopes: ['experiment:write'],+ },+ ])+ const result = JSON.parse(+ (await exec.handler(mockContext, { command: 'search create experiment' })) as string+ )+ expect(result.scope_gated_matches).toEqual([+ { name: 'experiment-create', missing_scopes: ['experiment:write'] },+ ])+ expect(result.hint).toContain('experiment:write')+ })++ it('caps ranked results and notes truncation', async () => {+ const tools = Array.from({ length: 30 }, (_, i) =>+ makeMockTool({ name: `dashboard-tool-${i}`, title: `Dashboard tool ${i}` })+ )+ const exec = createExec(tools)+ const result = JSON.parse((await exec.handler(mockContext, { command: 'search dashboard' })) as string)+ expect(result.truncated).toBe(true)+ expect(result.matches).toHaveLength(25)+ expect(result.hint).toContain('30')+ })++ it('reports an invalid regex gracefully', async () => {+ const exec = createExec([makeMockTool()])+ await expect(exec.handler(mockContext, { command: 'search [invalid' })).rejects.toThrow(+ /invalid regex pattern/i+ )+ })})describe('deprecated tool redirects', () => {diff --git a/services/mcp/tests/unit/tool-search.test.ts b/services/mcp/tests/unit/tool-search.test.tsnew file mode 100644index 000000000000..8c9e0bf8ce3e--- /dev/null+++ b/services/mcp/tests/unit/tool-search.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest'++import { isRegexPattern, type SearchableTool, searchToolsRanked, searchToolsRegex } from '@/tools/tool-search'++const TOOLS: SearchableTool[] = [+ { name: 'dashboard-create', title: 'Create dashboard', description: 'Create a new dashboard' },+ { name: 'dashboard-get-all', title: 'List dashboards', description: 'List all dashboards in the project' },+ { name: 'insight-create', title: 'Create insight', description: 'Create a new insight (graph/trend)' },+ { name: 'insight-get-all', title: 'List insights', description: 'List all insights' },+ { name: 'feature-flag-get-all', title: 'List feature flags', description: 'List all feature flags' },+ { name: 'query-run', title: 'Run query', description: 'Run an arbitrary HogQL query' },+ { name: 'experiment-create', title: 'Create experiment', description: 'Create a new experiment' },+]++describe('tool-search', () => {+ describe('searchToolsRanked', () => {+ it('surfaces the relevant create tools for a multi-word natural-language query', () => {+ // The original single-regex predicate returned ZERO for this phrase —+ // this is the regression the forgiving search exists to fix.+ const ranked = searchToolsRanked(TOOLS, 'create dashboard insight')+ expect(ranked.length).toBeGreaterThan(0)+ expect(ranked.slice(0, 2).map((r) => r.name)).toEqual(['dashboard-create', 'insight-create'])+ })++ it('weights a name hit above a token that only appears in prose', () => {+ // "experiment-create" matches two tokens in its name; tools that merely+ // mention "create" elsewhere must not outrank it.+ const ranked = searchToolsRanked(TOOLS, 'create experiment')+ expect(ranked[0]?.name).toBe('experiment-create')+ })++ it('returns nothing when no token matches any field', () => {+ expect(searchToolsRanked(TOOLS, 'nonexistent-token')).toEqual([])+ })+ })++ describe('searchToolsRegex', () => {+ it('matches a kebab-case prefix pattern against name/title/description', () => {+ expect(searchToolsRegex(TOOLS, 'query-').map((t) => t.name)).toEqual(['query-run'])+ })++ it('matches every feature-flag tool', () => {+ expect(searchToolsRegex(TOOLS, 'feature-flag').map((t) => t.name)).toEqual(['feature-flag-get-all'])+ })++ it('throws on an invalid regex so callers can surface their own message', () => {+ expect(() => searchToolsRegex(TOOLS, '[invalid')).toThrow(/regular expression/i)+ })+ })++ describe('isRegexPattern', () => {+ it('treats kebab-case and regex patterns as regex', () => {+ expect(isRegexPattern('query-')).toBe(true)+ expect(isRegexPattern('feature-flag')).toBe(true)+ expect(isRegexPattern('a|b')).toBe(true)+ expect(isRegexPattern('get.*')).toBe(true)+ })++ it('treats plain words as non-regex so they route to ranked search', () => {+ expect(isRegexPattern('dashboard')).toBe(false)+ expect(isRegexPattern('create dashboard insight')).toBe(false)+ })+ })+})