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.

15.2 KB
Raw Blame
// AUTO-GENERATED from products/alerts/mcp/tools.yaml + OpenAPI — do not edit
import { z } from 'zod'

import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/alerts/api'
import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'

const AlertCreateSchema = () => {
    const AlertsCreateBody = orvalSchemas.AlertsCreateBody()
    return AlertsCreateBody
}

const alertCreate = (): ToolBase<ReturnType<typeof AlertCreateSchema>, WithPostHogUrl<Schemas.Alert>> => ({
    name: 'alert-create',
    schema: AlertCreateSchema(),
    handler: async (context: Context, params: z.infer<ReturnType<typeof AlertCreateSchema>>) => {
        const projectId = await context.stateManager.getProjectId()
        const body: Record<string, unknown> = {}
        if (params.insight !== undefined) {
            body['insight'] = params.insight
        }
        if (params.name !== undefined) {
            body['name'] = params.name
        }
        if (params.subscribed_users !== undefined) {
            body['subscribed_users'] = params.subscribed_users
        }
        if (params.threshold !== undefined) {
            body['threshold'] = params.threshold
        }
        if (params.condition !== undefined) {
            body['condition'] = params.condition
        }
        if (params.enabled !== undefined) {
            body['enabled'] = params.enabled
        }
        if (params.schedule_start_time !== undefined) {
            body['schedule_start_time'] = params.schedule_start_time
        }
        if (params.config !== undefined) {
            body['config'] = params.config
        }
        if (params.detector_config !== undefined) {
            body['detector_config'] = params.detector_config
        }
        if (params.evaluation_delay_intervals !== undefined) {
            body['evaluation_delay_intervals'] = params.evaluation_delay_intervals
        }
        if (params.calculation_interval !== undefined) {
            body['calculation_interval'] = params.calculation_interval
        }
        if (params.snoozed_until !== undefined) {
            body['snoozed_until'] = params.snoozed_until
        }
        if (params.skip_weekend !== undefined) {
            body['skip_weekend'] = params.skip_weekend
        }
        if (params.schedule_restriction !== undefined) {
            body['schedule_restriction'] = params.schedule_restriction
        }
        if (params.investigation_agent_enabled !== undefined) {
            body['investigation_agent_enabled'] = params.investigation_agent_enabled
        }
        if (params.investigation_gates_notifications !== undefined) {
            body['investigation_gates_notifications'] = params.investigation_gates_notifications
        }
        if (params.investigation_inconclusive_action !== undefined) {
            body['investigation_inconclusive_action'] = params.investigation_inconclusive_action
        }
        const result = await context.api.request<Schemas.Alert>({
            method: 'POST',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/`,
            body,
        })
        return await withPostHogUrl(context, result, `/alerts?alert_type=insights&alert_id=${result.id}`)
    },
})

const AlertDeleteSchema = () => {
    const AlertsDestroyParams = orvalSchemas.AlertsDestroyParams()
    return AlertsDestroyParams.omit({ project_id: true })
}

const alertDelete = (): ToolBase<ReturnType<typeof AlertDeleteSchema>, unknown> => ({
    name: 'alert-delete',
    schema: AlertDeleteSchema(),
    handler: async (context: Context, params: z.infer<ReturnType<typeof AlertDeleteSchema>>) => {
        const projectId = await context.stateManager.getProjectId()
        const result = await context.api.request<unknown>({
            method: 'DELETE',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/${encodeURIComponent(String(params.id))}/`,
        })
        return result
    },
})

const AlertDestinationsCreateSchema = () => {
    const AlertsDestinationsCreateBody = orvalSchemas.AlertsDestinationsCreateBody()
    const AlertsDestinationsCreateParams = orvalSchemas.AlertsDestinationsCreateParams()
    return AlertsDestinationsCreateParams.omit({ project_id: true })
        .extend(AlertsDestinationsCreateBody.shape)
        .extend({
            type: AlertsDestinationsCreateBody.shape['type'].describe(
                'Destination type. Slack is the only type this tool creates.'
            ),
            slack_workspace_id: AlertsDestinationsCreateBody.shape['slack_workspace_id'].describe(
                'Integration ID of the connected Slack workspace.'
            ),
            slack_channel_id: AlertsDestinationsCreateBody.shape['slack_channel_id'].describe(
                'Slack channel ID to post in, for example C0123456789.'
            ),
            slack_channel_name: AlertsDestinationsCreateBody.shape['slack_channel_name'].describe(
                'Optional channel name shown on the destination.'
            ),
        })
}

