:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mcp): make switch tools findable from exec search and instructions (#124919)
Adam Bowker9cd312f96539
diff --git a/services/mcp/src/lib/instructions-formatter.ts b/services/mcp/src/lib/instructions-formatter.tsindex 362873b1e310..cce892d95b6e 100644--- a/services/mcp/src/lib/instructions-formatter.ts+++ b/services/mcp/src/lib/instructions-formatter.ts@@ -52,6 +52,9 @@ const WHATS_NEW_CHANGELOG_ONLY = "Check what's new in the changelog (https://posconst PROJECT_LOOKUP ='Call `project-get` without an ID to read the active project: its name, id, organization, timezone, person-on-events mode, test account filter default, and enabled products. Call it before you rely on one of these, for example the timezone for a date range.'const GROUP_TYPES_LOOKUP = "For the project's group types, run `execute-sql` on `system.group_type_mappings`."+const SWITCH_TOOLS = ['switch-project', 'switch-organization', 'projects-get', 'organizations-get']+const SWITCH_LOOKUP =+ 'To work in another project or organization, call `switch-project` or `switch-organization`. `projects-get` and `organizations-get` resolve a name to the id they take. Do not search the tool list for this.'export interface InstructionsContext {guidelines: string@@ -139,6 +142,7 @@ function envContextSections(ctx: InstructionsContext): string[] {const available = (tool: string): boolean => ctx.tools?.some(({ name }) => name === tool) ?? falseconst lookups = [...(available('project-get') ? [PROJECT_LOOKUP] : []),+ ...(SWITCH_TOOLS.every(available) ? [SWITCH_LOOKUP] : []),...(available('execute-sql') ? [GROUP_TYPES_LOOKUP] : []),]return lookups.length > 0 ? [formatPrompt(ENV_CONTEXT, { env_lookups: lookups.join(' ') })] : []diff --git a/services/mcp/src/templates/sections/tool-search.md b/services/mcp/src/templates/sections/tool-search.mdindex e5fc23f914bd..78a485dee5a7 100644--- a/services/mcp/src/templates/sections/tool-search.md+++ b/services/mcp/src/templates/sections/tool-search.md@@ -7,6 +7,8 @@- **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.+Quotes are ignored. A regex that matches no tool falls back to ranking by its words, so a guessed name such as "project-update" still returns the nearest tools.+**Good queries:**- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools firstdiff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 13e0fa516c84..14f42a162572 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -184,6 +184,8 @@ export interface ExecCommandMeta {exec_search_query?: string/** How many tools matched, before the response is truncated — 0 is the interesting case. */exec_search_match_count?: number+ /** When a regex matched nothing, how many tools the word-ranked fallback returned instead. */+ exec_search_fallback_match_count?: number/** How many of those matches came from a connected third-party server. */exec_search_gateway_match_count?: numberexec_learn_kind?: ExecLearnKind@@ -1858,6 +1860,12 @@ export function createExecTool()}+ // Agents quote single words (`search "project"`), and a literal quote+ // matches no tool.+ const query = rest.replace(/["'`]/g, '').trim()+ if (!query) {+ throw new ExecCommandError('Usage: search <words or regex_pattern>', 'usage')+ }// 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-@@ -1866,35 +1874,51 @@ export function createExecTool(// `matches` is the page the agent sees; `matchedNames` is every match,// which is what the counts report — a truncated page would make a broad// query look as narrow as a precise one.- let matchedNames: string[]- let matches: string[]- let gatedMatches: ScopeGatedTool[]+ let matchedNames: string[] = []+ let matches: string[] = []+ let gatedMatches: ScopeGatedTool[] = []let truncatedFrom = 0- if (isRegexPattern(rest)) {- try {- matchedNames = searchToolsRegex(searchableTools, rest).map((t) => t.name)- matches = matchedNames- gatedMatches = searchToolsRegex(scopeGatedTools, rest)- } catch {- throw new ExecCommandError(`Invalid regex pattern: "${rest}"`, 'invalid_regex')- }- } else {- const ranked = searchToolsRanked(searchableTools, rest)+ let fallbackFrom: string | undefined+ const rankByWords = (words: string): void => {+ const ranked = searchToolsRanked(searchableTools, words)truncatedFrom = ranked.length > MAX_RANKED_SEARCH_RESULTS ? ranked.length : 0matchedNames = ranked.map((r) => r.name)matches = matchedNames.slice(0, MAX_RANKED_SEARCH_RESULTS)// 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)+ gatedMatches = searchToolsRanked(scopeGatedTools, words).map((r) => gatedByName.get(r.name)).filter((t): t is ScopeGatedTool => t !== undefined)}+ if (isRegexPattern(query)) {+ try {+ matchedNames = searchToolsRegex(searchableTools, query).map((t) => t.name)+ matches = matchedNames+ gatedMatches = searchToolsRegex(scopeGatedTools, query)+ } catch {+ throw new ExecCommandError(`Invalid regex pattern: "${query}"`, 'invalid_regex')+ }+ // A guessed name such as `project-update` matches nothing as a regex,+ // but its words usually name the tool the agent wants.+ const words = query.replace(/[^a-z0-9]+/gi, ' ').trim()+ if (matchedNames.length === 0 && gatedMatches.length === 0 && words) {+ rankByWords(words)+ if (matchedNames.length > 0 || gatedMatches.length > 0) {+ fallbackFrom = query+ }+ }+ } else {+ rankByWords(query)+ }options.trackCommand?.({exec_verb: verb,exec_search_query: rest,- exec_search_match_count: matchedNames.length,+ exec_search_match_count: fallbackFrom === undefined ? matchedNames.length : 0,+ ...(fallbackFrom === undefined+ ? {}+ : { exec_search_fallback_match_count: matchedNames.length }),exec_search_gateway_match_count: matchedNames.filter(isGatewayToolName).length,})@@ -1914,15 +1938,20 @@ export function createExecTool(if (matches.length === 0) {return JSON.stringify({matches: [],- hint: `No tools matched "${rest}". Run "tools" to see all available tool names.`,+ hint: `No tools matched "${query}". Search again with plain words that describe the task, for example "create dashboard". Run "tools" only if that also finds nothing.`,})}+ const fallbackHint =+ fallbackFrom === undefined+ ? undefined+ : `No tool is named "${fallbackFrom}". These are the closest matches by its words.`if (truncatedFrom > 0) {const catalogHint = catalogDiscoveryHint(allTools, matches)return JSON.stringify({matches,truncated: true,hint: [+ fallbackHint,catalogHint,`Showing the top ${MAX_RANKED_SEARCH_RESULTS} of ${truncatedFrom} matches, ranked by relevance. Use a more specific query to narrow the results.`,]@@ -1931,8 +1960,9 @@ export function createExecTool(})}const catalogHint = catalogDiscoveryHint(allTools, matches)- if (catalogHint) {- return JSON.stringify({ matches, hint: catalogHint })+ const hint = [fallbackHint, catalogHint].filter(Boolean).join(' ')+ if (hint) {+ return JSON.stringify({ matches, hint })}return JSON.stringify(matches)}diff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txtindex 5eec61b3ca7b..27f8e7231614 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat-skills.txt@@ -152,6 +152,8 @@ If you get errors due to permissions being denied, check that you have the corre- **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.+Quotes are ignored. A regex that matches no tool falls back to ranking by its words, so a guessed name such as "project-update" still returns the nearest tools.+**Good queries:**- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools firstdiff --git a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txtindex f2a9b10bcf64..956c3e3067fe 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/exec-command-reference-claude-chat.txt@@ -139,6 +139,8 @@ If you get errors due to permissions being denied, check that you have the corre- **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.+Quotes are ignored. A regex that matches no tool falls back to ranking by its words, so a guessed name such as "project-update" still returns the nearest tools.+**Good queries:**- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools firstdiff --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 cde0ccc55d21..15a577b59f90 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@@ -157,6 +157,8 @@ If you get errors due to permissions being denied, check that you have the corre- **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.+Quotes are ignored. A regex that matches no tool falls back to ranking by its words, so a guessed name such as "project-update" still returns the nearest tools.+**Good queries:**- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools firstdiff --git a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txtindex bacfff0a60fc..ac0daf5ac89e 100644--- a/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt+++ b/services/mcp/tests/unit/__snapshots__/instructions/tools-instructions.txt@@ -36,6 +36,8 @@ For an in-scope request, use the available sources in this order:- **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.+Quotes are ignored. A regex that matches no tool falls back to ranking by its words, so a guessed name such as "project-update" still returns the nearest tools.+**Good queries:**- `search create dashboard insight` — plain words, ranked: dashboard/insight creation tools firstdiff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 720c107af7fb..3759ed96121b 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -1893,6 +1893,41 @@ describe('exec tool', () => {/invalid regex pattern/i)})++ it.each(['search "project"', "search 'switch project'", 'search `switch-project`'])(+ 'ignores quotes around the query: %s',+ async (command) => {+ const exec = createExec([makeMockTool({ name: 'switch-project', title: 'Switch active project' })])+ const result = JSON.parse((await exec.handler(mockContext, { command })) as string)+ expect(Array.isArray(result) ? result : result.matches).toEqual(['switch-project'])+ }+ )++ it('falls back to word ranking when a guessed tool name matches nothing', async () => {+ const tracked: ExecCommandMeta[] = []+ const exec = createExec(+ [+ makeMockTool({ name: 'project-settings-update', title: 'Update project settings' }),+ makeMockTool({ name: 'feature-flag-get-all', title: 'List feature flags' }),+ ],+ undefined,+ { trackCommand: (meta) => tracked.push(meta) }+ )+ const result = JSON.parse((await exec.handler(mockContext, { command: 'search project-update' })) as string)+ expect(result.matches).toEqual(['project-settings-update'])+ expect(result.hint).toContain('No tool is named "project-update"')+ expect(tracked.at(-1)).toMatchObject({+ exec_search_match_count: 0,+ exec_search_fallback_match_count: 1,+ })+ })++ it('tells the agent to retry with plain words when nothing matches at all', async () => {+ const exec = createExec([makeMockTool()])+ const result = JSON.parse((await exec.handler(mockContext, { command: 'search zzz-qqq' })) as string)+ expect(result.matches).toEqual([])+ expect(result.hint).toContain('plain words')+ })})describe('held tool set', () => {diff --git a/services/mcp/tests/unit/instructions-formatter.test.ts b/services/mcp/tests/unit/instructions-formatter.test.tsindex 9228759ae39d..8a5a4539a300 100644--- a/services/mcp/tests/unit/instructions-formatter.test.ts+++ b/services/mcp/tests/unit/instructions-formatter.test.ts@@ -269,11 +269,26 @@ describe('InstructionsFormatter', () => {{ name: 'only project-get', tools: ['project-get'], project: true, groups: false },{ name: 'only execute-sql', tools: ['execute-sql'], project: false, groups: true },{ name: 'neither lookup tool', tools: [], project: false, groups: false },+ {+ name: 'the switch tools too',+ tools: ['project-get', 'switch-project', 'switch-organization', 'projects-get', 'organizations-get'],+ project: true,+ groups: false,+ },+ {+ name: 'switch-project without its lookups',+ tools: ['project-get', 'switch-project'],+ project: true,+ groups: false,+ },])('names only the env lookup tools the roster has: $name', ({ tools, project, groups }) => {const ctx = { ...fullCtx, tools: tools.map((name) => ({ name, category: 'Core' })) }const result = new InstructionsFormatter().buildExecCommandReference(ctx)expect(result.includes(ENV_POINTER)).toBe(project)expect(result.includes(GROUP_TYPES_POINTER)).toBe(groups)+ expect(result.includes('call `switch-project` or `switch-organization`')).toBe(+ tools.includes('organizations-get')+ )expect(result.includes('### Active environment')).toBe(project || groups)})