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(mcp): resolve eight-digit numeric insight ids in insight-query (#115678)

posthog[bot]979b562ec0b9
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index c54b6cb9de0a..03995ca82604 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -707,7 +707,6 @@
"type": "object",
"properties": {
"insightId": {
- "description": "The insight to run: its numeric `id` or 8-character `short_id`.",
"anyOf": [
{
"type": "string"
@@ -715,7 +714,8 @@
{
"type": "number"
}
- ]
+ ],
+ "description": "The insight to run: its numeric `id` or 8-character `short_id`."
},
"output_format": {
"default": "optimized",
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 7cad300b022f..a3b6ed7deeb6 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -1262,7 +1262,7 @@ export class ApiClient {
variables_override,
filters_override,
}: {
- insightId: string
+ insightId: string | number
variables_override?: string
filters_override?: string
}): Promise<Result<Schemas.Insight>> => {
@@ -1274,39 +1274,46 @@ export class ApiClient {
params.set('filters_override', filters_override)
}
- // Check if insightId is a short_id (8 character alphanumeric string)
- // Note: This won't work when we start creating insight id's with 8 digits. (We're at 7 currently)
- if (isShortId(insightId)) {
- // The list endpoint accepts ?short_id=... and runs the same
- // InsightSerializer.to_representation, which applies
- // variables_override / filters_override from query_params. So
- // short_id resolution + override application happen in one hop.
- params.set('short_id', insightId)
- const url = `${this.baseUrl}/api/projects/${projectId}/insights/?${params}`
-
- const result = await this.fetchJson<{ results: Schemas.Insight[] }>(url)
+ const retrieveById = (): Promise<Result<Schemas.Insight>> => {
+ const queryString = params.toString() ? `?${params}` : ''
+ return this.fetchJson<Schemas.Insight>(
+ `${this.baseUrl}/api/projects/${projectId}/insights/${insightId}/${queryString}`
+ )
+ }
- if (!result.success) {
- return result
- }
+ // A number is always a numeric id. Eight-digit ids also match the short_id syntax.
+ if (typeof insightId === 'number' || !isShortId(insightId)) {
+ return retrieveById()
+ }
- const insights = result.data.results
- const insight = insights[0]
+ // The list endpoint accepts ?short_id=... and runs the same
+ // InsightSerializer.to_representation, which applies
+ // variables_override / filters_override from query_params. So
+ // short_id resolution + override application happen in one hop.
+ const listParams = new URLSearchParams(params)
+ listParams.set('short_id', insightId)
+ const result = await this.fetchJson<{ results: Schemas.Insight[] }>(
+ `${this.baseUrl}/api/projects/${projectId}/insights/?${listParams}`
+ )
- if (insights.length === 0 || !insight) {
- return {
- success: false,
- error: new Error(`No insight found with short_id: ${insightId}`),
- }
- }
+ if (!result.success) {
+ return result
+ }
+ const insight = result.data.results[0]
+ if (insight) {
return { success: true, data: insight }
}
- const queryString = params.toString() ? `?${params}` : ''
- return this.fetchJson<Schemas.Insight>(
- `${this.baseUrl}/api/projects/${projectId}/insights/${insightId}/${queryString}`
- )
+ // Short ids are random alphanumerics, so an all-digit string can be either kind of id.
+ if (/^\d+$/.test(insightId)) {
+ return retrieveById()
+ }
+
+ return {
+ success: false,
+ error: new Error(`No insight found with short_id: ${insightId}`),
+ }
},
create: async ({ data }: { data: Record<string, any> }): Promise<Result<Schemas.Insight>> => {
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 966c5b37f5ac..0b0a115f21e4 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -507,7 +507,6 @@ export const InsightQueryInputSchema = z.preprocess(
z.object({
insightId: z
.union([z.string(), z.number()])
- .transform((value) => String(value))
.describe('The insight to run: its numeric `id` or 8-character `short_id`.'),
output_format: z
.enum(['optimized', 'json'])
diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.ts
index ae7767035c4a..5670b648ca74 100644
--- a/services/mcp/tests/unit/api-client.test.ts
+++ b/services/mcp/tests/unit/api-client.test.ts
@@ -418,6 +418,60 @@ describe('ApiClient', () => {
vi.unstubAllGlobals()
})
+
+ it.each([
+ ['a seven-digit number', 1234567, 'https://example.com/api/projects/1/insights/1234567/'],
+ ['an eight-digit number', 12345678, 'https://example.com/api/projects/1/insights/12345678/'],
+ ['a seven-digit numeric string', '1234567', 'https://example.com/api/projects/1/insights/1234567/'],
+ ])('resolves %s through the retrieve endpoint only', async (_label, insightId, expectedUrl) => {
+ const { client, mockFetch } = setupClient()
+ mockFetch.mockResolvedValueOnce(
+ new Response(JSON.stringify({ id: 42, short_id: 'abc12345' }), { status: 200 })
+ )
+
+ const result = await client.insights({ projectId: '1' }).get({ insightId })
+
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ expect(mockFetch.mock.calls[0]![0]).toBe(expectedUrl)
+ expect(result.success).toBe(true)
+
+ vi.unstubAllGlobals()
+ })
+
+ it.each([
+ ['an all-digit short_id', { results: [{ id: 42, short_id: '12345678' }] }, 1],
+ ['a numeric id with no short_id match', { results: [] }, 2],
+ ])('resolves an eight-digit numeric string that is %s', async (_label, listBody, expectedCalls) => {
+ const { client, mockFetch } = setupClient()
+ mockFetch
+ .mockResolvedValueOnce(new Response(JSON.stringify(listBody), { status: 200 }))
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ id: 12345678, short_id: 'abc12345' }), { status: 200 })
+ )
+
+ const result = await client.insights({ projectId: '1' }).get({ insightId: '12345678' })
+
+ expect(mockFetch).toHaveBeenCalledTimes(expectedCalls)
+ expect(mockFetch.mock.calls[0]![0]).toContain('/api/projects/1/insights/?short_id=12345678')
+ if (expectedCalls === 2) {
+ expect(mockFetch.mock.calls[1]![0]).toBe('https://example.com/api/projects/1/insights/12345678/')
+ }
+ expect(result.success).toBe(true)
+
+ vi.unstubAllGlobals()
+ })
+
+ it('reports a missing alphanumeric short_id without a retrieve fallback', async () => {
+ const { client, mockFetch } = setupClient()
+ mockFetch.mockResolvedValueOnce(new Response(JSON.stringify({ results: [] }), { status: 200 }))
+
+ const result = await client.insights({ projectId: '1' }).get({ insightId: 'abc12345' })
+
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ expect(result.success).toBe(false)
+
+ vi.unstubAllGlobals()
+ })
})
describe('actors query paging', () => {
diff --git a/services/mcp/tests/unit/insight-id-aliases.test.ts b/services/mcp/tests/unit/insight-id-aliases.test.ts
index dc15124608f4..df0900b43396 100644
--- a/services/mcp/tests/unit/insight-id-aliases.test.ts
+++ b/services/mcp/tests/unit/insight-id-aliases.test.ts
@@ -41,17 +41,19 @@ describe('insight id aliases', () => {
}
)
- describe('insight-query normalizes aliases to `insightId` and coerces numbers to string', () => {
+ // Numbers must stay numbers: an eight-digit numeric id also matches the short_id syntax.
+ describe('insight-query normalizes aliases to `insightId` and keeps the input type', () => {
it.each([
['insightId (string)', { insightId: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
- ['insightId (numeric)', { insightId: 36 }, '36'],
- ['id (numeric)', { id: 36 }, '36'],
+ ['insightId (numeric)', { insightId: 36 }, 36],
+ ['insightId (eight-digit numeric)', { insightId: 12345678 }, 12345678],
+ ['id (numeric)', { id: 36 }, 36],
['id (string)', { id: '36' }, '36'],
- ['insight_id', { insight_id: 36 }, '36'],
+ ['insight_id', { insight_id: 36 }, 36],
['short_id', { short_id: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
['shortId', { shortId: 'AaVQ8Ijw' }, 'AaVQ8Ijw'],
- ['insightId over aliases on conflict', { insightId: 1, id: 2 }, '1'],
- ['first-listed alias on alias conflict', { id: 2, short_id: 'AaVQ8Ijw' }, '2'],
+ ['insightId over aliases on conflict', { insightId: 1, id: 2 }, 1],
+ ['first-listed alias on alias conflict', { id: 2, short_id: 'AaVQ8Ijw' }, 2],
])('accepts %s', (_label, input, expected) => {
const result = InsightQueryInputSchema.safeParse(input)
expect(result.success).toBe(true)