Skip to content

: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.

fix(flags): return not-found as data from feature-flag-get-definition-by-key (#72736)

posthog[bot]750c3bf6bdce
diff --git a/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts b/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts
index e38bc393b2e7..fb21b5281926 100644
--- a/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts
+++ b/services/mcp/src/tools/featureFlags/getDefinitionByKey.ts
@@ -13,13 +13,30 @@ import type { Context, ToolBase } from '@/tools/types'
* 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.
+ *
+ * A key that matches no flag is not an error. The dominant caller is an agent checking whether
+ * a flag exists before creating it (a read-before-create existence check), so a miss is the
+ * expected answer: it returns a structured `{ found: false }` result naming the key and
+ * pointing at the list/create path. The caller's next step, creating the flag, doesn't depend
+ * on this being an exception. Reuse this not-found-as-data pattern for other existence checks;
+ * keep throwing where the caller expects the target to already exist, so a miss signals a
+ * genuine problem rather than an expected outcome.
*/
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>
+
+/** The result shape returned when no flag matches `key`. See the file doc comment for why this is data, not a thrown error. */
+interface FeatureFlagLookupMiss {
+ found: false
+ key: string
+ message: string
+}
+
+/** Discriminate on `found` in both branches, so callers don't have to test for its absence on a match. */
+type Result = (WithPostHogUrl<Schemas.FeatureFlag> & { found: true }) | FeatureFlagLookupMiss
const featureFlagGetDefinitionByKey = (): ToolBase<typeof schema, Result> => ({
name: 'feature-flag-get-definition-by-key',
@@ -47,12 +64,17 @@ const featureFlagGetDefinitionByKey = (): ToolBase<typeof schema, Result> => ({
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.'
- )
+ return {
+ found: false,
+ key,
+ message:
+ `No feature flag with key "${key}" exists in this project. ` +
+ 'Create it with `create-feature-flag`, or call `feature-flag-get-all` to list existing flags.',
+ }
}
if (matches.length > 1) {
+ // Unlike a miss, this is still an error: the key is ambiguous and the agent can't
+ // proceed on its own — it needs the numeric id from a different tool call.
const ids = matches.map((flag) => flag.id).join(', ')
throw new ToolInputValidationError(
`Multiple feature flags matched key "${key}" (IDs: ${ids}). Pass the numeric \`id\` to ` +
@@ -60,7 +82,8 @@ const featureFlagGetDefinitionByKey = (): ToolBase<typeof schema, Result> => ({
)
}
const flag = matches[0]!
- return await withPostHogUrl(context, flag, `/feature_flags/${flag.id}`)
+ const flagWithUrl = await withPostHogUrl(context, flag, `/feature_flags/${flag.id}`)
+ return { ...flagWithUrl, found: true }
},
})
diff --git a/services/mcp/tests/tools/featureFlags.integration.test.ts b/services/mcp/tests/tools/featureFlags.integration.test.ts
index 2becd2891b79..ceef62e58e3b 100644
--- a/services/mcp/tests/tools/featureFlags.integration.test.ts
+++ b/services/mcp/tests/tools/featureFlags.integration.test.ts
@@ -231,6 +231,17 @@ describe('Feature flags', { concurrent: false }, () => {
expect(flagData.id).toBe(createdFlag.id)
expect(flagData.key).toBe(uniqueKey)
expect(flagData._posthogUrl).toContain('/feature_flags/')
+ expect(flagData.found).toBe(true)
+ })
+
+ it('should return a non-error found:false result for a flag that does not exist', async () => {
+ const missingKey = generateUniqueKey('does-not-exist')
+
+ const result = await getByKeyTool.handler(context, { key: missingKey })
+ const flagData = parseToolResponse(result)
+
+ expect(flagData.found).toBe(false)
+ expect(flagData.key).toBe(missingKey)
})
})
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.ts
index 5bd291d90753..3757992cca85 100644
--- 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.ts
@@ -37,7 +37,7 @@ describe('feature-flag-get-definition-by-key', () => {
path: '/api/projects/42/feature_flags/',
query: { key: 'new-checkout', limit: 5 },
})
- expect(result).toMatchObject({ id: 7, key: 'new-checkout' })
+ expect(result).toMatchObject({ id: 7, key: 'new-checkout', found: true })
})
it('picks the exact-case match when the key filter also returns a same-key different-case duplicate', async () => {
@@ -45,7 +45,7 @@ describe('feature-flag-get-definition-by-key', () => {
const result = await tool.handler(createMockContext(request), { key: 'checkout' })
- expect(result).toMatchObject({ id: 7, key: 'checkout' })
+ expect(result).toMatchObject({ id: 7, key: 'checkout', found: true })
})
it('resolves a key case-insensitively when no exact-case match exists', async () => {
@@ -53,7 +53,7 @@ describe('feature-flag-get-definition-by-key', () => {
const result = await tool.handler(createMockContext(request), { key: 'new-checkout' })
- expect(result).toMatchObject({ id: 7, key: 'New-Checkout' })
+ expect(result).toMatchObject({ id: 7, key: 'New-Checkout', found: true })
})
it('raises a validation error when a key matches multiple flags only case-insensitively', async () => {
@@ -64,12 +64,13 @@ describe('feature-flag-get-definition-by-key', () => {
)
})
- it('raises a validation error naming the missing key when no flag matches', async () => {
+ it('returns a non-error found:false result 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
- )
+ const result = await tool.handler(createMockContext(request), { key: 'checkout' })
+
+ expect(result).toMatchObject({ found: false, key: 'checkout' })
+ expect((result as { message: string }).message).toContain('checkout')
expect(request).toHaveBeenCalledTimes(1)
})