: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): fail codegen when an enabled tool loses its operation (#111783)
Julian Bez8abbf9f53216
diff --git a/posthog/mcp_tool_definitions.py b/posthog/mcp_tool_definitions.pyindex 330eb0f24dfb..8306f738d1d2 100644--- a/posthog/mcp_tool_definitions.py+++ b/posthog/mcp_tool_definitions.py@@ -20,8 +20,8 @@ from posthog.settings.base_variables import BASE_DIR_SCHEMA_DIR = Path(BASE_DIR) / "services" / "mcp" / "schema"-# Hand-written first, generated second, so the generated definition wins on the seven names-# both files hold. This is the precedence `getToolDefinitions()` in+# Hand-written first, generated second, so the generated definition wins on any name both+# files hold. This is the precedence `getToolDefinitions()` in# services/mcp/src/tools/toolDefinitions.ts merges with, and a catalogue built the other way# round would describe a tool the server does not serve. Both files are needed: some tools# exist only as hand-written ones (for example read-data-schema), and they are the only usersdiff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 6a2746ca76a8..75de75100913 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -561,104 +561,6 @@"readOnlyHint": false}},- "survey-create": {- "description": "Creates a new survey in the project. Use this for both in-app surveys and hosted forms. Prefer draft creation by default and do not set start_date unless the user explicitly asks to launch immediately. For in-app surveys, popover is the default unless the user asks for widget or api. For hosted forms, use external_survey. Keep surveys short unless the user asks for a longer flow.",- "category": "Surveys",- "summary": "Creates a new survey in the project.",- "required_scopes": ["survey:write"],- "feature": "surveys",- "title": "Create survey",- "annotations": {- "destructiveHint": false,- "idempotentHint": false,- "openWorldHint": true,- "readOnlyHint": false- }- },- "survey-get": {- "description": "Get a specific survey by ID. Returns its questions, targeting flag — including current property targeting rules under targeting_flag.filters — and scheduling details. To change targeting, use targeting_flag_filters with survey-update.",- "category": "Surveys",- "summary": "Get a specific survey by ID.",- "required_scopes": ["survey:read"],- "feature": "surveys",- "title": "Get survey",- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- }- },- "surveys-get-all": {- "description": "Get all surveys in the project with optional filtering. Can filter by search term or use pagination.",- "category": "Surveys",- "summary": "Get all surveys in the project with optional filtering.",- "required_scopes": ["survey:read"],- "feature": "surveys",- "title": "Get all surveys",- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- }- },- "survey-update": {- "description": "Update an existing survey by ID. Omitted top-level fields are preserved, but nested objects and arrays you provide may replace existing values. Before changing questions, conditions, appearance, targeting, translations, or hosted-form content, retrieve the survey first and preserve fields that should remain. Do not send null to clear a field unless the user explicitly asked to remove it.",- "category": "Surveys",- "summary": "Update an existing survey by ID.",- "required_scopes": ["survey:write"],- "feature": "surveys",- "title": "Update survey",- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- }- },- "survey-delete": {- "description": "Delete a survey by ID (soft delete - marks as archived).",- "category": "Surveys",- "summary": "Delete a survey by ID.",- "required_scopes": ["survey:write"],- "feature": "surveys",- "title": "Delete survey",- "annotations": {- "destructiveHint": true,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- }- },- "surveys-global-stats": {- "description": "Get aggregated response statistics across all surveys in the project. Includes event counts (shown, dismissed, sent), unique respondents, conversion rates, and timing data. Supports optional date filtering.",- "category": "Surveys",- "summary": "Get aggregated response statistics across all surveys.",- "required_scopes": ["survey:read"],- "feature": "surveys",- "title": "Get all survey response stats",- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- }- },- "survey-stats": {- "description": "Get response statistics for a specific survey. Includes detailed event counts (shown, dismissed, sent), unique respondents, conversion rates, and timing data. Supports optional date filtering.",- "category": "Surveys",- "summary": "Get response statistics for a specific survey.",- "required_scopes": ["survey:read"],- "feature": "surveys",- "title": "Get survey response stats",- "annotations": {- "destructiveHint": false,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": true- }- },"debug-mcp-ui-apps": {"description": "Debug tool for testing MCP Apps SDK integration. Returns sample data displayed in an interactive UI app with component showcase. Use this to verify that MCP Apps are working correctly.","category": "Debug",diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex dc7ef8aa51c6..c1f59a208609 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -1717,10 +1717,11 @@ function generateCategoryFile(}const resolved = findOperation(spec, config.operation)if (!resolved) {- console.warn(- `Warning: operationId "${config.operation}" not found in OpenAPI for tool "${name}" — skipping`+ console.error(+ `Enabled tool "${name}": operationId "${config.operation}" not found in OpenAPI. ` ++ `The operationId no longer exists. Fix "operation:" in the tool's YAML, or set "enabled: false" / remove the tool.`)- continue+ process.exit(1)}enabledTools.push([name, config as EnabledToolConfig, resolved])}diff --git a/services/mcp/scripts/scaffold-yaml.ts b/services/mcp/scripts/scaffold-yaml.tsindex 98f3971b7ed2..67bab48cc96d 100644--- a/services/mcp/scripts/scaffold-yaml.ts+++ b/services/mcp/scripts/scaffold-yaml.ts@@ -225,7 +225,15 @@ function mergeWithExisting(tag: string,validOperationIds: Set<string>,subset = false-): { content: string; added: number; removed: number; updated: number; matched: number; unmatchedTools: string[] } {+): {+ content: string+ added: number+ removed: number+ updated: number+ matched: number+ unmatchedTools: string[]+ lostEnabledTools: string[]+} {const parsed = parseYaml(fs.readFileSync(existingPath, 'utf-8'))const result = CategoryConfigSchema.safeParse(parsed)if (!result.success) {@@ -245,6 +253,7 @@ function mergeWithExisting(let updated = 0let matched = 0const unmatchedTools: string[] = []+ const lostEnabledTools: string[] = []// Preserve hand-authored config (enabled, scopes, descriptions, etc.) per tool.// Tool order itself is normalized alphabetically below — see `sortedTools`.@@ -267,6 +276,10 @@ function mergeWithExisting(// different tag/URL space) but warn so missing tags get noticedmergedTools[name] = { ...config }unmatchedTools.push(`${name} (${config.operation})`)+ } else if (config.enabled) {+ // Dropping an enabled tool would silently remove it from the MCP server.+ mergedTools[name] = { ...config }+ lostEnabledTools.push(`${name} (${config.operation})`)} else {unmatchedTools.push(`${name} (${config.operation})`)removed++@@ -278,8 +291,10 @@ function mergeWithExisting(const existingBaseIds = new Set(Object.values(existingTools).map((c) => c.operation.replace(/_\d+$/, '')))for (const op of ops) {const base = op.operationId.replace(/_\d+$/, '')- if (!existingBaseIds.has(base)) {- mergedTools[operationIdToToolName(op.operationId)] = {+ const toolName = operationIdToToolName(op.operationId)+ // A kept enabled tool with a lost operation can share this name. Do not overwrite it.+ if (!existingBaseIds.has(base) && !Object.prototype.hasOwnProperty.call(mergedTools, toolName)) {+ mergedTools[toolName] = {operation: op.operationId,enabled: false,}@@ -314,7 +329,26 @@ function mergeWithExisting(updated,matched,unmatchedTools,+ lostEnabledTools,+ }+}++/**+ * An enabled tool whose operation vanished stays in the YAML. Report it and+ * fail the command so the author fixes it before codegen rejects the file.+ */+function reportLostEnabledTools(lostEnabledTools: string[]): void {+ if (lostEnabledTools.length === 0) {+ return+ }+ process.stderr.write(+ ` ✗ ${lostEnabledTools.length} enabled tool(s) reference an operationId that no longer exists in OpenAPI. ` ++ `Fix "operation:" or set "enabled: false" / remove the tool:\n`+ )+ for (const tool of lostEnabledTools) {+ process.stderr.write(` - ${tool}\n`)}+ process.exitCode = 1}// ------------------------------------------------------------------@@ -404,7 +438,7 @@ function syncAll(spec: OpenApiSpec): void {}const label = path.relative(REPO_ROOT, filePath)const validIds = new Set(rawOps.map((op) => op.operationId))- const { content, added, removed, updated, matched, unmatchedTools } = mergeWithExisting(+ const { content, added, removed, updated, matched, unmatchedTools, lostEnabledTools } = mergeWithExisting(filePath,ops,product,@@ -438,6 +472,7 @@ function syncAll(spec: OpenApiSpec): void {process.stderr.write(` - ${tool}\n`)}}+ reportLostEnabledTools(lostEnabledTools)}formatWithPrettier(writtenFiles)@@ -500,7 +535,7 @@ function main(): void {const validIds = new Set(rawOps.map((op) => op.operationId))if (fs.existsSync(resolvedOutput)) {- const { content, added, removed } = mergeWithExisting(resolvedOutput, ops, name, validIds)+ const { content, added, removed, lostEnabledTools } = mergeWithExisting(resolvedOutput, ops, name, validIds)fs.writeFileSync(resolvedOutput, content)const parts = [`${ops.length} operation(s)`]if (added > 0) {@@ -513,6 +548,7 @@ function main(): void {parts.push('no changes')}process.stdout.write(`${parts.join(', ')} — ${resolvedOutput}\n`)+ reportLostEnabledTools(lostEnabledTools)} else {fs.mkdirSync(path.dirname(resolvedOutput), { recursive: true })fs.writeFileSync(resolvedOutput, generateFreshYaml(ops, name))diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.tsindex 1833814334c1..70cc141d1592 100644--- a/services/mcp/tests/unit/generate-tools.test.ts+++ b/services/mcp/tests/unit/generate-tools.test.ts@@ -1,9 +1,10 @@-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'import {buildResponseFilter,composeToolSchema,extractPathParams,+ generateCategoryFile,generateDefinitionsJson,generateQueryWrapperDefinitionsJson,generateQueryWrapperFile,@@ -1385,7 +1386,12 @@ describe('per-tool category in tool definitions', () => {}const definitions = generateDefinitionsJson([{- config: { category: 'AI observability', feature: 'llm_analytics', url_prefix: '/ai-observability', tools: {} },+ config: {+ category: 'AI observability',+ feature: 'llm_analytics',+ url_prefix: '/ai-observability',+ tools: {},+ },enabledTools: [['llma-prompt-list', toolConfig, resolved]],enabledWrappers: [],yamlDir: '/tmp',@@ -2400,3 +2406,34 @@ describe('composeToolSchema param aliases', () => {)})})++describe('generateCategoryFile with a missing operation', () => {+ const tool = {+ operation: 'things_gone',+ scopes: ['thing:read'],+ annotations: { readOnly: true, destructive: false, idempotent: true },+ }++ it.each([+ { name: 'exits for an enabled tool', enabled: true, exits: true },+ { name: 'skips a disabled tool', enabled: false, exits: false },+ ])('$name', ({ enabled, exits }) => {+ const exit = vi.spyOn(process, 'exit').mockImplementation((() => {+ throw new Error('process.exit')+ }) as never)+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const category = { ...defaultCategory, tools: { 'thing-get': { ...tool, enabled } } }+ const generate = (): unknown =>+ generateCategoryFile(category, 'things.yaml', 'things', makeSpec(), new Set(), stubGetQuerySchema as never)++ if (exits) {+ expect(generate).toThrow('process.exit')+ expect(exit).toHaveBeenCalledWith(1)+ expect(error).toHaveBeenCalledWith(expect.stringContaining('things_gone'))+ } else {+ expect(generate).not.toThrow()+ expect(exit).not.toHaveBeenCalled()+ }+ vi.restoreAllMocks()+ })+})