: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 a skill lookup miss read as a miss, not a service failure (#99267)
posthog[bot]bf7786fc6d4a
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 1bfa01894838..43df171e0b54 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -35,6 +35,7 @@ import {import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { createRenderUiTool } from '@/tools/render-ui'import { skillAnalyticsProperties } from '@/tools/skills/analytics'+import { formatSkillLookupMiss } from '@/tools/skills/notFound'import type { Context, Tool, ZodObjectAny } from '@/tools/types'import {@@ -63,6 +64,11 @@ interface ExecMetricState {innerToolName: string | undefined/** What the agent asked for, merged onto the event whichever verb ran. */commandMeta: ExecCommandMeta | undefined+ /**+ * The inner call's failure when the dispatcher recovered from it and returned+ * a normal result, so the canonical event still records the failure.+ */+ innerFailure: { error: unknown } | undefined}/**@@ -411,6 +417,17 @@ export class ToolExecutor {input: validation.data,})+ // A skill lookup that misses is not a failure the agent should read as+ // one. The exec dispatcher rewrites the same miss, and a tools-mode+ // client reaching this path must get the same answer — otherwise the+ // behavior changes with the client. Telemetry above already recorded+ // the 404, and `handleToolError` adds nothing to a 4xx that is lost+ // here: no recovery hint, no exception capture.+ const lookupMiss = formatSkillLookupMiss(tool.name, error, validation.data as Record<string, unknown>)+ if (lookupMiss) {+ return { content: [{ type: 'text', text: lookupMiss }] }+ }+const sessionUuid = await state.reqCtx.getEffectiveSessionUuid(state.requestContext)return handleToolError(error, tool.name, state.distinctId, sessionUuid)}@@ -421,7 +438,11 @@ export class ToolExecutor {state: ResolvedState,analyticsMeta?: ToolCallAnalyticsMeta): Promise<unknown> {- const execMetrics: ExecMetricState = { innerToolName: undefined, commandMeta: undefined }+ const execMetrics: ExecMetricState = {+ innerToolName: undefined,+ commandMeta: undefined,+ innerFailure: undefined,+ }const resolved = this.resolveExecTool(state, execMetrics, analyticsMeta)const toolArgs = (params?.arguments ?? {}) as Record<string, unknown>@@ -470,14 +491,23 @@ export class ToolExecutor {distinctId: undefined,})+ // A handler can return normally for a call that failed: a skill lookup+ // miss is rewritten so the agent does not read it as an outage. The+ // canonical event still records the failure, and must not stamp a skill+ // the store never delivered — a miss is not a read.+ const innerFailure = execMetrics.innerFailure+ const failureShape = innerFailure+ ? errorAnalyticsProperties(classifyToolError(innerFailure.error, execToolName()), innerFailure.error)+ : undefined+void trackToolCall(execToolName(),duration,- false,+ failureShape !== undefined,state,{...execShape,- ...execSkillShape,+ ...(failureShape ?? execSkillShape),input_tokens: estimateTokens(validation.data),output_tokens: estimateResponseTokens(response),...execMetrics.commandMeta,@@ -547,6 +577,9 @@ export class ToolExecutor {// event (now relabelled to the inner tool name, with the inner tool's category// derived from it) already carries this call, so a second emit would double-count.execMetrics.innerToolName = toolName+ if (!properties.success) {+ execMetrics.innerFailure = { error: properties.error }+ }const status = properties.success ? 'success' : properties.validation_error ? 'validation_error' : 'error'toolCallsTotal.inc({ tool: toolName, status })// Mirror the native path: schema rejections never start a handler, sodiff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex e538f41d8051..e045c6338d3e 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -214,8 +214,20 @@ export class PostHogApiError extends Error {}}+/** The request path without the upstream host. The host is not something an+ * agent can act on, and reading one makes a 4xx look like an infrastructure+ * fault; `client.ts` already logs the full URL server-side. */+function requestPath(url: string): string {+ try {+ const parsed = new URL(url)+ return `${parsed.pathname}${parsed.search}`+ } catch {+ return url+ }+}+function buildDefaultApiErrorMessage(options: PostHogApiErrorOptions): string {- return `Request failed:\nURL: ${options.method} ${options.url}\nStatus Code: ${options.status} (${options.statusText})\nError Message: ${options.body}`+ return `Request failed:\nPath: ${options.method} ${requestPath(options.url)}\nStatus Code: ${options.status} (${options.statusText})\nError Message: ${options.body}`}export interface PostHogRateLimitErrorOptions {diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex b65f7acd3b0a..8bc8a4ae2c6b 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -17,6 +17,7 @@ import { APP_DATA_META_KEY } from '@/ui-apps/types'import { type ExecLearnCatalog, QUALIFIED_IDENTIFIER, tokenizeLearnInput } from './exec-learn'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'+import { formatSkillLookupMiss } from './skills/notFound'import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'import { getToolDefinitions, type FlagGatedTool, type ScopeGatedTool } from './toolDefinitions'import {@@ -84,6 +85,14 @@ export interface ExecInnerCallProperties {error_status?: number/** Input rejected by the tool's schema before dispatch — no handler ran. */validation_error?: boolean+ /**+ * The thrown value itself. The dispatcher can turn a failure into a normal+ * return — a skill lookup miss is rewritten so the agent does not read it as+ * an outage — and then the wrapper never sees the exception. Carrying it lets+ * the wrapper classify and sanitize the failure exactly as it does for one+ * that reaches its catch block, instead of recording the call as a success.+ */+ error?: unknown/*** Estimated input/output tokens for the inner tool call. Carried so single-exec* mode attributes token usage to the real tool rather than the `exec` wrapper.@@ -1687,7 +1696,18 @@ export function createExecTool(? { error_status: apiError instanceof PostHogApiError ? apiError.status : 400 }: {}),input,+ error: err,})+ // A skill lookup that misses is not a failure the agent should+ // read as one. Telemetry above still records the 404.+ const lookupMiss = formatSkillLookupMiss(tool.name, err, input)+ if (lookupMiss) {+ // The success path below serializes a string result under+ // `--json`, so encode this the same way. A `--json` caller+ // reaches for `JSON.parse`, and raw prose is the one reply+ // that would break in its hands.+ return useJson ? JSON.stringify(lookupMiss) : lookupMiss+ }throw err}const durationMs = Date.now() - startedAtdiff --git a/services/mcp/src/tools/skills/analytics.ts b/services/mcp/src/tools/skills/analytics.tsindex 9fbe3f1182ba..aadc370d0fb8 100644--- a/services/mcp/src/tools/skills/analytics.ts+++ b/services/mcp/src/tools/skills/analytics.ts@@ -27,7 +27,7 @@ const RECORDABLE_SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$//** Read tools that name a single skill. The `llma-skill-*` entries are the* deprecated aliases from `deprecatedAliases.ts`, which reach analytics under* their own name and would otherwise be a silent hole in the data. */-const SKILL_READ_TOOLS = new Set(['skill-get', 'skill-file-get', 'llma-skill-get', 'llma-skill-file-get'])+export const SKILL_READ_TOOLS = new Set(['skill-get', 'skill-file-get', 'llma-skill-get', 'llma-skill-file-get'])/** Only `skill-get` pages a body; the offset is meaningless on the others. */const BODY_PAGINATED_TOOLS = new Set(['skill-get', 'llma-skill-get'])diff --git a/services/mcp/src/tools/skills/notFound.ts b/services/mcp/src/tools/skills/notFound.tsnew file mode 100644index 000000000000..54c2cb38f757--- /dev/null+++ b/services/mcp/src/tools/skills/notFound.ts@@ -0,0 +1,79 @@+import { findRecoverableApiError, PostHogApiError } from '@/lib/errors'++import { SKILL_READ_TOOLS } from './analytics'++/** Only the file-level 404 names the enclosing skill, which is how a miss on a+ * bundled file is told apart from a miss on the skill itself. */+const FILE_MISSING_DETAIL = 'not found in skill'++/** The store's own skill-level 404 detail, from `_skill_not_found_response` in+ * `products/skills/backend/api/skills.py`. The name lookup is the only thing+ * that emits it, so a 404 without it came from somewhere else. */+const SKILL_MISSING_DETAIL = 'Skill with name'++/**+ * Returns the plain not-found message for a skill lookup 404, or undefined for+ * anything else — a different tool, a different status, or a genuine failure+ * that must keep its own shape.+ *+ * The generic API error shape leads with "Request failed" and an upstream URL,+ * which reads as a service outage rather than a lookup miss. A model that draws+ * that conclusion stops calling the skill tools at all, so the miss has to name+ * itself and point at the tool that lists what exists.+ */+export function formatSkillLookupMiss(+ toolName: string,+ error: unknown,+ input: Record<string, unknown>+): string | undefined {+ if (!SKILL_READ_TOOLS.has(toolName)) {+ return undefined+ }+ const apiError = findRecoverableApiError(error)+ if (!(apiError instanceof PostHogApiError) || apiError.status !== 404) {+ return undefined+ }++ // Without the name the caller asked for there is no message worth+ // substituting, so the generic error stands.+ const { skill_name: skillName, file_path: filePath, version } = input+ if (typeof skillName !== 'string' || !skillName) {+ return undefined+ }++ if (typeof filePath === 'string' && filePath && apiError.body.includes(FILE_MISSING_DETAIL)) {+ // A file belongs to one version row, so the manifest worth reading is the+ // one for the version the caller asked for. An unpinned `skill-get`+ // returns the latest version's files, and a publish replaces the whole+ // set, so those paths can be absent at the pinned version.+ const pinnedVersion = typeof version === 'number' ? `, "version": ${version}` : ''+ return [+ `No file "${filePath}" in the skill "${skillName}".`,+ `Run \`call skill-get {"skill_name": "${skillName}"${pinnedVersion}}\` to see the skill's file manifest.`,+ ].join('\n')+ }++ // A 404 the name lookup did not produce says nothing about what the store+ // holds, because it can come from a route or a project the connection cannot+ // reach. Rewriting it would assert the skill is absent on evidence that does+ // not support the claim, so it keeps the generic shape.+ if (!apiError.body.includes(SKILL_MISSING_DETAIL)) {+ return undefined+ }++ // Both read tools take a `version`, and the store returns this same+ // skill-level detail when the name resolves but the pinned version does not+ // exist. So a pinned read cannot be told the skill is absent: `skill-list`+ // would then list the skill the message just denied.+ if (typeof version === 'number') {+ return [+ `No version ${version} of the skill "${skillName}" in this project's skills store. The store answers the same way when the skill itself is missing.`,+ `Run \`call skill-get {"skill_name": "${skillName}"}\` to read the latest version, or \`call skill-list\` to see the skills that are available.`,+ ].join('\n')+ }++ return [+ `No skill named "${skillName}" in this project's skills store.`,+ 'Run `call skill-list` to see the skills that are available.',+ ].join('\n')+}diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.tsindex f7b665652333..43a73a977286 100644--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts@@ -645,6 +645,25 @@ describe('ToolExecutor metrics', () => {}}+ /** A context whose skill fetch 404s with the store's own lookup detail,+ * which is the only 404 the dispatcher rewrites into a plain result. */+ function contextThatMisses(): any {+ return {+ ...contextThatServes(),+ api: {+ request: vi.fn().mockRejectedValue(+ new PostHogApiError({+ status: 404,+ statusText: 'Not Found',+ body: '{"detail":"Skill with name \'conductor\' not found."}',+ url: 'https://us.posthog.com/api/projects/2/llm_skills/name/conductor/',+ method: 'GET',+ })+ ),+ },+ }+ }+function execStateWith(context: any): ResolvedState {return { ...execState(), context }}@@ -685,6 +704,22 @@ describe('ToolExecutor metrics', () => {expect(lastExtras()).not.toHaveProperty('$mcp_skill_body_offset')})+ // The agent reads a lookup miss as a plain result, but the miss rate has to+ // stay measurable. Recording the rewritten result as a success would hide+ // every deleted or renamed skill agents keep asking for.+ it('records a rewritten lookup miss as a failed call', async () => {+ const response: any = await executor.handleToolCall(+ { name: 'exec', arguments: { command: 'call skill-get {"skill_name":"conductor"}' } },+ execStateWith(contextThatMisses())+ )++ expect(response.isError).toBeFalsy()+ expect(mockTrackToolCall.mock.calls.at(-1)?.[2]).toBe(true)+ expect(lastExtras()).not.toHaveProperty('$mcp_skill_name')+ expect(lastExtras()).toMatchObject({ $mcp_error_type: 'api_4xx', $mcp_error_status: 404 })+ expect(callsFor(mockToolErrorsInc, 'skill-get')).toEqual([{ tool: 'skill-get', error_type: 'api_4xx' }])+ })+// Dropping the skill must not take the exec properties with it — those are// stamped on failures by design, and are the only record of what was tried.it('keeps the exec verb and target when a skill read fails', async () => {diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.tsindex 5d78dd84bf03..32ee9395b6f8 100644--- a/services/mcp/tests/hono/tool-executor.test.ts+++ b/services/mcp/tests/hono/tool-executor.test.ts@@ -17,6 +17,7 @@ import { InstructionsBuilder } from '@/hono/instructions'import type { ResolvedState } from '@/hono/request-state-resolver'import { ToolCatalog } from '@/hono/tool-catalog'import { ToolExecutor } from '@/hono/tool-executor'+import { PostHogApiError } from '@/lib/errors'import { buildToolDomainsCompact } from '@/lib/instructions'import { RENDER_UI_RESOURCE_URI, URI_MAP } from '@/resources/ui-apps.generated'import { makeSkillFile, SkillCatalog } from '@/skills/skill-catalog'@@ -163,6 +164,53 @@ describe('ToolExecutor', () => {expect(text).toContain('organization-get')expect(text).not.toContain('feature-flag-get-all')})++ // Cursor and ChatGPT get the per-tool roster, so they call the skill read+ // tools here rather than through exec. Left on the generic error shape, the+ // same miss reads as a service outage for them and as a plain answer for+ // everyone else — the divergence this rewrite exists to remove.+ it.each([+ [+ 'skill-get',+ { skill_name: 'missing-skill' },+ '{"detail":"Skill with name \'missing-skill\' not found."}',+ 'No skill named "missing-skill" in this project\'s skills store.',+ ],+ [+ 'skill-file-get',+ { skill_name: 'real-skill', file_path: 'refs/guide.md' },+ '{"detail":"File \'refs/guide.md\' not found in skill \'real-skill\'."}',+ 'No file "refs/guide.md" in the skill "real-skill".',+ ],+ ])('answers a %s miss with the plain message in tools mode', async (name, args, body, expected) => {+ const state = makeState([{ name }], {+ context: {+ api: {+ request: vi.fn().mockRejectedValue(+ new PostHogApiError({+ status: 404,+ statusText: 'Not Found',+ body,+ url: `https://internal.example.com/api/projects/1/llm_skills/name/${args.skill_name}/`,+ method: 'GET',+ })+ ),+ },+ cache: {},+ env: {},+ stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },+ sessionManager: {},+ getDistinctId: vi.fn(),+ trackEvent: vi.fn(),+ } as any,+ })++ const result = (await executor.handleToolCall({ name, arguments: args }, state)) as any++ expect(result.isError).toBeFalsy()+ expect(result.content[0].text).toContain(expected)+ expect(result.content[0].text).not.toContain('Request failed')+ })})describe('handleToolsList', () => {diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 08ce4eb73f0d..a81c845d5326 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -870,6 +870,154 @@ describe('exec tool', () => {})})+ describe('skill lookup misses', () => {+ function makeSkillTool(name: string, body: string): Tool<ZodObjectAny> {+ return makeMockTool({+ name,+ schema: z.object({+ skill_name: z.string(),+ file_path: z.string().optional(),+ version: z.number().optional(),+ }),+ handler: async () => {+ throw new PostHogApiError({+ status: 404,+ statusText: 'Not Found',+ body,+ url: 'https://internal.example.com/api/projects/1/llm_skills/name/missing-skill/',+ method: 'GET',+ })+ },+ })+ }++ it('answers a missing skill with a plain message that points at skill-list', async () => {+ const exec = createExec([+ makeSkillTool('skill-get', '{"detail":"Skill with name \'missing-skill\' not found."}'),+ ])++ const result = await exec.handler(mockContext, { command: 'call skill-get {"skill_name":"missing-skill"}' })++ expect(result).toBe(+ [+ 'No skill named "missing-skill" in this project\'s skills store.',+ 'Run `call skill-list` to see the skills that are available.',+ ].join('\n')+ )+ })++ // A file belongs to one version row, and a publish replaces the whole set,+ // so an unpinned recovery command sends an agent working from an older+ // version to a manifest whose paths it cannot fetch.+ it.each([+ ['', '{"skill_name": "real-skill"}'],+ [',"version":3', '{"skill_name": "real-skill", "version": 3}'],+ ])(+ 'names the file when the skill exists but a bundled file does not, and keeps "%s" on its own manifest',+ async (pinnedVersion, expectedArgs) => {+ const exec = createExec([+ makeSkillTool(+ 'skill-file-get',+ '{"detail":"File \'refs/guide.md\' not found in skill \'real-skill\'."}'+ ),+ ])++ const result = await exec.handler(mockContext, {+ command: `call skill-file-get {"skill_name":"real-skill","file_path":"refs/guide.md"${pinnedVersion}}`,+ })++ expect(result).toBe(+ [+ 'No file "refs/guide.md" in the skill "real-skill".',+ `Run \`call skill-get ${expectedArgs}\` to see the skill's file manifest.`,+ ].join('\n')+ )+ }+ )++ // A `--json` caller parses what it gets back, and every other result it can+ // receive is serialized. Raw prose here would be the one reply it cannot read.+ it('encodes the miss when the caller asked for --json', async () => {+ const exec = createExec([+ makeSkillTool('skill-get', '{"detail":"Skill with name \'missing-skill\' not found."}'),+ ])++ const result = (await exec.handler(mockContext, {+ command: 'call --json skill-get {"skill_name":"missing-skill"}',+ })) as string++ expect(JSON.parse(result)).toContain('No skill named "missing-skill"')+ })++ it('falls back to the skill message when skill-file-get misses on the skill itself', async () => {+ const exec = createExec([+ makeSkillTool('skill-file-get', '{"detail":"Skill with name \'missing-skill\' not found."}'),+ ])++ const result = await exec.handler(mockContext, {+ command: 'call skill-file-get {"skill_name":"missing-skill","file_path":"refs/guide.md"}',+ })++ expect(result).toContain('No skill named "missing-skill"')+ })++ it('still records the 404 in telemetry', async () => {+ const calls: { toolName: string; properties: ExecInnerCallProperties }[] = []+ const exec = createExecTool(+ [makeSkillTool('skill-get', '{"detail":"Skill with name \'missing-skill\' not found."}')],+ mockContext,+ 'test description',+ 'test command reference',+ undefined,+ (toolName, properties) => calls.push({ toolName, properties })+ )++ await exec.handler(mockContext, { command: 'call skill-get {"skill_name":"missing-skill"}' })++ expect(calls).toHaveLength(1)+ expect(calls[0]!.properties.success).toBe(false)+ expect(calls[0]!.properties.error_status).toBe(404)+ })++ it('leaves a 404 on an unrelated tool as an error', async () => {+ const exec = createExec([makeSkillTool('insight-get', '{"detail":"Not found."}')])++ await expect(+ exec.handler(mockContext, { command: 'call insight-get {"skill_name":"whatever"}' })+ ).rejects.toThrow(/Request failed/)+ })++ // The store returns its skill-level 404 for a version that was never+ // published as well as for a name that does not exist. Reporting the+ // skill as absent would contradict `skill-list`, which still lists it,+ // and an agent may drop a skill it could have read.+ it.each([+ ['skill-get', 'call skill-get {"skill_name":"real-skill","version":7}'],+ [+ 'skill-file-get',+ 'call skill-file-get {"skill_name":"real-skill","file_path":"refs/guide.md","version":7}',+ ],+ ])('names the version rather than the skill when %s pins one', async (name, command) => {+ const exec = createExec([makeSkillTool(name, '{"detail":"Skill with name \'real-skill\' not found."}')])++ const result = (await exec.handler(mockContext, { command })) as string++ expect(result).toContain('No version 7 of the skill "real-skill"')+ expect(result).not.toContain('No skill named')+ })++ // Only the name lookup emits the store's own detail. Any other 404 from+ // these tools carries no evidence about what the store holds, so it must+ // not be rewritten into a claim that the skill is absent.+ it('leaves a 404 that the name lookup did not produce as an error', async () => {+ const exec = createExec([makeSkillTool('skill-get', '{"detail":"Not found."}')])++ await expect(+ exec.handler(mockContext, { command: 'call skill-get {"skill_name":"real-skill"}' })+ ).rejects.toThrow(/Request failed/)+ })+ })+describe('output_format suppression', () => {// Mirrors the generated query wrappers / insight-query: `output_format`// toggles whether the handler surfaces the server-side formatted table.diff --git a/services/mcp/tests/unit/tool-error-hints.test.ts b/services/mcp/tests/unit/tool-error-hints.test.tsindex 75826b174a36..20cfed8f9aca 100644--- a/services/mcp/tests/unit/tool-error-hints.test.ts+++ b/services/mcp/tests/unit/tool-error-hints.test.ts@@ -79,6 +79,22 @@ describe('handleToolError recovery hints', () => {expect(content?.text).toContain('Narrow the query and retry')})+ it('reports the request path without the upstream host', () => {+ const error = new PostHogApiError({+ status: 404,+ statusText: 'Not Found',+ body: '{"detail":"Not found."}',+ url: 'https://internal.example.com/api/projects/2/insights/?limit=1',+ method: 'GET',+ })++ const result = handleToolError(error, 'insight-get')+ const [content] = result.content as Array<{ type: string; text: string }>++ expect(content?.text).toContain('Path: GET /api/projects/2/insights/?limit=1')+ expect(content?.text).not.toContain('internal.example.com')+ })+it('appends the hint even when the typed error is hidden behind Error.cause', () => {const original = new PostHogApiError({status: 503,