: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): drop the skills-first gate from exec (#104476)
Jake Ruth167292a16660
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex f2d811f3a73c..5c2530bd81b6 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -109,10 +109,8 @@ 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.+Skill use is advisory: a product `call` is never rejected for skipping `learn`, so stateless and session-holding clients behave the same.+Unknown learning topics and empty search queries return recovery instructions.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/README.md b/services/mcp/README.mdindex a3c941cd8b1d..69bfc78f5b9d 100644--- a/services/mcp/README.md+++ b/services/mcp/README.md@@ -306,7 +306,7 @@ Optional, task-specific guidance is served through the same tool:Built-in guides are specific to Claude web and desktop. Skill discovery is independently available to every cli-mode client when the `mcp-exec-skills` feature flag is enabled. Other clients, including Claude Code, receive only the skill commands and do not receive Claude's built-in guides. If the flag is missing, disabled, or cannot be evaluated, skill commands are omitted from the schema and rejected at runtime.When skill discovery is enabled, the inline prompt tells every non-plugin cli client, including Claude web and desktop, to search with `learn -s "<task keywords>"` before non-trivial PostHog work, load matches by exact qualified name, and follow the loaded `SKILL.md` before choosing tools. Trivial lookups and unrelated conversation skip this workflow.-A product `call` in a session that loaded no skill is rejected with an instruction to search first; `call --no-skills ...` records that no skill applies and opens the gate for the rest of the session. Clients without an MCP session id are not gated.+Skill use is advisory: a product `call` is never rejected for skipping `learn`, so every client behaves the same whether or not it holds an MCP session id.The skill bundle is shared through Redis: each pod loads it once at startup, parses it into memory, and serves every `learn` command from that parsed catalog.A background timer polls a small version key in Redis; only when the version changes does a pod read the archive bytes again.diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.tsindex a4f471fe282d..4c4c26c1733c 100644--- a/services/mcp/src/hono/request-context.ts+++ b/services/mcp/src/hono/request-context.ts@@ -73,11 +73,6 @@ export class RequestContext {return this.userCacheInstance}- /** State scoped to one MCP session, such as the skills-first gate markers. */- getSessionCache(mcpSessionId: string): RedisCache<State> {- return new RedisCache<State>(hash(mcpSessionId), this.redis, 'session', SESSION_CACHE_TTL_SECONDS)- }-get cache(): RedisCache<State> {return this.tokenCache}diff --git a/services/mcp/src/hono/skills-session.ts b/services/mcp/src/hono/skills-session.tsdeleted file mode 100644index 1952a4cee173..000000000000--- a/services/mcp/src/hono/skills-session.ts+++ /dev/null@@ -1,31 +0,0 @@-import type { RequestContext } from '@/hono/request-context'-import type { SkillsSessionState } from '@/tools/exec'--/**- * Session-scoped skill-usage markers for the exec skills-first gate, backed by- * a Redis cache keyed on the MCP session id. Requires that id — stateless- * clients get no gate rather than a per-request one.- */-export function buildSkillsSessionState(- reqCtx: RequestContext,- mcpSessionId: string | undefined-): SkillsSessionState | undefined {- if (!mcpSessionId) {- return undefined- }- const cache = reqCtx.getSessionCache(mcpSessionId)- return {- async hasLearned(): Promise<boolean> {- return (await cache.get('skillsLearnedAt')) !== undefined- },- async markLearned(): Promise<void> {- await cache.set('skillsLearnedAt', Date.now())- },- async hasAcknowledgedNoSkills(): Promise<boolean> {- return (await cache.get('skillsNoSkillsAckAt')) !== undefined- },- async markAcknowledgedNoSkills(): Promise<void> {- await cache.set('skillsNoSkillsAckAt', Date.now())- },- }-}diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.tsindex 49f07fb930ef..b18fc9961c73 100644--- a/services/mcp/src/hono/tool-executor.ts+++ b/services/mcp/src/hono/tool-executor.ts@@ -52,7 +52,6 @@ import { getEffectiveMCPClientContext } from './mcp-context'import { toolCallDurationSeconds, toolCallsTotal, toolErrorsTotal } from './metrics'import type { ResolvedState } from './request-state-resolver'import type { SkillCatalogService } from './skill-catalog-service'-import { buildSkillsSessionState } from './skills-session'import type { ToolCatalog } from './tool-catalog'interface ResolvedTool {@@ -693,9 +692,6 @@ export class ToolExecutor {),flagGatedTools: state.flagGatedTools,builtInSkillHint: this.builtInSkillHint(state),- skillsSession: this.instructionsBuilder.execSkillsEnabled(state)- ? buildSkillsSessionState(state.reqCtx, state.requestContext.mcpSessionId)- : undefined,...(state.gatewayToolsEnabled ? { gatewayToolsProvider: () => this.gatewayToolsFor(state) } : {}),// A verb-only report lands first; `search` then reports again with its query// and counts. Merge so the richer report wins without losing the verb.diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex c1b919aff7cd..5bf54fc0045f 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -155,7 +155,6 @@ export type ExecCommandErrorReason =| 'invalid_regex'| 'unknown_learn_topic'| 'needs_confirmation'- | 'skills_gate'/*** Thrown by the `exec` dispatcher when it rejects a command before any innerdiff --git a/services/mcp/src/templates/sections/skills-first.md b/services/mcp/src/templates/sections/skills-first.mdindex f532e4f8a74e..b2bb19701a45 100644--- a/services/mcp/src/templates/sections/skills-first.md+++ b/services/mcp/src/templates/sections/skills-first.md@@ -1 +1 @@-**SKILLS FIRST — this server is the authoritative source of PostHog agent skills.** Before answering any PostHog product or data question — including questions about PostHog's own behavior, warnings, thresholds, or internals — run `learn -s "<task keywords>"` here and load the matching skills. Never answer such questions by cloning, grepping, or web-searching PostHog source or docs: they may not match this instance, and un-learned product calls are rejected.+**SKILLS FIRST — this server is the authoritative source of PostHog agent skills.** Before answering any PostHog product or data question — including questions about PostHog's own behavior, warnings, thresholds, or internals — run `learn -s "<task keywords>"` here and load the matching skills. Never answer such questions by cloning, grepping, or web-searching PostHog source or docs: they may not match this instance.diff --git a/services/mcp/src/tools/exec.ts b/services/mcp/src/tools/exec.tsindex 6d027a30772e..85ebd5398ea1 100644--- a/services/mcp/src/tools/exec.ts+++ b/services/mcp/src/tools/exec.ts@@ -15,7 +15,7 @@ import { GATEWAY_TOOL_SEPARATOR, isGatewayToolName } from '@/lib/gateway-tools'import { formatResponse } from '@/lib/response'import { APP_DATA_META_KEY } from '@/ui-apps/types'-import { type ExecLearnCatalog, QUALIFIED_IDENTIFIER, tokenizeLearnInput } from './exec-learn'+import { type ExecLearnCatalog } from './exec-learn'import { TOKEN_CHAR_LIMIT, listAvailablePaths, resolveSchemaPath, summarizeSchema } from './schema-utils'import { type BuiltInSkillHint, formatSkillLookupMiss, type SkillLookupMissKind } from './skills/notFound'import { isRegexPattern, searchToolsRanked, searchToolsRegex } from './tool-search'@@ -164,26 +164,9 @@ export interface ExecCommandMeta {export type ExecCommandTracker = (meta: ExecCommandMeta) => void-/**- * Session-scoped skill-usage markers backing the skills-first gate. Product- * `call`s in a session that ran no `learn` load are rejected with a retryable- * instruction — interaction-time enforcement of the SKILLS FIRST prompt section,- * which agents demonstrably rationalize their way past when it is advisory only.- * `call --no-skills` acknowledges that no skill applies and opens the gate for- * the rest of the session.- */-export interface SkillsSessionState {- hasLearned(): Promise<boolean>- markLearned(): Promise<void>- hasAcknowledgedNoSkills(): Promise<boolean>- markAcknowledgedNoSkills(): Promise<void>-}-export interface ExecToolOptions {requireDestructiveConfirmation?: booleanlearnCatalog?: ExecLearnCatalog- /** Present only when skill distribution is enabled and the client has a session. */- skillsSession?: SkillsSessionState/*** Client is an inline-exec UI-app host that renders MCP UI apps on the exec* response (Claude Code, Cowork). Gets the same UI-app payload treatment as the@@ -214,10 +197,7 @@ export interface ExecToolOptions {builtInSkillHint?: BuiltInSkillHint}-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>"`, 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 ...`.'+const CALL_USAGE = 'Usage: call [--json] [--confirm] <tool_name> <json_input>'/*** Plain errors out of the learn catalog are agent mistakes — unknown names, bad@@ -233,58 +213,6 @@ function classifyLearnError(error: unknown): unknown {return new ExecCommandError(error.message, reason)}-/**- * True when a `learn` input loads skill content (a qualified `source:skill` read,- * including file reads within a skill). Generic guide reads, listings, searches,- * and describes don't count — a guide is not a skill, and opening the gate on- * `learn analytics` would restore exactly the bypass the gate exists to catch.- *- * Uses the dispatcher's quote-aware tokenizer so a quoted flag (`learn '-s' ...`)- * or quoted identifier (`learn 'posthog:x'`) resolves the same way it dispatches —- * a naive whitespace split disagrees on both. An unterminated quote can't be a- * skill load (and `execute` would have thrown first), so it returns false.- */-function isSkillLoad(rest: string): boolean {- let tokens: string[]- try {- tokens = tokenizeLearnInput(rest)- } catch {- return false- }- if (tokens[0] === 'skills' || tokens[0] === '-s' || tokens[0] === '-d') {- return false- }- return tokens.some((token) => QUALIFIED_IDENTIFIER.test(token))-}--/**- * Returns the gate rejection message, or undefined when the call may proceed.- * A session-store hiccup opens the gate — enforcement must never break tools.- */-async function resolveSkillsGate(- session: SkillsSessionState | undefined,- noSkillsFlag: boolean-): Promise<string | undefined> {- if (!session) {- return undefined- }- try {- if (noSkillsFlag) {- await session.markAcknowledgedNoSkills()- return undefined- }- if (await session.hasLearned()) {- return undefined- }- if (await session.hasAcknowledgedNoSkills()) {- return undefined- }- return SKILLS_GATE_MESSAGE- } catch {- return undefined- }-}-function makeExecSchema(commandReference: string): z.ZodObject<{ command: z.ZodString }> {return z.object({command: z.string().describe(commandReference),@@ -379,11 +307,10 @@ function batchedCommandMessage(commands: string[]): string {].join('\n')}-function parseCallFlags(input: string): { forceJson: boolean; confirmed: boolean; noSkills: boolean; rest: string } {+function parseCallFlags(input: string): { forceJson: boolean; confirmed: boolean; rest: string } {let rest = input.trim()let forceJson = falselet confirmed = false- let noSkills = falsewhile (rest) {const parsed = parseCommand(rest)@@ -398,14 +325,14 @@ function parseCallFlags(input: string): { forceJson: boolean; confirmed: booleancontinue}if (parsed.verb === '--no-skills') {- noSkills = true+ // Ignore for backward compatibility with clients that still send this flag.rest = parsed.restcontinue}break}- return { forceJson, confirmed, noSkills, rest }+ return { forceJson, confirmed, rest }}// Extracts the inner tool name from an exec `call` command, e.g.@@ -1634,11 +1561,6 @@ export function createExecTool(} catch (error) {throw classifyLearnError(error)}- // Only skill loads count as "learned" — a search whose results are- // then ignored is exactly the bypass the gate exists to catch.- if (options.skillsSession && isSkillLoad(rest)) {- await options.skillsSession.markLearned().catch(() => undefined)- }return learnResult}@@ -1852,16 +1774,12 @@ export function createExecTool(// belongs in the `internal` bucket its siblings are kept out of.throw new Error('Cannot call PostHog tools without an API context')}- const { forceJson, confirmed, noSkills, rest: callArgs } = parseCallFlags(rest)+ const { forceJson, confirmed, rest: callArgs } = parseCallFlags(rest)if (!callArgs) {throw new ExecCommandError(CALL_USAGE, 'usage')}const { verb: toolName, rest: jsonBody } = parseCommand(callArgs)const tool = findTool(await resolveTools(), scopeGatedTools, flagGatedTools, toolName)- const gateMessage = await resolveSkillsGate(options.skillsSession, noSkills)- if (gateMessage) {- throw new ExecCommandError(gateMessage, 'skills_gate')- }if (options.requireDestructiveConfirmation && tool.annotations.destructiveHint && !confirmed) {throw new ExecCommandError(`Tool "${tool.name}" is destructive. Re-run with "call --confirm ${tool.name} ..." after verifying the target IDs. Use "info ${tool.name}" to inspect the tool first.`,diff --git a/services/mcp/tests/unit/exec.test.ts b/services/mcp/tests/unit/exec.test.tsindex 8ed71100e8a7..c4db7e2ed272 100644--- a/services/mcp/tests/unit/exec.test.ts+++ b/services/mcp/tests/unit/exec.test.ts@@ -4,13 +4,12 @@ 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 { handleToolError, PostHogApiError, ToolInputValidationError } from '@/lib/errors'+import { PostHogApiError, ToolInputValidationError } from '@/lib/errors'import { estimateTokens } from '@/lib/estimate-tokens'import { formatResponse } from '@/lib/response'import { buildQueryToolsBlock, buildToolDomainsCompact } from '@/lib/instructions'import { InstructionsFormatter } from '@/lib/instructions-formatter'import { SessionManager } from '@/lib/SessionManager'-import { makeSkillFile, SkillCatalog } from '@/skills/skill-catalog'import { getToolsFromContext } from '@/tools'import {createExecTool,@@ -173,184 +172,6 @@ describe('exec tool', () => {})})- describe('skills-first gate', () => {- const guideCatalog = (withGuides = true): ExecLearnCatalog =>- new ExecLearnCatalog(- withGuides- ? [{ id: 'analytics', title: 'Analytics', description: 'Guidance.', content: 'Use the tools.' }]- : [],- {- posthog: new SkillCatalog([- {- name: 'bot-traffic',- description: 'Filtering bot traffic.',- files: [makeSkillFile('SKILL.md', '# Bot traffic\n\nFilter bots.')],- },- ]),- }- )-- function makeSkillsSession(): NonNullable<ExecToolOptions['skillsSession']> {- const state: { learnedAt?: number; ackAt?: number } = {}- return {- hasLearned: async () => state.learnedAt !== undefined,- markLearned: async () => {- state.learnedAt = Date.now()- },- hasAcknowledgedNoSkills: async () => state.ackAt !== undefined,- markAcknowledgedNoSkills: async () => {- state.ackAt = Date.now()- },- }- }-- 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(),- })-- const command = `call ${name} {}`- await expect(exec.handler(mockContext, { command })).rejects.toMatchObject({- name: 'ExecCommandError',- reason: 'skills_gate',- 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>"',- },- {- command: 'learn posthog:bot-traffic/SKILL.md',- hint: 'Separate the skill name and file path with a space: `learn <source>:<skill> <path>`.',- recovery: 'learn posthog:bot-traffic SKILL.md',- },- {- command: 'learn posthog:bot-traffic --file SKILL.md',- hint: '`learn` does not support --file. Pass the file path directly: `learn <source>:<skill> <path>`.',- recovery: 'learn posthog:bot-traffic SKILL.md',- },- {- command: 'learn posthog:bot-traffic SKILL.md --file',- hint: '`learn` does not support --file. Pass the file path directly: `learn <source>:<skill> <path>`.',- recovery: 'learn posthog:bot-traffic SKILL.md',- },- ])('returns recovery guidance for $command without opening the gate', async ({ command, hint, recovery }) => {- 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: recovery ?? 'learn posthog:bot-traffic' })- await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()- })-- // Each of these is a way an agent can touch `learn` without loading a skill; none- // may open the gate, and the quoting cases fail a naive whitespace split.- it.each([- { label: 'a generic guide read', command: 'learn analytics' },- { label: 'a bare search', command: 'learn -s bot traffic' },- { label: 'a quoted search flag', command: "learn '-s' bot traffic" },- { label: 'a listing', command: 'learn skills' },- ])('does not open the gate for $label', async ({ command }) => {- const exec = createExec(undefined, undefined, {- learnCatalog: guideCatalog(),- skillsSession: makeSkillsSession(),- })-- await exec.handler(mockContext, { command })-- await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).rejects.toThrow(- 'No skills loaded this session'- )- })-- it('opens the gate when the skill identifier is quoted', async () => {- const exec = createExec(undefined, undefined, {- learnCatalog: guideCatalog(),- skillsSession: makeSkillsSession(),- })-- // A leading quote defeats a naive `startsWith('posthog:')` check, so a- // real skill load would fail to open the gate.- await exec.handler(mockContext, { command: "learn 'posthog:bot-traffic'" })-- await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()- })-- it('call --no-skills acknowledges once and opens the gate for the session', async () => {- const exec = createExec(undefined, undefined, {- learnCatalog: guideCatalog(),- skillsSession: makeSkillsSession(),- })-- await expect(exec.handler(mockContext, { command: 'call --no-skills mock-tool {}' })).resolves.toBeDefined()- await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()- })-- it('opens the gate when the session store fails', async () => {- const down = async (): Promise<never> => {- throw new Error('redis down')- }- const failing: NonNullable<ExecToolOptions['skillsSession']> = {- hasLearned: down,- markLearned: down,- hasAcknowledgedNoSkills: down,- markAcknowledgedNoSkills: down,- }- const exec = createExec(undefined, undefined, { learnCatalog: guideCatalog(), skillsSession: failing })-- await expect(exec.handler(mockContext, { command: 'learn posthog:bot-traffic' })).resolves.toContain(- 'Bot traffic'- )- await expect(exec.handler(mockContext, { command: 'call mock-tool {}' })).resolves.toBeDefined()- })- })-describe('user-get uuid contract', () => {// `user-get` fetches the caller's own profile, so CLI clients routinely dispatch// `call user-get` with no body — the exec parser then hands the schema an empty@@ -527,20 +348,23 @@ describe('exec tool', () => {it('throws usage error for bare call', async () => {const exec = createExec()await expect(exec.handler(mockContext, { command: 'call' })).rejects.toThrow(- 'Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>'+ 'Usage: call [--json] [--confirm] <tool_name> <json_input>')})it('throws usage error for call --json with no tool name', async () => {const exec = createExec()await expect(exec.handler(mockContext, { command: 'call --json' })).rejects.toThrow(- 'Usage: call [--json] [--confirm] [--no-skills] <tool_name> <json_input>'+ 'Usage: call [--json] [--confirm] <tool_name> <json_input>')})- it('allows --confirm before --json when dispatching a call', async () => {+ it.each([+ { label: '--confirm before --json', command: 'call --confirm --json mock-tool' },+ { label: 'the retired --no-skills flag', command: 'call --no-skills --json mock-tool' },+ ])('dispatches a call with $label', async ({ command }) => {const exec = createExec()- const result = await exec.handler(mockContext, { command: 'call --confirm --json mock-tool' })+ const result = await exec.handler(mockContext, { command })const parsed = JSON.parse(result as string)expect(parsed).toEqual({ id: 1, name: 'test', items: [{ a: 1 }, { a: 2 }] })})