const alertDestinationsCreate = (): ToolBase<
    ReturnType<typeof AlertDestinationsCreateSchema>,
    Schemas.AlertDestinationResponse
> => ({
    name: 'alert-destinations-create',
    schema: AlertDestinationsCreateSchema(),
    handler: async (context: Context, params: z.infer<ReturnType<typeof AlertDestinationsCreateSchema>>) => {
        const projectId = await context.stateManager.getProjectId()
        const body: Record<string, unknown> = {}
        if (params.type !== undefined) {
            body['type'] = params.type
        }
        if (params.slack_workspace_id !== undefined) {
            body['slack_workspace_id'] = params.slack_workspace_id
        }
        if (params.slack_channel_id !== undefined) {
            body['slack_channel_id'] = params.slack_channel_id
        }
        if (params.slack_channel_name !== undefined) {
            body['slack_channel_name'] = params.slack_channel_name
        }
        const result = await context.api.request<Schemas.AlertDestinationResponse>({
            method: 'POST',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/${encodeURIComponent(String(params.id))}/destinations/`,
            body,
        })
        const filtered = pickResponseFields(result, ['hog_function_ids']) as typeof result
        return filtered
    },
})

const AlertDestinationsDeleteSchema = () => {
    const AlertsDestinationsDeleteCreateBody = orvalSchemas.AlertsDestinationsDeleteCreateBody()
    const AlertsDestinationsDeleteCreateParams = orvalSchemas.AlertsDestinationsDeleteCreateParams()
    return AlertsDestinationsDeleteCreateParams.omit({ project_id: true }).extend(
        AlertsDestinationsDeleteCreateBody.shape
    )
}

const alertDestinationsDelete = (): ToolBase<ReturnType<typeof AlertDestinationsDeleteSchema>, unknown> => ({
    name: 'alert-destinations-delete',
    schema: AlertDestinationsDeleteSchema(),
    handler: async (context: Context, params: z.infer<ReturnType<typeof AlertDestinationsDeleteSchema>>) => {
        const projectId = await context.stateManager.getProjectId()
        const body: Record<string, unknown> = {}
        if (params.hog_function_ids !== undefined) {
            body['hog_function_ids'] = params.hog_function_ids
        }
        const result = await context.api.request<unknown>({
            method: 'POST',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/${encodeURIComponent(String(params.id))}/destinations/delete/`,
            body,
        })
        return result
    },
})

const AlertGetSchema = () => {
    const AlertsRetrieveParams = orvalSchemas.AlertsRetrieveParams()
    const AlertsRetrieveQueryParams = orvalSchemas.AlertsRetrieveQueryParams()
    return AlertsRetrieveParams.omit({ project_id: true }).extend(AlertsRetrieveQueryParams.shape)
}

const alertGet = (): ToolBase<ReturnType<typeof AlertGetSchema>, WithPostHogUrl<Schemas.Alert>> => ({
    name: 'alert-get',
    schema: AlertGetSchema(),
    handler: async (context: Context, params: z.infer<ReturnType<typeof AlertGetSchema>>) => {
        const projectId = await context.stateManager.getProjectId()
        const result = await context.api.request<Schemas.Alert>({
            method: 'GET',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/${encodeURIComponent(String(params.id))}/`,
            query: {
                checks_date_from: params.checks_date_from,
                checks_date_to: params.checks_date_to,
                checks_limit: params.checks_limit,
                checks_offset: params.checks_offset,
            },
        })
        return await withPostHogUrl(context, result, `/alerts?alert_type=insights&alert_id=${result.id}`)
    },
})

const AlertSimulateSchema = () => {
    const AlertsSimulateCreateBody = orvalSchemas.AlertsSimulateCreateBody()
    return AlertsSimulateCreateBody
}

const alertSimulate = (): ToolBase<ReturnType<typeof AlertSimulateSchema>, Schemas.AlertSimulateResponse> => ({
    name: 'alert-simulate',
    schema: AlertSimulateSchema(),
    handler: async (context: Context, params: z.infer<ReturnType<typeof AlertSimulateSchema>>) => {
        const projectId = await context.stateManager.getProjectId()
        const body: Record<string, unknown> = {}
        if (params.evaluation_delay_intervals !== undefined) {
            body['evaluation_delay_intervals'] = params.evaluation_delay_intervals
        }
        if (params.insight !== undefined) {
            body['insight'] = params.insight
        }
        if (params.detector_config !== undefined) {
            body['detector_config'] = params.detector_config
        }
        if (params.series_index !== undefined) {
            body['series_index'] = params.series_index
        }
        if (params.date_from !== undefined) {
            body['date_from'] = params.date_from
        }
        if (params.config !== undefined) {
            body['config'] = params.config
        }
        if (params.alert !== undefined) {
            body['alert'] = params.alert
        }
        const result = await context.api.request<Schemas.AlertSimulateResponse>({
            method: 'POST',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/simulate/`,
            body,
        })
        return result
    },
})

