: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): clarify learn gate and error recovery (#102361)
Jake Ruthdb23450eafc8
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex f74f9dee3c16..f2d811f3a73c 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -109,6 +109,10 @@ A missing flag evaluates as off. Development `FEATURE_FLAG_OVERRIDES` do not enaVerify the published skills archive loads, then start a new MCP session and sandbox task for an enabled user.Exercise `learn -s`, a qualified skill read, and a product call, and check that a disabled user retains the prior behavior.+The skills-first gate response directs agents to search, load an exact qualified name with `learn posthog:<skill>` or `learn project:<skill>`, then retry the original call.+Searching alone does not open the gate, and `skill-get` and `skill-list` cannot satisfy it.+Unknown learning topics and empty search queries return recovery instructions; a failed `learn` does not open the gate.+If no skill applies, the existing `call --no-skills ...` acknowledgement remains available.The `plugin` and `posthog-code` consumers remain excluded regardless of the flag.Monitor archive validation errors, catalog size, MCP memory, and task failures before expanding the release condition.diff --git a/services/mcp/src/tools/exec-learn.ts b/services/mcp/src/tools/exec-learn.tsindex 4d6aebadf634..351a5f1fb15f 100644--- a/services/mcp/src/tools/exec-learn.ts+++ b/services/mcp/src/tools/exec-learn.ts@@ -127,7 +127,7 @@ export class ExecLearnCatalog {if (tokens[0] === '-s') {const query = tokens.slice(1).join(' ')- this.validateSearchQuery(query)+ this.validateSearchQuery(query, 'learn -s "<task keywords>"')return await this.searchSkills(query)}@@ -167,7 +167,7 @@ export class ExecLearnCatalog {const flagArgs = args.slice(flagIndex + 1)if (flag === '-s') {const query = flagArgs.join(' ')- this.validateSearchQuery(query)+ this.validateSearchQuery(query, 'learn <source>:<skill> <path> -s "<keywords>"')return await this.searchSkillFile(skill, path, query)}if (flag === '--lines' && flagArgs.length === 1) {@@ -419,9 +419,9 @@ export class ExecLearnCatalog {}}- private validateSearchQuery(query: string): void {+ private validateSearchQuery(query: string, usage: string): void {if (!query.trim()) {- throw new Error('Search query cannot be empty.')+ throw new Error(`Search query cannot be empty. Usage: ${usage}.`)}if (query.length > MAX_SEARCH_QUERY_LENGTH) {throw new Error(`Search query must be at most ${MAX_SEARCH_QUERY_LENGTH} characters.`)@@ -441,8 +441,12 @@ export class ExecLearnCatalog {.map((guide) => guide.id).join(', ')const unknown = unknownGuideIds.map((guideId) => `"${guideId}"`).join(', ')+ const availableHint = available ? ` Available: ${available}.` : ''+ const recovery = this.skillSources+ ? ' To load a skill, run `learn -s "<task keywords>"`, then `learn posthog:<skill>` or `learn project:<skill>` using the exact qualified name from the results.'+ : ' Run `learn` to list available topics.'throw new Error(- `Unknown learning ${unknownGuideIds.length === 1 ? 'topic' : 'topics'}: ${unknown}. Available: ${available}`+ `Unknown learning ${unknownGuideIds.length === 1 ? 'topic' : 'topics'}: ${unknown}.${availableHint}${recovery}`)}diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex a4babe5f2ed2..afd4f833a5b3 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -215,7 +215,7 @@ export interface ExecToolOptions {const CALL_USAGE = 'Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>'const SKILLS_GATE_MESSAGE =- 'No skills loaded this session. Run `learn -s "<task keywords>"` and load the matching skills first — they carry the thresholds, schemas, and query patterns this task needs. If no skill applies, re-run this exact command as `call --no-skills ...`.'+ 'No skills loaded this session. Run `learn -s "<task keywords>"`, then load a result with `learn posthog:<skill>` or `learn project:<skill>` using its exact qualified name. Searching alone does not load a skill. `skill-get` and `skill-list` do not satisfy this gate. After loading, retry the original call. If no skill applies, re-run this exact command as `call --no-skills ...`.'/*** Plain errors out of the learn catalog are agent mistakes — unknown names, baddiff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex fc83ab5be836..089f85e92912 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -4,7 +4,7 @@ import { parse as parseYaml } from 'yaml'import { z } from 'zod'import { STRUCTURED_CONTENT_ONLY_TEXT, type ToolResultPayload, UI_APP_RENDER_NOTE } from '@/lib/build-tool-result'-import { PostHogApiError, ToolInputValidationError } from '@/lib/errors'+import { handleToolError, PostHogApiError, ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'import { InstructionsFormatter } from '@/lib/instructions-formatter'@@ -135,17 +135,26 @@ describe('exec tool', () => {)})- it('reports every unknown guide as a typed learn error without partial content', async () => {- const exec = createExec(undefined, undefined, { learnCatalog })+ it.each([true, false])(+ 'reports unknown guides with recovery instructions (skills enabled: %s)',+ async (skillsEnabled) => {+ const exec = createExec(undefined, undefined, {+ learnCatalog: new ExecLearnCatalog(guides, skillsEnabled ? { posthog: undefined } : undefined),+ })- await expect(- exec.handler(mockContext, { command: 'learn analytics unknown missing unknown' })- ).rejects.toMatchObject({- name: 'ExecCommandError',- reason: 'unknown_learn_topic',- message: 'Unknown learning topics: "unknown", "missing". Available: analytics, visualizations',- })- })+ await expect(+ exec.handler(mockContext, { command: 'learn analytics unknown missing unknown' })+ ).rejects.toMatchObject({+ name: 'ExecCommandError',+ reason: 'unknown_learn_topic',+ message:+ 'Unknown learning topics: "unknown", "missing". Available: analytics, visualizations.' ++ (skillsEnabled+ ? ' To load a skill, run `learn -s "<task keywords>"`, then `learn posthog:<skill>` or `learn project:<skill>` using the exact qualified name from the results.'+ : ' Run `learn` to list available topics.'),+ })+ }+ )it('keeps core exec usable and reports each unavailable skill source', async () => {const exec = createExec(undefined, undefined, { learnCatalog })@@ -164,9 +173,11 @@ describe('exec tool', () => {})describe('skills-first gate', () => {- const guideCatalog = (): ExecLearnCatalog =>+ const guideCatalog = (withGuides = true): ExecLearnCatalog =>new ExecLearnCatalog(- [{ id: 'analytics', title: 'Analytics', description: 'Guidance.', content: 'Use the tools.' }],+ withGuides+ ? [{ id: 'analytics', title: 'Analytics', description: 'Guidance.', content: 'Use the tools.' }]+ : [],{posthog: new SkillCatalog([{@@ -192,18 +203,72 @@ describe('exec tool', () => {}}- it('rejects an un-learned call with a typed reason and passes it after a skill load', async () => {- const exec = createExec(undefined, undefined, {+ it.each([+ 'mock-tool',+ 'skill-get',+ 'skill-file-get',+ 'skill-list',+ 'llma-skill-get',+ 'llma-skill-file-get',+ 'llma-skill-list',+ ])('directs a gated %s call to learn and permits it after a skill load', async (name) => {+ const exec = createExec([makeMockTool({ name })], undefined, {learnCatalog: guideCatalog(),skillsSession: makeSkillsSession(),})- await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toMatchObject({+ const command = `call ${name} {}`+ await expect(exec.handler(mockContext, { command })).rejects.toMatchObject({name: 'ExecCommandError',reason: 'skills_gate',- message: expect.stringContaining('No skills loaded this session'),+ message: expect.stringContaining('`learn posthog:<skill>` or `learn project:<skill>`'),+ })+ const rejected = await exec+ .handler(mockContext, { command })+ .catch((error: unknown) => handleToolError(error, 'exec'))+ expect(rejected).toMatchObject({+ isError: true,+ content: [+ {+ type: 'text',+ text: expect.stringContaining('`skill-get` and `skill-list` do not satisfy this gate.'),+ },+ ],})+ await exec.handler(mockContext, { command: 'learn posthog:bot-traffic' })+ await expect(exec.handler(mockContext, { command })).resolves.toBeDefined()+ })++ it.each([+ { command: 'learn bot-traffic', hint: '`learn posthog:<skill>` or `learn project:<skill>`' },+ { command: 'learn -s', hint: 'Usage: learn -s "<task keywords>"' },+ {+ command: 'learn posthog:bot-traffic SKILL.md -s',+ hint: 'Usage: learn <source>:<skill> <path> -s "<keywords>"',+ },+ ])('returns recovery guidance for $command without opening the gate', async ({ command, hint }) => {+ const exec = createExec(undefined, undefined, {+ learnCatalog: guideCatalog(false),+ skillsSession: makeSkillsSession(),+ })+ const rejected = await exec+ .handler(mockContext, { command })+ .catch((error: unknown) => handleToolError(error, 'exec'))+ expect(rejected).toMatchObject({+ isError: true,+ content: [{ type: 'text', text: expect.stringContaining(hint) }],+ })+ expect(JSON.stringify(rejected)).not.toContain('Available:')+ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toMatchObject({+ reason: 'skills_gate',+ })+ await expect(exec.handler(mockContext, { command: 'learn -s "bot traffic"' })).resolves.toContain(+ 'posthog:bot-traffic'+ )+ await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toMatchObject({+ reason: 'skills_gate',+ })await exec.handler(mockContext, { command: 'learn posthog:bot-traffic' })await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()})