: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(flags): add feature-flag-get-definition-by-key MCP tool (#71312)
posthog[bot]43ba799842bb
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 05ac01a30c16..7f89752d3009 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -2896,6 +2896,13 @@ class FeatureFlagViewSet(required=False,description="Search by feature flag key or name. Case insensitive.",),+ OpenApiParameter(+ "key",+ OpenApiTypes.STR,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by exact feature flag key match. Case insensitive.",+ ),OpenApiParameter("type",OpenApiTypes.STR,@@ -3629,6 +3636,11 @@ class FeatureFlagViewSet(| Q(name__iregex=regex_pattern)| Q(experiment__name__iregex=regex_pattern, experiment__deleted=False)).distinct()+ elif key == "key":+ if isinstance(value, str):+ value = value.strip()+ if value:+ queryset = queryset.filter(key__iexact=value)elif key == "type":if value == "boolean":queryset = queryset.filter(diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 153c108fb2c9..2c10332eb15d 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1791,6 +1791,10 @@ export type FeatureFlagsListParams = {* Filter feature flags by presence of evaluation contexts. 'true' returns only flags with at least one evaluation context, 'false' returns only flags without.*/has_evaluation_contexts?: FeatureFlagsListHasEvaluationContexts+ /**+ * Filter by exact feature flag key match. Case insensitive.+ */+ key?: string/*** Number of results to return per page.*/diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 6ef3323f30a3..55d388507863 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -14,7 +14,7 @@ ui_apps:feature-flag-list:type: listdetail_tool: feature-flag-get-definition- detail_args: '{ flagId: item.id }'+ detail_args: '{ id: item.id }'item_name_field: keyclick_prop: onFlagClickfeature-flag-testing:diff --git a/services/mcp/CONTRIBUTING.md b/services/mcp/CONTRIBUTING.mdindex ea934f79d911..49a342622006 100644--- a/services/mcp/CONTRIBUTING.md+++ b/services/mcp/CONTRIBUTING.md@@ -283,7 +283,10 @@ Convention defaults (derived from the app key and product directory):- `item_name_field` → `name`, `entity_label` → `my entity`Override any field explicitly when the convention doesn't match-(e.g. `click_prop: onFlagClick`, `detail_args: "{ flagId: item.id }"`).+(e.g. `click_prop: onEntityClick`, `detail_args: "{ entityId: item.id }"`).+`detail_args` must match the target tool's actual parameter names —+mismatching them (e.g. passing `flagId` to a tool that expects `id`) silently+drops the argument instead of failing.**Link tools to apps** with `ui_app`:diff --git a/services/mcp/evals/benchmark/tasks.yaml b/services/mcp/evals/benchmark/tasks.yamlindex 193aac781be1..ca87c0c7e7b4 100644--- a/services/mcp/evals/benchmark/tasks.yaml+++ b/services/mcp/evals/benchmark/tasks.yaml@@ -157,9 +157,9 @@ tasks:- id: flag-rollout-conditionscategory: feature-flagsintent: 'What are the rollout conditions for our mcp-analytics feature flag?'- expected_tools: [feature-flag-get-definition]- acceptable_tools: [feature-flag-get-all]- success_criteria: "Resolves the flag's numeric id first, then reports its release conditions — does not guess the id."+ expected_tools: [feature-flag-get-definition-by-key]+ acceptable_tools: [feature-flag-get-all, feature-flag-get-definition]+ success_criteria: "Resolves the flag by its key ('mcp-analytics') directly — does not guess a numeric id."# --- session-replay ----------------------------------------------------------- id: replay-rage-clicksdiff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 4a68828ce2f7..b027c2570f04 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4399,6 +4399,20 @@"readOnlyHint": true}},+ "feature-flag-get-definition-by-key": {+ "description": "Get a feature flag by its string key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the key but not the numeric ID; use `feature-flag-get-definition` when you have the numeric ID.",+ "category": "Feature flags",+ "feature": "flags",+ "summary": "Get a feature flag by its key.",+ "title": "Get feature flag definition by key",+ "required_scopes": ["feature_flag:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"feature-flags-activity-retrieve": {"description": "Get the audit trail for a specific feature flag by ID. Returns a paginated list of changes including who made changes, what was changed, and when. Use limit and page query params for pagination.","category": "Feature flags",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex 85b336522055..cc1f021c8d5d 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -407,6 +407,20 @@"readOnlyHint": false}},+ "feature-flag-get-definition-by-key": {+ "description": "Get a feature flag by its string key (e.g. \"new-checkout\") — the identifier used in code and shown in the UI. Use this when you have the key but not the numeric ID; use `feature-flag-get-definition` when you have the numeric ID.",+ "category": "Feature flags",+ "feature": "flags",+ "summary": "Get a feature flag by its key.",+ "title": "Get feature flag definition by key",+ "required_scopes": ["feature_flag:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"switch-project": {"description": "Switch the active PostHog project for subsequent tool calls. Call this proactively whenever the user names a project or workspace they want to operate on. Use `projects-get` to resolve a project name to an id. If the project isn't found, the user may be referring to a project in a different organization, in which case call `organizations-list` and `switch-organization` first, then retry `projects-get`. Default to the active project when no specific project is mentioned.","category": "Organization & project management",diff --git a/services/mcp/scripts/load-test.ts b/services/mcp/scripts/load-test.tsindex 0688c89c75e5..448cfd8f3969 100644--- a/services/mcp/scripts/load-test.ts+++ b/services/mcp/scripts/load-test.ts@@ -23,6 +23,7 @@ const TOOLS: ToolCall[] = [{ name: 'feature-flag-get-all', arguments: { limit: 5, offset: 10 } },{ name: 'feature-flag-get-all', arguments: { limit: 3, offset: 50 } },{ name: 'feature-flag-get-definition', arguments: { id: 683820 } },+ { name: 'feature-flag-get-definition-by-key', arguments: { key: 'new-checkout' } },{ name: 'dashboards-get-all', arguments: { limit: 3 } },{ name: 'dashboards-get-all', arguments: { limit: 5, search: 'revenue' } },{ name: 'insights-list', arguments: { limit: 3 } },diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 62350f59939d..95cf1bb3e15f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74708,6 +74708,10 @@ export namespace Schemas {* Filter feature flags by presence of evaluation contexts. 'true' returns only flags with at least one evaluation context, 'false' returns only flags without.*/has_evaluation_contexts?: FeatureFlagsListHasEvaluationContexts;+ /**+ * Filter by exact feature flag key match. Case insensitive.+ */+ key?: string;/*** Number of results to return per page.*/diff --git a/services/mcp/src/cli/tools.ts b/services/mcp/src/cli/tools.tsindex 5c6e21f06799..03b48a080e55 100644--- a/services/mcp/src/cli/tools.ts+++ b/services/mcp/src/cli/tools.ts@@ -22,10 +22,7 @@ function materializeTool(}export function getCliTools(options: CliToolOptions = {}): Tool<ZodObjectAny>[] {- const factories: Record<string, () => ToolBase<ZodObjectAny>> = {- ...TOOL_MAP,- ...GENERATED_TOOL_MAP,- }+ const factories: Record<string, () => ToolBase<ZodObjectAny>> = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }const names = getToolsForFeatures({aiConsentGiven: options.aiConsentGiven,})diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.tsindex 812aa9be1d53..bb8075b90f67 100644--- a/services/mcp/src/generated/feature_flags/api.ts+++ b/services/mcp/src/generated/feature_flags/api.ts@@ -95,6 +95,7 @@ export const FeatureFlagsListQueryParams = /* @__PURE__ */ zod.object({.describe("Filter feature flags by presence of evaluation contexts. 'true' returns only flags with at least one evaluation context, 'false' returns only flags without."),+ key: zod.string().optional().describe('Filter by exact feature flag key match. Case insensitive.'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),search: zod.string().optional().describe('Search by feature flag key or name. Case insensitive.'),diff --git a/services/mcp/src/hono/tool-catalog.ts b/services/mcp/src/hono/tool-catalog.tsindex eb8a48ae04c0..efb8bc7eb6ab 100644--- a/services/mcp/src/hono/tool-catalog.ts+++ b/services/mcp/src/hono/tool-catalog.ts@@ -104,10 +104,7 @@ export class ToolCatalog {import('@/tools/generated'),])- const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = {- ...TOOL_MAP,- ...GENERATED_TOOL_MAP,- }+ const allFactories: Record<string, () => ToolBase<ZodObjectAny>> = { ...TOOL_MAP, ...GENERATED_TOOL_MAP }const defs = getToolDefinitions()diff --git a/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts b/services/mcp/src/tools/featureFlags/getDefinitionByKey.tsnew file mode 100644index 000000000000..e38bc393b2e7--- /dev/null+++ b/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts@@ -0,0 +1,67 @@+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import { ToolInputValidationError } from '@/lib/errors'+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'+import type { Context, ToolBase } from '@/tools/types'++/**+ * `feature-flag-get-definition-by-key` fetches a flag by its string key.+ *+ * `feature-flag-get-definition` (generated from `feature_flags_retrieve`) only accepts the+ * flag's numeric ID, but the identifier agents naturally have is the key — the string they see+ * in the UI and in code. This hand-written tool resolves a key to its flag via the list+ * endpoint's `key` filter (a case-insensitive exact match), narrowed to the exact-case match+ * when the filter returns more than one case-variant.+ */+const schema = z.object({+ key: z.string().describe('The feature flag key: the string identifier used in code (e.g. "new-checkout").'),+})++type Params = z.infer<typeof schema>+type Result = WithPostHogUrl<Schemas.FeatureFlag>++const featureFlagGetDefinitionByKey = (): ToolBase<typeof schema, Result> => ({+ name: 'feature-flag-get-definition-by-key',+ schema,+ handler: async (context: Context, params: Params) => {+ const key = params.key.trim()+ if (key === '') {+ throw new ToolInputValidationError('Provide the feature flag key to fetch.')+ }++ const projectId = await context.stateManager.getProjectId()++ // The list endpoint's `key` filter is a case-insensitive exact match, so it can return+ // more than one flag only when two keys differ solely by case — prefer an exact-case+ // match among the results before falling back to whatever case-insensitive match came+ // back. The search result already has the full flag, so it's wrapped directly instead of+ // triggering a redundant fetch-by-id round trip.+ const list = await context.api.request<Schemas.PaginatedFeatureFlagList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(projectId)}/feature_flags/`,+ query: { key, limit: 5 },+ })+ const results = list.results ?? []+ const exact = results.filter((flag) => flag.key === key)+ const matches = exact.length > 0 ? exact : results++ if (matches.length === 0) {+ throw new ToolInputValidationError(+ `No feature flag with key "${key}" found in this project. Use feature-flag-get-all to list ` ++ 'available flags.'+ )+ }+ if (matches.length > 1) {+ const ids = matches.map((flag) => flag.id).join(', ')+ throw new ToolInputValidationError(+ `Multiple feature flags matched key "${key}" (IDs: ${ids}). Pass the numeric \`id\` to ` ++ 'feature-flag-get-definition instead.'+ )+ }+ const flag = matches[0]!+ return await withPostHogUrl(context, flag, `/feature_flags/${flag.id}`)+ },+})++export default featureFlagGetDefinitionByKeydiff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.tsindex 66c1142f10e7..836f4ec1345f 100644--- a/services/mcp/src/tools/generated/feature_flags.ts+++ b/services/mcp/src/tools/generated/feature_flags.ts@@ -141,6 +141,7 @@ const featureFlagGetAll = (): ToolBase<excluded_properties: params.excluded_properties,excluded_tags: params.excluded_tags,has_evaluation_contexts: params.has_evaluation_contexts,+ key: params.key,limit: params.limit,offset: params.offset,search: params.search,diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex 33d00b689a6c..3531a8e6ba8c 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -10,6 +10,8 @@ import debugMcpUiApps from './debug/debugMcpUiApps'// Experiments (hand-written — CRUD + lifecycle are codegen in generated/experiments.ts)import getExperimentResults from './experiments/getResults'import experimentListDeprecated from './experiments/listDeprecated'+// Feature flags (get-definition-by-key is hand-written; get-definition-by-id is codegen)+import featureFlagGetDefinitionByKey from './featureFlags/getDefinitionByKey'// Feedbackimport submitFeedback from './feedback/submit'// Generated tools (from definitions/*.yaml)@@ -64,6 +66,10 @@ export const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {'projects-get': getProjects,'switch-project': setActiveProject,'event-definition-update': updateEventDefinition,++ // Feature flags (get-definition-by-key is hand-written; get-definition by numeric id is codegen)+ 'feature-flag-get-definition-by-key': featureFlagGetDefinitionByKey,+'path-cleaning-rules-update': updatePathCleaning,// Experiments (results is hand-written; CRUD + lifecycle are codegen)diff --git a/services/mcp/src/ui-apps/apps/generated/feature-flag-list.tsx b/services/mcp/src/ui-apps/apps/generated/feature-flag-list.tsxindex 82ea3c10e491..997f092601a5 100644--- a/services/mcp/src/ui-apps/apps/generated/feature-flag-list.tsx+++ b/services/mcp/src/ui-apps/apps/generated/feature-flag-list.tsx@@ -37,7 +37,7 @@ function FeatureFlagListContent({ data, app }: { data: FeatureFlagListData; app:try {const result = await app.callServerTool({name: 'feature-flag-get-definition',- arguments: { flagId: item.id },+ arguments: { id: item.id },})if (result.isError || !result.structuredContent) {fallbackToChat(item.key)diff --git a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsxindex 044755e60a22..76d0b5b240a1 100644--- a/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx+++ b/services/mcp/src/ui-apps/generated/render-dispatch.generated.tsx@@ -236,7 +236,7 @@ function FeatureFlagListContent({ data, app }: { data: FeatureFlagListData; app:try {const result = await app.callServerTool({name: 'feature-flag-get-definition',- arguments: { flagId: item.id },+ arguments: { id: item.id },})if (result.isError || !result.structuredContent) {fallbackToChat(item.key)diff --git a/services/mcp/tests/tools/featureFlags.integration.test.ts b/services/mcp/tests/tools/featureFlags.integration.test.tsindex 34c78cd7b7aa..2becd2891b79 100644--- a/services/mcp/tests/tools/featureFlags.integration.test.ts+++ b/services/mcp/tests/tools/featureFlags.integration.test.ts@@ -12,6 +12,7 @@ import {setActiveProjectAndOrg,validateEnvironmentVariables,} from '@/shared/test-utils'+import featureFlagGetDefinitionByKey from '@/tools/featureFlags/getDefinitionByKey'import { GENERATED_TOOLS } from '@/tools/generated/feature_flags'import { GENERATED_TOOLS as PERSONS_GENERATED_TOOLS } from '@/tools/generated/persons'import type { Context } from '@/tools/types'@@ -207,6 +208,32 @@ describe('Feature flags', { concurrent: false }, () => {})})+ describe('feature-flag-get-definition-by-key tool', () => {+ const getByKeyTool = featureFlagGetDefinitionByKey()+ const createTool = GENERATED_TOOLS['create-feature-flag']!()++ it('should get a feature flag by its exact key', async () => {+ const uniqueKey = generateUniqueKey('by-key-test')+ const createResult = await createTool.handler(context, {+ name: 'By-key test flag',+ key: uniqueKey,+ filters: {+ groups: [{ properties: [], rollout_percentage: 100 }],+ },+ active: true,+ })+ const createdFlag = parseToolResponse(createResult)+ createdResources.featureFlags.push(createdFlag.id)++ const result = await getByKeyTool.handler(context, { key: uniqueKey })+ const flagData = parseToolResponse(result)++ expect(flagData.id).toBe(createdFlag.id)+ expect(flagData.key).toBe(uniqueKey)+ expect(flagData._posthogUrl).toContain('/feature_flags/')+ })+ })+describe('update-feature-flag tool', () => {const updateTool = GENERATED_TOOLS['update-feature-flag']!()const createTool = GENERATED_TOOLS['create-feature-flag']!()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.jsonindex 531d28058ff8..230e96d38d93 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-all.json@@ -37,6 +37,10 @@"enum": ["false", "true"],"type": "string"},+ "key": {+ "description": "Filter by exact feature flag key match. Case insensitive.",+ "type": "string"+ },"limit": {"description": "Number of results to return per page.","type": "number"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-definition-by-key.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-definition-by-key.jsonnew file mode 100644index 000000000000..b64c9bbf2172--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-get-definition-by-key.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "key": {+ "description": "The feature flag key: the string identifier used in code (e.g. \"new-checkout\").",+ "type": "string"+ }+ },+ "required": ["key"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/feature-flag-get-definition-by-key.test.ts b/services/mcp/tests/unit/feature-flag-get-definition-by-key.test.tsnew file mode 100644index 000000000000..5bd291d90753--- /dev/null+++ b/services/mcp/tests/unit/feature-flag-get-definition-by-key.test.ts@@ -0,0 +1,84 @@+import { describe, expect, it, vi } from 'vitest'++import { ToolInputValidationError } from '@/lib/errors'+import featureFlagGetDefinitionByKey from '@/tools/featureFlags/getDefinitionByKey'+import type { Context } from '@/tools/types'++function createMockContext(requestMock: ReturnType<typeof vi.fn>): Context {+ return {+ api: {+ request: requestMock,+ getProjectBaseUrl: (projectId: string) => `https://us.posthog.com/project/${projectId}`,+ } as any,+ stateManager: { getProjectId: vi.fn().mockResolvedValue('42') } as any,+ env: {} as any,+ sessionManager: {} as any,+ cache: {} as any,+ getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},+ }+}++const flag = (id: number, key: string): { id: number; key: string; name: string } => ({ id, key, name: key })++describe('feature-flag-get-definition-by-key', () => {+ const tool = featureFlagGetDefinitionByKey()++ it('resolves a key from the search result, without a second fetch', async () => {+ const request = vi.fn().mockResolvedValue({ results: [flag(7, 'new-checkout')] })++ const result = await tool.handler(createMockContext(request), { key: 'new-checkout' })++ // The search result already has the full flag, so it's returned directly instead of+ // triggering a redundant fetch-by-id round trip.+ expect(request).toHaveBeenCalledTimes(1)+ expect(request).toHaveBeenCalledWith({+ method: 'GET',+ path: '/api/projects/42/feature_flags/',+ query: { key: 'new-checkout', limit: 5 },+ })+ expect(result).toMatchObject({ id: 7, key: 'new-checkout' })+ })++ it('picks the exact-case match when the key filter also returns a same-key different-case duplicate', async () => {+ const request = vi.fn().mockResolvedValue({ results: [flag(7, 'checkout'), flag(8, 'Checkout')] })++ const result = await tool.handler(createMockContext(request), { key: 'checkout' })++ expect(result).toMatchObject({ id: 7, key: 'checkout' })+ })++ it('resolves a key case-insensitively when no exact-case match exists', async () => {+ const request = vi.fn().mockResolvedValue({ results: [flag(7, 'New-Checkout')] })++ const result = await tool.handler(createMockContext(request), { key: 'new-checkout' })++ expect(result).toMatchObject({ id: 7, key: 'New-Checkout' })+ })++ it('raises a validation error when a key matches multiple flags only case-insensitively', async () => {+ const request = vi.fn().mockResolvedValue({ results: [flag(7, 'Checkout'), flag(8, 'CHECKOUT')] })++ await expect(tool.handler(createMockContext(request), { key: 'checkout' })).rejects.toBeInstanceOf(+ ToolInputValidationError+ )+ })++ it('raises a validation error naming the missing key when no flag matches', async () => {+ const request = vi.fn().mockResolvedValue({ results: [] })++ await expect(tool.handler(createMockContext(request), { key: 'checkout' })).rejects.toBeInstanceOf(+ ToolInputValidationError+ )+ expect(request).toHaveBeenCalledTimes(1)+ })++ it('raises a validation error for a blank key without calling the API', async () => {+ const request = vi.fn()++ await expect(tool.handler(createMockContext(request), { key: ' ' })).rejects.toBeInstanceOf(+ ToolInputValidationError+ )+ expect(request).not.toHaveBeenCalled()+ })+})