const AlertUpdateSchema = () => {
    const AlertsPartialUpdateBody = orvalSchemas.AlertsPartialUpdateBody()
    const AlertsPartialUpdateParams = orvalSchemas.AlertsPartialUpdateParams()
    return AlertsPartialUpdateParams.omit({ project_id: true }).extend(AlertsPartialUpdateBody.shape)
}

const alertUpdate = (): ToolBase<ReturnType<typeof AlertUpdateSchema>, WithPostHogUrl<Schemas.Alert>> => ({
    name: 'alert-update',
    schema: AlertUpdateSchema(),
    handler: async (context: Context, params: z.infer<ReturnType<typeof AlertUpdateSchema>>) => {
        const projectId = await context.stateManager.getProjectId()
        const body: Record<string, unknown> = {}
        if (params.insight !== undefined) {
            body['insight'] = params.insight
        }
        if (params.name !== undefined) {
            body['name'] = params.name
        }
        if (params.subscribed_users !== undefined) {
            body['subscribed_users'] = params.subscribed_users
        }
        if (params.threshold !== undefined) {
            body['threshold'] = params.threshold
        }
        if (params.condition !== undefined) {
            body['condition'] = params.condition
        }
        if (params.enabled !== undefined) {
            body['enabled'] = params.enabled
        }
        if (params.schedule_start_time !== undefined) {
            body['schedule_start_time'] = params.schedule_start_time
        }
        if (params.config !== undefined) {
            body['config'] = params.config
        }
        if (params.detector_config !== undefined) {
            body['detector_config'] = params.detector_config
        }
        if (params.evaluation_delay_intervals !== undefined) {
            body['evaluation_delay_intervals'] = params.evaluation_delay_intervals
        }
        if (params.calculation_interval !== undefined) {
            body['calculation_interval'] = params.calculation_interval
        }
        if (params.snoozed_until !== undefined) {
            body['snoozed_until'] = params.snoozed_until
        }
        if (params.skip_weekend !== undefined) {
            body['skip_weekend'] = params.skip_weekend
        }
        if (params.schedule_restriction !== undefined) {
            body['schedule_restriction'] = params.schedule_restriction
        }
        if (params.investigation_agent_enabled !== undefined) {
            body['investigation_agent_enabled'] = params.investigation_agent_enabled
        }
        if (params.investigation_gates_notifications !== undefined) {
            body['investigation_gates_notifications'] = params.investigation_gates_notifications
        }
        if (params.investigation_inconclusive_action !== undefined) {
            body['investigation_inconclusive_action'] = params.investigation_inconclusive_action
        }
        const result = await context.api.request<Schemas.Alert>({
            method: 'PATCH',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/${encodeURIComponent(String(params.id))}/`,
            body,
        })
        return await withPostHogUrl(context, result, `/alerts?alert_type=insights&alert_id=${result.id}`)
    },
})

const AlertsListSchema = () => {
    const AlertsListQueryParams = orvalSchemas.AlertsListQueryParams()
    return AlertsListQueryParams
}

const alertsList = (): ToolBase<ReturnType<typeof AlertsListSchema>, WithPostHogUrl<Schemas.PaginatedAlertList>> => ({
    name: 'alerts-list',
    schema: AlertsListSchema(),
    handler: async (context: Context, params: z.infer<ReturnType<typeof AlertsListSchema>>) => {
        const projectId = await context.stateManager.getProjectId()
        const result = await context.api.request<Schemas.PaginatedAlertList>({
            method: 'GET',
            path: `/api/projects/${encodeURIComponent(String(projectId))}/alerts/`,
            query: {
                created_by: params.created_by,
                has_detector: params.has_detector,
                insight_id: params.insight_id,
                insight_tag: params.insight_tag,
                limit: params.limit,
                offset: params.offset,
                search: params.search,
            },
        })
        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'
        )
    },
})

export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
    'alert-create': alertCreate,
    'alert-delete': alertDelete,
    'alert-destinations-create': alertDestinationsCreate,
    'alert-destinations-delete': alertDestinationsDelete,
    'alert-get': alertGet,
    'alert-simulate': alertSimulate,
    'alert-update': alertUpdate,
    'alerts-list': alertsList,
}