: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): give alerts and subscriptions per-entity _posthogUrl links (#76037)
Matt Pua5241afe39334
diff --git a/products/alerts/mcp/tools.yaml b/products/alerts/mcp/tools.yamlindex 210870194a71..5226ac890978 100644--- a/products/alerts/mcp/tools.yaml+++ b/products/alerts/mcp/tools.yaml@@ -18,6 +18,7 @@ tools:readOnly: falsedestructive: falseidempotent: false+ enrich_url: ?alert_type=insights&alert_id={id}title: Create alertdescription: >Create a new alert on an insight. Alerts can use either threshold-based conditions or anomaly detection. For@@ -74,6 +75,7 @@ tools:readOnly: truedestructive: falseidempotent: true+ enrich_url: ?alert_type=insights&alert_id={id}title: Get alertdescription: >Get a specific alert by ID. Returns the full alert configuration including check results, threshold@@ -108,6 +110,7 @@ tools:readOnly: falsedestructive: falseidempotent: true+ enrich_url: ?alert_type=insights&alert_id={id}title: Update alertdescription: >Update an existing alert by ID. Can update name, threshold, condition, config, detector_config, subscribed@@ -137,6 +140,7 @@ tools:readOnly: truedestructive: falseidempotent: true+ enrich_url: ?alert_type=insights&alert_id={id}list: truetitle: List alertsdescription: >diff --git a/products/subscriptions/mcp/tools.yaml b/products/subscriptions/mcp/tools.yamlindex cf47a45f0d4c..f87f462cfb3c 100644--- a/products/subscriptions/mcp/tools.yaml+++ b/products/subscriptions/mcp/tools.yaml@@ -137,6 +137,7 @@ tools:readOnly: truedestructive: falseidempotent: true+ enrich_url: '{id}'list: truetitle: List subscriptionsdescription: >diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex 464e39af0717..9d770ef5a067 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -945,6 +945,11 @@ function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVar: notedExpression}+ // Joiner between url_prefix and the enrich_url prefix: append `/` for path-segment enrichments,+ // but not when the template continues with a query string (e.g. '?tab=alerts&alert_id={id}')+ // or fragment (e.g. '#runs').+ const joinerFor = (prefix: string): string => (/^[?#]/.test(prefix) ? '' : '/')+if (config.list && config.enrich_url) {const { prefix, field, suffix, source } = parseEnrichUrl(config.enrich_url)// For list endpoints, 'params.x' is not meaningful (items come from the response@@ -954,10 +959,11 @@ function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVar`enrich_url '{params.${field}}' is not supported on list tools — list items are enriched from the response array`)}+ const joiner = joinerFor(prefix)const enriched = [`await withPostHogUrl(context, {`,` ...${resultVar},`,- ` results: await Promise.all((${resultVar}.results ?? []).map((item) => withPostHogUrl(context, item, \`${baseUrl}/${prefix}\${item.${field}}${suffix}\`))),`,+ ` results: await Promise.all((${resultVar}.results ?? []).map((item) => withPostHogUrl(context, item, \`${baseUrl}${joiner}${prefix}\${item.${field}}${suffix}\`))),`,` }, '${baseUrl}')`,].join('\n')return ` return ${wrapped(enriched)}\n`@@ -970,8 +976,9 @@ function buildEnrichment(config: ToolConfig, category: CategoryConfig, resultVarif (config.enrich_url) {const { prefix, field, suffix, source } = parseEnrichUrl(config.enrich_url)const sourceExpr = source === 'params' ? `params.${field}` : `${resultVar}.${field}`+ const joiner = joinerFor(prefix)- return ` return ${wrapped(`await withPostHogUrl(context, ${resultVar}, \`${baseUrl}/${prefix}\${${sourceExpr}}${suffix}\`)`)}\n`+ return ` return ${wrapped(`await withPostHogUrl(context, ${resultVar}, \`${baseUrl}${joiner}${prefix}\${${sourceExpr}}${suffix}\`)`)}\n`}return ` return ${wrapped(resultVar)}\n`diff --git a/services/mcp/src/tools/generated/alerts.ts b/services/mcp/src/tools/generated/alerts.tsindex 4d42f258738e..28bc2b7ead40 100644--- a/services/mcp/src/tools/generated/alerts.ts+++ b/services/mcp/src/tools/generated/alerts.ts@@ -17,7 +17,7 @@ import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'const AlertCreateSchema = AlertsCreateBody-const alertCreate = (): ToolBase<typeof AlertCreateSchema, Schemas.Alert> => ({+const alertCreate = (): ToolBase<typeof AlertCreateSchema, WithPostHogUrl<Schemas.Alert>> => ({name: 'alert-create',schema: AlertCreateSchema,handler: async (context: Context, params: z.infer<typeof AlertCreateSchema>) => {@@ -73,7 +73,7 @@ const alertCreate = (): ToolBase<typeof AlertCreateSchema, Schemas.Alert> => ({path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/`,body,})- return result+ return await withPostHogUrl(context, result, `/alerts?alert_type=insights&alert_id=${result.id}`)},})@@ -94,7 +94,7 @@ const alertDelete = (): ToolBase<typeof AlertDeleteSchema, unknown> => ({const AlertGetSchema = AlertsRetrieveParams.omit({ project_id: true }).extend(AlertsRetrieveQueryParams.shape)-const alertGet = (): ToolBase<typeof AlertGetSchema, Schemas.Alert> => ({+const alertGet = (): ToolBase<typeof AlertGetSchema, WithPostHogUrl<Schemas.Alert>> => ({name: 'alert-get',schema: AlertGetSchema,handler: async (context: Context, params: z.infer<typeof AlertGetSchema>) => {@@ -109,7 +109,7 @@ const alertGet = (): ToolBase<typeof AlertGetSchema, Schemas.Alert> => ({checks_offset: params.checks_offset,},})- return result+ return await withPostHogUrl(context, result, `/alerts?alert_type=insights&alert_id=${result.id}`)},})@@ -147,7 +147,7 @@ const alertSimulate = (): ToolBase<typeof AlertSimulateSchema, Schemas.AlertSimuconst AlertUpdateSchema = AlertsPartialUpdateParams.omit({ project_id: true }).extend(AlertsPartialUpdateBody.shape)-const alertUpdate = (): ToolBase<typeof AlertUpdateSchema, Schemas.Alert> => ({+const alertUpdate = (): ToolBase<typeof AlertUpdateSchema, WithPostHogUrl<Schemas.Alert>> => ({name: 'alert-update',schema: AlertUpdateSchema,handler: async (context: Context, params: z.infer<typeof AlertUpdateSchema>) => {@@ -203,7 +203,7 @@ const alertUpdate = (): ToolBase<typeof AlertUpdateSchema, Schemas.Alert> => ({path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/${encodeURIComponent(String(params.id))}/`,body,})- return result+ return await withPostHogUrl(context, result, `/alerts?alert_type=insights&alert_id=${result.id}`)},})@@ -225,7 +225,18 @@ const alertsList = (): ToolBase<typeof AlertsListSchema, WithPostHogUrl<Schemas.search: params.search,},})- return await withPostHogUrl(context, result, '/alerts')+ return await withPostHogUrl(+ context,+ {+ ...result,+ results: await Promise.all(+ (result.results ?? []).map((item) =>+ withPostHogUrl(context, item, `/alerts?alert_type=insights&alert_id=${item.id}`)+ )+ ),+ },+ '/alerts'+ )},})diff --git a/services/mcp/src/tools/generated/data_warehouse.ts b/services/mcp/src/tools/generated/data_warehouse.tsindex 3e2392023479..23dd7e1dc07e 100644--- a/services/mcp/src/tools/generated/data_warehouse.ts+++ b/services/mcp/src/tools/generated/data_warehouse.ts@@ -200,7 +200,7 @@ const viewCreate = (): ToolBase<typeof ViewCreateSchema, WithPostHogUrl<Schemas.path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/`,body,})- return await withPostHogUrl(context, result, `/sql/?open_view=${result.id}`)+ return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)},})@@ -231,7 +231,7 @@ const viewGet = (): ToolBase<typeof ViewGetSchema, WithPostHogUrl<Schemas.DataWamethod: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/`,})- return await withPostHogUrl(context, result, `/sql/?open_view=${result.id}`)+ return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)},})@@ -258,7 +258,7 @@ const viewList = (): ToolBase<{...result,results: await Promise.all(- (result.results ?? []).map((item) => withPostHogUrl(context, item, `/sql/?open_view=${item.id}`))+ (result.results ?? []).map((item) => withPostHogUrl(context, item, `/sql?open_view=${item.id}`))),},'/sql'@@ -314,7 +314,7 @@ const viewMaterialize = (): ToolBase<path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/materialize/`,body,})- return await withPostHogUrl(context, result, `/sql/?open_view=${result.id}`)+ return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)},})@@ -363,7 +363,7 @@ const viewRun = (): ToolBase<typeof ViewRunSchema, WithPostHogUrl<Schemas.DataWapath: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/run/`,body,})- return await withPostHogUrl(context, result, `/sql/?open_view=${result.id}`)+ return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)},})@@ -378,7 +378,7 @@ const viewRunHistory = (): ToolBase<typeof ViewRunHistorySchema, WithPostHogUrl<method: 'GET',path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/run_history/`,})- return await withPostHogUrl(context, result, `/sql/?open_view=${result.id}`)+ return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)},})@@ -430,7 +430,7 @@ const viewUnmaterialize = (): ToolBase<path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/revert_materialization/`,body,})- return await withPostHogUrl(context, result, `/sql/?open_view=${result.id}`)+ return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)},})@@ -480,7 +480,7 @@ const viewUpdate = (): ToolBase<typeof ViewUpdateSchema, WithPostHogUrl<Schemas.path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/`,body,})- return await withPostHogUrl(context, result, `/sql/?open_view=${result.id}`)+ return await withPostHogUrl(context, result, `/sql?open_view=${result.id}`)},})diff --git a/services/mcp/src/tools/generated/subscriptions.ts b/services/mcp/src/tools/generated/subscriptions.tsindex 9d59de4c48c6..fe2614571de4 100644--- a/services/mcp/src/tools/generated/subscriptions.ts+++ b/services/mcp/src/tools/generated/subscriptions.ts@@ -205,7 +205,16 @@ const subscriptionsList = (): ToolBase<...result,results: (result.results ?? []).map((item: any) => omitResponseFields(item, ['invite_message'])),} as typeof result- return await withPostHogUrl(context, filtered, '/subscriptions')+ return await withPostHogUrl(+ context,+ {+ ...filtered,+ results: await Promise.all(+ (filtered.results ?? []).map((item) => withPostHogUrl(context, item, `/subscriptions/${item.id}`))+ ),+ },+ '/subscriptions'+ )},})diff --git a/services/mcp/src/tools/generated/tracing.ts b/services/mcp/src/tools/generated/tracing.tsindex 139fcee72025..b6e9ad9b7de5 100644--- a/services/mcp/src/tools/generated/tracing.ts+++ b/services/mcp/src/tools/generated/tracing.ts@@ -266,7 +266,7 @@ const apmTraceGet = (): ToolBase<typeof ApmTraceGetSchema, unknown> =>body,})const filtered = pickResponseFields(result, ['results']) as typeof result- return await withPostHogUrl(context, filtered, `/tracing/?trace=${params.trace_id}`)+ return await withPostHogUrl(context, filtered, `/tracing?trace=${params.trace_id}`)},})diff --git a/services/mcp/tests/tools/alerts.integration.test.ts b/services/mcp/tests/tools/alerts.integration.test.tsindex ef6409aa75c5..5540c1252bf9 100644--- a/services/mcp/tests/tools/alerts.integration.test.ts+++ b/services/mcp/tests/tools/alerts.integration.test.ts@@ -98,6 +98,19 @@ describe('Alerts', { concurrent: false }, () => {expect(data._posthogUrl).toContain('/alerts')})+ it('should return a per-alert _posthogUrl on each result', async () => {+ const created = await createTool.handler(context, makeAlertParams())+ const createdAlert = parseToolResponse(created)+ createdAlertIds.push(createdAlert.id)++ const result = await listTool.handler(context, { search: createdAlert.name })+ const data = parseToolResponse(result)++ const found = data.results.find((a: { id: string }) => a.id === createdAlert.id)+ expect(found).toBeTruthy()+ expect(found._posthogUrl).toContain(`/alerts?alert_type=insights&alert_id=${createdAlert.id}`)+ })+it('should respect the limit parameter', async () => {const result = await listTool.handler(context, { limit: 1 })const data = parseToolResponse(result)@@ -190,6 +203,7 @@ describe('Alerts', { concurrent: false }, () => {expect(alert.id).toBe(createdAlert.id)expect(alert.name).toBe(createdAlert.name)expect(alert.threshold).toBeTruthy()+ expect(alert._posthogUrl).toContain(`/alerts?alert_type=insights&alert_id=${createdAlert.id}`)})it('should throw for a non-existent UUID', async () => {diff --git a/services/mcp/tests/unit/generate-tools.test.ts b/services/mcp/tests/unit/generate-tools.test.tsindex 250cd67c90bf..78d1a0c60875 100644--- a/services/mcp/tests/unit/generate-tools.test.ts+++ b/services/mcp/tests/unit/generate-tools.test.ts@@ -360,6 +360,52 @@ describe('generateToolCode with input_schema', () => {expect(result.code).toMatchSnapshot()})+ it('applies list enrichment without inserting a path slash before a query-string prefix', () => {+ const config: ToolConfig = {+ operation: 'things_list',+ enabled: true,+ input_schema: 'ThingListSchema',+ list: true,+ enrich_url: '?tab=alerts&alert_id={id}',+ }+ const resolved = makeResolved({ method: 'GET' })++ const result = generateToolCode(+ 'things-list',+ config,+ resolved,+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )++ expect(result.code).toContain('`/things?tab=alerts&alert_id=${item.id}`')+ })++ it('applies list enrichment without inserting a path slash before a fragment prefix', () => {+ const config: ToolConfig = {+ operation: 'things_list',+ enabled: true,+ input_schema: 'ThingListSchema',+ list: true,+ enrich_url: '#tab-{id}',+ }+ const resolved = makeResolved({ method: 'GET' })++ const result = generateToolCode(+ 'things-list',+ config,+ resolved,+ defaultCategory,+ makeSpec(),+ new Set<string>(),+ stubGetQuerySchema+ )++ expect(result.code).toContain('`/things#tab-${item.id}`')+ })+it('extends the custom schema with a selectable `fields` param and narrows the response', () => {const config: ToolConfig = {operation: 'things_list',