: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
// AUTO-GENERATED from products/surveys/mcp/tools.yaml + OpenAPI — do not edit
import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/surveys/api'
import { withUiApp } from '@/resources/ui-apps'
import { normalizeParamAliases } from '@/tools/cast-helpers'
import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const SurveyCreateSchema = () => {
const SurveysCreateBody = orvalSchemas.SurveysCreateBody()
return SurveysCreateBody.omit({
linked_insight_id: true,
targeting_flag_id: true,
remove_targeting_flag: true,
end_date: true,
archived: true,
iteration_start_dates: true,
current_iteration: true,
current_iteration_start_date: true,
response_sampling_start_date: true,
response_sampling_interval_type: true,
response_sampling_interval: true,
response_sampling_limit: true,
response_sampling_daily_limits: true,
base_language: true,
_create_in_folder: true,
}).extend({
appearance: SurveysCreateBody.shape['appearance'].describe(
'Optional appearance customization. Omit this to keep the default styling. whiteLabel=true requires the organization to have the white-labelling entitlement (Enterprise); leave it unset unless requested and available. surveyPopupDelaySeconds must be non-negative.'
),
type: SurveysCreateBody.shape['type'].describe(
'Survey type. Use popover for most in-app surveys, widget for always-available feedback entrypoints, external_survey for hosted forms with a shareable public URL, and api only for headless custom implementations.'
),
schedule: SurveysCreateBody.shape['schedule'].describe(
'How often a person can see the survey. Omit this to use the default once behavior. Use recurring only when the user explicitly asks for a repeated schedule, and set iteration_count and iteration_frequency_days with it. Use always when the user wants the survey to show every time its display conditions are met, also after the person responds or dismisses it. The survey editor calls this "Every time the display conditions are met". An always popover without display conditions or a wait period shows again and again, so suggest a URL condition or seenSurveyWaitPeriodInDays.'
),
questions: SurveysCreateBody.shape['questions'].describe(
'Complete survey question list. Prefer 1-3 questions unless the user explicitly asks for a longer survey. Use rating questions for NPS/CSAT, open for freeform feedback, and choice questions when the user wants structured answers. Questions can include inline translations on each question.'
),
conditions: SurveysCreateBody.shape['conditions'].describe(
'Display conditions for in-app surveys, such as URL matching, event triggers, device filters, or linked flag variants. To target people, groups, or cohorts by properties, use targeting_flag_filters instead. Do not use URL, selector, event, device, or linkedFlagVariant conditions for external_survey forms.'
),
start_date: SurveysCreateBody.shape['start_date'].describe(
'Setting this launches the survey immediately. Leave unset unless the user explicitly asks to launch now.'
),
linked_flag_id: SurveysCreateBody.shape['linked_flag_id'].describe(
'Feature flag ID linked to this survey. Use only when the user explicitly wants the survey linked to a feature flag. Resolve the flag ID first, preferably with SQL in v2.'
),
targeting_flag_filters: SurveysCreateBody.shape['targeting_flag_filters'].describe(
'Target an in-app survey to a subset of users by person, group, or cohort properties. Pass one or more rules in groups[].properties[], each with key, value, operator, and an optional type. Use this instead of conditions for property targeting. Do not use this for external_survey forms. Cohorts with behavioral filters cannot be used directly. Use a supported static cohort snapshot only with user approval; never remove targeting rules to work around validation.'
),
enable_iframe_embedding: SurveysCreateBody.shape['enable_iframe_embedding'].describe(
'Allows an external_survey form to be embedded in an iframe. Use only when the user explicitly asks for iframe embedding.'
),
translations: SurveysCreateBody.shape['translations'].describe(
"Optional survey-level translations keyed by language code. Use for translated survey name, description, thank-you message, and intro screen fields. Question text translations belong inside each question's translations object."
),
form_content: SurveysCreateBody.shape['form_content'].describe(
'Optional hosted-form content configuration for external_survey forms. Only include this when the user explicitly asks to customize the hosted form content beyond the standard question flow.'
),
})
}
const surveyCreate = (): ToolBase<
ReturnType<typeof SurveyCreateSchema>,
WithPostHogUrl<Schemas.SurveySerializerCreateUpdateOnly>
> =>
withUiApp('survey', {
name: 'survey-create',
schema: SurveyCreateSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveyCreateSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const body: Record<string, unknown> = {}
if (params.name !== undefined) {
body['name'] = params.name
}
if (params.description !== undefined) {
body['description'] = params.description
}
if (params.type !== undefined) {
body['type'] = params.type
}
if (params.schedule !== undefined) {
body['schedule'] = params.schedule
}
if (params.linked_flag_id !== undefined) {
body['linked_flag_id'] = params.linked_flag_id
}
if (params.targeting_flag_filters !== undefined) {
body['targeting_flag_filters'] = params.targeting_flag_filters
}
if (params.questions !== undefined) {
body['questions'] = params.questions
}
if (params.conditions !== undefined) {
body['conditions'] = params.conditions
}
if (params.appearance !== undefined) {
body['appearance'] = params.appearance
}
if (params.start_date !== undefined) {
body['start_date'] = params.start_date
}
if (params.responses_limit !== undefined) {
body['responses_limit'] = params.responses_limit
}
if (params.iteration_count !== undefined) {
body['iteration_count'] = params.iteration_count
}
if (params.iteration_frequency_days !== undefined) {
body['iteration_frequency_days'] = params.iteration_frequency_days
}
if (params.enable_partial_responses !== undefined) {
body['enable_partial_responses'] = params.enable_partial_responses
}
if (params.enable_iframe_embedding !== undefined) {
body['enable_iframe_embedding'] = params.enable_iframe_embedding
}
if (params.translations !== undefined) {
body['translations'] = params.translations
}
if (params.form_content !== undefined) {
body['form_content'] = params.form_content
}
const result = await context.api.request<Schemas.SurveySerializerCreateUpdateOnly>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/`,
body,
})
return await withPostHogUrl(context, result, `/surveys/${result.id}`)
},
})
const SurveyDeleteSchema = () => {
const SurveysDestroyParams = orvalSchemas.SurveysDestroyParams()
return z.preprocess(
normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),
SurveysDestroyParams.omit({ project_id: true })
)
}
const surveyDelete = (): ToolBase<ReturnType<typeof SurveyDeleteSchema>, Schemas.SurveySerializerCreateUpdateOnly> => ({
name: 'survey-delete',
schema: SurveyDeleteSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveyDeleteSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.SurveySerializerCreateUpdateOnly>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/`,
body: { archived: true },
})
return result
},
})
const SurveyGetSchema = () => {
const SurveysRetrieveParams = orvalSchemas.SurveysRetrieveParams()
return z.preprocess(
normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),
SurveysRetrieveParams.omit({ project_id: true })
)
}
const surveyGet = (): ToolBase<ReturnType<typeof SurveyGetSchema>, WithPostHogUrl<Schemas.Survey>> =>
withUiApp('survey', {
name: 'survey-get',
schema: SurveyGetSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveyGetSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.Survey>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/`,
})
return await withPostHogUrl(context, result, `/surveys/${result.id}`)
},
})
const SurveyLaunchSchema = () => {
const SurveysLaunchParams = orvalSchemas.SurveysLaunchParams()
return z.preprocess(
normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),
SurveysLaunchParams.omit({ project_id: true })
)
}
const surveyLaunch = (): ToolBase<ReturnType<typeof SurveyLaunchSchema>, WithPostHogUrl<Schemas.Survey>> =>
withUiApp('survey', {
name: 'survey-launch',
schema: SurveyLaunchSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveyLaunchSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.Survey>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/launch/`,
})
return await withPostHogUrl(context, result, `/surveys/${result.id}`)
},
})
const SurveyStatsSchema = () => {
const SurveysStatsRetrieveParams = orvalSchemas.SurveysStatsRetrieveParams()
const SurveysStatsRetrieveQueryParams = orvalSchemas.SurveysStatsRetrieveQueryParams()
return z.preprocess(
normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),
SurveysStatsRetrieveParams.omit({ project_id: true }).extend(SurveysStatsRetrieveQueryParams.shape)
)
}
const surveyStats = (): ToolBase<ReturnType<typeof SurveyStatsSchema>, WithPostHogUrl<Schemas.SurveyStatsResponse>> =>
withUiApp('survey-stats', {
name: 'survey-stats',
schema: SurveyStatsSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveyStatsSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.SurveyStatsResponse>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/stats/`,
query: {
date_from: params.date_from,
date_to: params.date_to,
include_per_question_stats: params.include_per_question_stats,
},
})
return await withPostHogUrl(context, result, `/surveys/${result.survey_id}`)
},
})
const SurveyStopSchema = () => {
const SurveysStopParams = orvalSchemas.SurveysStopParams()
return z.preprocess(
normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),
SurveysStopParams.omit({ project_id: true })
)
}
const surveyStop = (): ToolBase<ReturnType<typeof SurveyStopSchema>, WithPostHogUrl<Schemas.Survey>> =>
withUiApp('survey', {
name: 'survey-stop',
schema: SurveyStopSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveyStopSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.Survey>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/stop/`,
})
return await withPostHogUrl(context, result, `/surveys/${result.id}`)
},
})
const SurveyUpdateSchema = () => {
const SurveysPartialUpdateBody = orvalSchemas.SurveysPartialUpdateBody()
const SurveysPartialUpdateParams = orvalSchemas.SurveysPartialUpdateParams()
return z.preprocess(
normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),
SurveysPartialUpdateParams.omit({ project_id: true })
.extend(
SurveysPartialUpdateBody.omit({
linked_insight_id: true,
iteration_start_dates: true,
current_iteration: true,
current_iteration_start_date: true,
response_sampling_start_date: true,
response_sampling_interval_type: true,
response_sampling_interval: true,
response_sampling_limit: true,
response_sampling_daily_limits: true,
base_language: true,
_create_in_folder: true,
}).shape
)
.extend({
appearance: SurveysPartialUpdateBody.shape['appearance'].describe(
'Optional appearance customization. Omit this to preserve current styling. When changing it, fetch the survey first and preserve existing appearance fields. whiteLabel=true requires the organization to have the white-labelling entitlement (Enterprise); leave it unset unless requested and available. surveyPopupDelaySeconds must be non-negative.'
),
schedule: SurveysPartialUpdateBody.shape['schedule'].describe(
'How often a person can see the survey: once, recurring, or always. Omit this to keep the current schedule. When setting recurring, also set iteration_count and iteration_frequency_days. Use always when the user wants the survey to show every time its display conditions are met, also after the person responds or dismisses it. The survey editor calls this "Every time the display conditions are met". When you change away from recurring, the iteration fields are cleared. An always popover without display conditions or a wait period shows again and again, so suggest a URL condition or seenSurveyWaitPeriodInDays.'
),
questions: SurveysPartialUpdateBody.shape['questions'].describe(
"Complete replacement question list. Existing question IDs are tied to response data and must be preserved. Before sending this field, fetch the survey first, modify the existing question objects in place, keep every unchanged or edited question's id, and include the complete intended ordered question list. New questions should omit id. Do not regenerate existing questions from scratch."
),
conditions: SurveysPartialUpdateBody.shape['conditions'].describe(
'Complete replacement display conditions object. Do not provide this field unless changing display targeting. Use targeting_flag_filters for person, group, or cohort property targeting. Preserve existing URL, selector, event, device, wait-period, and linked flag variant conditions unless explicitly changing them.'
),
targeting_flag_filters: SurveysPartialUpdateBody.shape['targeting_flag_filters'].describe(
"Update an in-app survey's person, group, or cohort property targeting. Pass rules in groups[].properties[], each with key, value, operator, and an optional type. Use this instead of conditions for property targeting. Complete replacement: fetch the survey first, start from targeting_flag.filters, and send the full groups list — omitted groups are removed. Do not use this for external_survey forms. Cohorts with behavioral filters cannot be used directly. Use a supported static cohort snapshot only with user approval; never remove targeting rules to work around validation."
),
translations: SurveysPartialUpdateBody.shape['translations'].describe(
'Complete replacement survey-level translations object. Do not provide this field unless changing translations. Preserve existing language keys and translated fields that should remain. Use null only when the user explicitly asks to remove survey-level translations.'
),
form_content: SurveysPartialUpdateBody.shape['form_content'].describe(
'Hosted-form content configuration for external_survey forms. Do not provide this field unless editing hosted-form content. Preserve existing content fields that should remain.'
),
})
)
}
const surveyUpdate = (): ToolBase<
ReturnType<typeof SurveyUpdateSchema>,
WithPostHogUrl<Schemas.SurveySerializerCreateUpdateOnly>
> =>
withUiApp('survey', {
name: 'survey-update',
schema: SurveyUpdateSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveyUpdateSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const body: Record<string, unknown> = {}
if (params.name !== undefined) {
body['name'] = params.name
}
if (params.description !== undefined) {
body['description'] = params.description
}
if (params.type !== undefined) {
body['type'] = params.type
}
if (params.schedule !== undefined) {
body['schedule'] = params.schedule
}
if (params.linked_flag_id !== undefined) {
body['linked_flag_id'] = params.linked_flag_id
}
if (params.targeting_flag_id !== undefined) {
body['targeting_flag_id'] = params.targeting_flag_id
}
if (params.targeting_flag_filters !== undefined) {
body['targeting_flag_filters'] = params.targeting_flag_filters
}
if (params.remove_targeting_flag !== undefined) {
body['remove_targeting_flag'] = params.remove_targeting_flag
}
if (params.questions !== undefined) {
body['questions'] = params.questions
}
if (params.conditions !== undefined) {
body['conditions'] = params.conditions
}
if (params.appearance !== undefined) {
body['appearance'] = params.appearance
}
if (params.start_date !== undefined) {
body['start_date'] = params.start_date
}
if (params.end_date !== undefined) {
body['end_date'] = params.end_date
}
if (params.archived !== undefined) {
body['archived'] = params.archived
}
if (params.responses_limit !== undefined) {
body['responses_limit'] = params.responses_limit
}
if (params.iteration_count !== undefined) {
body['iteration_count'] = params.iteration_count
}
if (params.iteration_frequency_days !== undefined) {
body['iteration_frequency_days'] = params.iteration_frequency_days
}
if (params.enable_partial_responses !== undefined) {
body['enable_partial_responses'] = params.enable_partial_responses
}
if (params.enable_iframe_embedding !== undefined) {
body['enable_iframe_embedding'] = params.enable_iframe_embedding
}
if (params.translations !== undefined) {
body['translations'] = params.translations
}
if (params.form_content !== undefined) {
body['form_content'] = params.form_content
}
const result = await context.api.request<Schemas.SurveySerializerCreateUpdateOnly>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/`,
body,
})
return await withPostHogUrl(context, result, `/surveys/${result.id}`)
},
})
const SurveysGetAllSchema = () => {
const SurveysListQueryParams = orvalSchemas.SurveysListQueryParams()
return SurveysListQueryParams
}
const surveysGetAll = (): ToolBase<
ReturnType<typeof SurveysGetAllSchema>,
WithPostHogUrl<Schemas.PaginatedSurveyList>
> =>
withUiApp('survey-list', {
name: 'surveys-get-all',
schema: SurveysGetAllSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveysGetAllSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.PaginatedSurveyList>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/`,
query: {
archived: params.archived,
created_by: params.created_by,
ids: Array.isArray(params.ids) ? params.ids.join(',') || undefined : params.ids,
limit: params.limit,
linked_flag_id: params.linked_flag_id,
offset: params.offset,
search: params.search,
status: params.status,
type: params.type,
},
})
return await withPostHogUrl(
context,
{
...result,
results: await Promise.all(
(result.results ?? []).map((item) => withPostHogUrl(context, item, `/surveys/${item.id}`))
),
},
'/surveys'
)
},
})
const SurveysGlobalStatsSchema = () => {
const SurveysGlobalStatsRetrieveQueryParams = orvalSchemas.SurveysGlobalStatsRetrieveQueryParams()
return SurveysGlobalStatsRetrieveQueryParams
}
const surveysGlobalStats = (): ToolBase<
ReturnType<typeof SurveysGlobalStatsSchema>,
Schemas.SurveyGlobalStatsResponse
> =>
withUiApp('survey-global-stats', {
name: 'surveys-global-stats',
schema: SurveysGlobalStatsSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveysGlobalStatsSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.SurveyGlobalStatsResponse>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/stats/`,
query: {
date_from: params.date_from,
date_to: params.date_to,
},
})
return result
},
})
const SurveysResponsesListSchema = () => {
const SurveysResponsesListParams = orvalSchemas.SurveysResponsesListParams()
const SurveysResponsesListQueryParams = orvalSchemas.SurveysResponsesListQueryParams()
return z.preprocess(
normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),
SurveysResponsesListParams.omit({ project_id: true }).extend(SurveysResponsesListQueryParams.shape)
)
}
const surveysResponsesList = (): ToolBase<ReturnType<typeof SurveysResponsesListSchema>, Schemas.SurveyResponsesList> =>
withUiApp('survey-stats', {
name: 'surveys-responses-list',
schema: SurveysResponsesListSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveysResponsesListSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const result = await context.api.request<Schemas.SurveyResponsesList>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/responses/`,
query: {
exclude_archived: params.exclude_archived,
limit: params.limit,
offset: params.offset,
question_id: params.question_id,
score_gte: params.score_gte,
score_lte: params.score_lte,
since: params.since,
until: params.until,
},
})
return result
},
})
const SurveysSummarizeResponsesCreateSchema = () => {
const SurveysSummarizeResponsesCreateBody = orvalSchemas.SurveysSummarizeResponsesCreateBody()
const SurveysSummarizeResponsesCreateParams = orvalSchemas.SurveysSummarizeResponsesCreateParams()
const SurveysSummarizeResponsesCreateQueryParams = orvalSchemas.SurveysSummarizeResponsesCreateQueryParams()
return z.preprocess(
normalizeParamAliases({ id: ['survey_id', 'surveyId'] }),
SurveysSummarizeResponsesCreateParams.omit({ project_id: true })
.extend(SurveysSummarizeResponsesCreateQueryParams.shape)
.extend(SurveysSummarizeResponsesCreateBody.shape)
)
}
const surveysSummarizeResponsesCreate = (): ToolBase<
ReturnType<typeof SurveysSummarizeResponsesCreateSchema>,
unknown
> => ({
name: 'surveys-summarize-responses-create',
schema: SurveysSummarizeResponsesCreateSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof SurveysSummarizeResponsesCreateSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const body: Record<string, unknown> = {}
if (params.force_refresh !== undefined) {
body['force_refresh'] = params.force_refresh
}
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/surveys/${encodeURIComponent(String(params.id))}/summarize_responses/`,
body,
query: {
question_id: params.question_id,
question_index: params.question_index,
},
})
return result
},
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'survey-create': surveyCreate,
'survey-delete': surveyDelete,
'survey-get': surveyGet,
'survey-launch': surveyLaunch,
'survey-stats': surveyStats,
'survey-stop': surveyStop,
'survey-update': surveyUpdate,
'surveys-get-all': surveysGetAll,
'surveys-global-stats': surveysGlobalStats,
'surveys-responses-list': surveysResponsesList,
'surveys-summarize-responses-create': surveysSummarizeResponsesCreate,
}