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.

feat(phai): apply headless query tool filters to open filter pages (#69281)

Georgiy Tarasov254967730297
diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
index b318635d9cbe..577215c25648 100644
--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx
@@ -57,7 +57,7 @@ import { actionsModel } from '~/models/actionsModel'
import { cohortsModel } from '~/models/cohortsModel'
import { groupsModel } from '~/models/groupsModel'
import { AndOrFilterSelect } from '~/queries/nodes/InsightViz/PropertyGroupFilters/AndOrFilterSelect'
-import { NodeKind } from '~/queries/schema/schema-general'
+import { NodeKind, RecordingsQuery } from '~/queries/schema/schema-general'
import {
PropertyOperator,
RecordingUniversalFilters,
@@ -65,7 +65,7 @@ import {
UniversalFiltersGroup,
} from '~/types'
-import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
+import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
import { sessionRecordingSavedFiltersLogic } from '../filters/sessionRecordingSavedFiltersLogic'
@@ -80,9 +80,39 @@ import { sessionRecordingEventUsageLogic } from '../sessionRecordingEventUsageLo
import { CurrentFilterIndicator } from './CurrentFilterIndicator'
import { DurationFilter } from './DurationFilter'
import { ProductAnalyticsOverLimitBanner } from './ProductAnalyticsOverLimitBanner'
-import { deriveOperand } from './recordingsQueryConversions'
+import {
+ DEFAULT_RECORDING_FILTERS_ORDER_BY,
+ DURATION_KEYS,
+ deriveOperand,
+ isValidRecordingOrder,
+ recordingsQueryToUniversalFilters,
+} from './recordingsQueryConversions'
import { SavedFilters } from './SavedFilters'
+// Static instruction rendered into the trusted context block — never interpolate user or ingested data.
+const RECORDINGS_QUERY_TOOL_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ value:
+ 'The user has the session replay list open. When you call query-session-recordings-list, the filters from ' +
+ 'your query (properties, duration, date range, ordering) are also applied to the open recordings list, so ' +
+ 'the user sees matching recordings both in this chat and on screen.',
+}
+
+// Recording-metric keys of the query's `properties` filters, whose `type: 'recording'` is a zod
+// default the agent may omit from its raw args.
+const RECORDING_METRIC_KEYS = new Set([
+ ...DURATION_KEYS,
+ 'console_error_count',
+ 'console_log_count',
+ 'console_warn_count',
+ 'click_count',
+ 'keypress_count',
+ 'activity_score',
+ 'visited_page',
+ 'snapshot_source',
+])
+
function HideRecordingsMenu(): JSX.Element {
const { hideViewedRecordings, hideRecordingsMenuLabelFor } = useValues(playerSettingsLogic)
const { setHideViewedRecordings } = useActions(playerSettingsLogic)
@@ -145,11 +175,60 @@ export const RecordingsUniversalFiltersEmbedButton = ({
useAttachedContext([
{ type: 'recording_filters', value: JSON.stringify(filters), label: 'Current filters' },
+ RECORDINGS_QUERY_TOOL_CONTEXT_ITEM,
...(currentSessionRecordingId
? [{ type: 'session_recording', key: currentSessionRecordingId, label: 'Current session' } as const]
: []),
] as AttachedContextItem[])
+ const applyFilters = (toolOutput: Record<string, any>): void => {
+ // Improve type
+ setFilters(toolOutput.recordings_filters)
+ setIsFiltersExpanded(true)
+ }
+
+ // The headless query tool's call input mirrored onto the open list. The input is a complete query:
+ // every field is applied, with omitted fields set to the query schema's defaults so the list shows
+ // the same recordings the tool returned. The args are raw agent-sent JSON (never zod-validated), so
+ // fields are coerced and the recording-metric `type` default is stamped back on before converting to
+ // the universal filter shape. person_uuid (query-level constraint), after (pagination cursor), and
+ // limit (the agent's page size, which shouldn't shrink the user's list) have no counterpart in the
+ // universal filters.
+ const applyRecordingsQuery = (input: Record<string, any>): void => {
+ const props = (Array.isArray(input.properties) ? input.properties : []).map((f: Record<string, any>) =>
+ f && !f.type && RECORDING_METRIC_KEYS.has(f.key) ? { ...f, type: 'recording' } : f
+ )
+ // Duration filters have their own control in the universal shape, so the converter expects
+ // them in `having_predicates` rather than `properties`.
+ const universal = recordingsQueryToUniversalFilters({
+ kind: NodeKind.RecordingsQuery,
+ properties: props.filter((f: Record<string, any>) => !DURATION_KEYS.has(f?.key)),
+ having_predicates: props.filter((f: Record<string, any>) => DURATION_KEYS.has(f?.key)),
+ } as RecordingsQuery)
+ setFilters({
+ filter_group: universal.filter_group,
+ duration: universal.duration,
+ date_from: input.date_from ?? '-3d',
+ date_to: input.date_to ?? null,
+ filter_test_accounts: !!input.filter_test_accounts,
+ order: isValidRecordingOrder(input.order) ? input.order : DEFAULT_RECORDING_FILTERS_ORDER_BY,
+ order_direction: input.order_direction === 'ASC' ? 'ASC' : 'DESC',
+ session_ids: Array.isArray(input.session_ids) ? input.session_ids : undefined,
+ })
+ setIsFiltersExpanded(true)
+ }
+
+ useMcpToolApplyBack({
+ tools: ['query-session-recordings-list'],
+ targetKey: 'replay-playlist-filters',
+ onApply: (_event, { innerInput }) => {
+ if (!innerInput) {
+ return
+ }
+ applyRecordingsQuery(innerInput)
+ },
+ })
+
return (
<>
<div className="flex gap-2">
@@ -159,11 +238,7 @@ export const RecordingsUniversalFiltersEmbedButton = ({
current_filters: filters,
current_session_id: currentSessionRecordingId,
}}
- callback={(toolOutput: Record<string, any>) => {
- // Improve type
- setFilters(toolOutput.recordings_filters)
- setIsFiltersExpanded(true)
- }}
+ callback={applyFilters}
initialMaxPrompt="Show me recordings where "
suggestions={[
'Show recordings of people who visited signup in the last 24 hours',
diff --git a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
index 66158b1945fa..6a91ca9512db 100644
--- a/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
+++ b/frontend/src/scenes/session-recordings/filters/recordingsQueryConversions.ts
@@ -28,7 +28,7 @@ import { filtersFromUniversalFilterGroups } from '../utils'
export const DEFAULT_RECORDING_FILTERS_ORDER_BY = 'start_time'
-const DURATION_KEYS = new Set(['duration', 'active_seconds', 'inactive_seconds'])
+export const DURATION_KEYS = new Set(['duration', 'active_seconds', 'inactive_seconds'])
/**
* `RecordingsQuery` carries a single `operand`, but the universal filter is a tree of AND/OR groups
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
index 4f5eb0f18fd0..7c3b1078f42f 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsFilters.tsx
@@ -31,11 +31,12 @@ import MaxTool from 'scenes/max/MaxTool'
import { Scene } from 'scenes/sceneTypes'
import { ReloadAll } from '~/queries/nodes/DataNode/Reload'
-import { PropertyFilterType, PropertyMathType } from '~/types'
+import { AnyPropertyFilter, PropertyFilterType, PropertyMathType, PropertyOperator } from '~/types'
-import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
+import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
+import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
-import { ProductTab, faviconUrl } from './common'
+import { INITIAL_DATE_FROM, INITIAL_DATE_TO, ProductTab, faviconUrl } from './common'
import { webAnalyticsDateMapping } from './constants'
import { PathCleaningToggle } from './PathCleaningToggle'
import { TableSortingIndicator } from './TableSortingIndicator'
@@ -153,6 +154,17 @@ export const WebAnalyticsFilters = ({ tabs }: { tabs: JSX.Element }): JSX.Elemen
)
}
+// Static instruction rendered into the trusted context block — never interpolate user or ingested data.
+const WEB_QUERY_TOOLS_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ value:
+ 'The user has the web analytics page open. When you call query-web-overview or query-web-stats, the filters ' +
+ 'from your query (date range, property filters, comparison, path cleaning, test-account filtering, conversion ' +
+ 'goal) are also applied to the page, so the user sees the results both in this chat and on screen. Only ' +
+ 'filters are updated on the page — breakdown and table options are not.',
+}
+
const WebAnalyticsAIFilters = ({ children }: { children: JSX.Element }): JSX.Element => {
const {
dateFilter: { dateTo, dateFrom },
@@ -160,8 +172,14 @@ const WebAnalyticsAIFilters = ({ children }: { children: JSX.Element }): JSX.Ele
isPathCleaningEnabled,
compareFilter,
} = useValues(webAnalyticsLogic)
- const { setDates, setWebAnalyticsFilters, setIsPathCleaningEnabled, setCompareFilter } =
- useActions(webAnalyticsLogic)
+ const {
+ setDates,
+ setWebAnalyticsFilters,
+ setIsPathCleaningEnabled,
+ setCompareFilter,
+ setShouldFilterTestAccounts,
+ setConversionGoal,
+ } = useActions(webAnalyticsLogic)
useAttachedContext([
{
@@ -175,8 +193,57 @@ const WebAnalyticsAIFilters = ({ children }: { children: JSX.Element }): JSX.Ele
}),
label: 'Current filters',
},
+ WEB_QUERY_TOOLS_CONTEXT_ITEM,
])
+ // Legacy MaxTool (langgraph) output: top-level date_from/date_to and possibly grouped properties.
+ const applyFilters = (toolOutput: Record<string, any>): void => {
+ if (toolOutput.properties !== undefined) {
+ const flattenedProperties = convertPropertyGroupToProperties(toolOutput.properties)
+ setWebAnalyticsFilters(flattenedProperties?.filter(isEventPersonOrSessionPropertyFilter) ?? [])
+ }
+ if (toolOutput.date_from !== undefined && toolOutput.date_to !== undefined) {
+ setDates(toolOutput.date_from, toolOutput.date_to)
+ }
+ if (toolOutput.doPathCleaning !== undefined) {
+ setIsPathCleaningEnabled(toolOutput.doPathCleaning)
+ }
+ if (toolOutput.compareFilter !== undefined) {
+ setCompareFilter(toolOutput.compareFilter)
+ }
+ }
+
+ // The headless query tools' call input mirrored onto the open page. The input is a complete query:
+ // every field is applied, with omitted fields set to the query schema's defaults so the page shows
+ // the same results the tool returned. The args are raw agent-sent JSON (never zod-validated), so
+ // fields are coerced and the property-filter type/operator defaults are stamped back on. Stats-only
+ // presentation fields (breakdownBy, includeBounceRate, limit, ...) are per-tile options with no
+ // page-level setter.
+ const applyWebQueryInput = (input: Record<string, any>): void => {
+ const props = (Array.isArray(input.properties) ? input.properties : []).map((f: Record<string, any>) => ({
+ ...f,
+ type: f.type || PropertyFilterType.Event,
+ ...(f.operator || f.type === PropertyFilterType.Cohort ? {} : { operator: PropertyOperator.Exact }),
+ })) as AnyPropertyFilter[]
+ setWebAnalyticsFilters(props.filter(isWebAnalyticsPropertyFilter))
+ setDates(input.dateRange?.date_from ?? INITIAL_DATE_FROM, input.dateRange?.date_to ?? INITIAL_DATE_TO)
+ setIsPathCleaningEnabled(!!input.doPathCleaning)
+ setCompareFilter(input.compareFilter ?? { compare: false })
+ setShouldFilterTestAccounts(!!input.filterTestAccounts)
+ setConversionGoal(input.conversionGoal ?? null)
+ }
+
+ useMcpToolApplyBack({
+ tools: ['query-web-overview', 'query-web-stats'],
+ targetKey: 'web-analytics-filters',
+ onApply: (_event, { innerInput }) => {
+ if (!innerInput) {
+ return
+ }
+ applyWebQueryInput(innerInput)
+ },
+ })
+
return (
<MaxTool
identifier="filter_web_analytics"
@@ -193,21 +260,7 @@ const WebAnalyticsAIFilters = ({ children }: { children: JSX.Element }): JSX.Ele
text: 'Current filters',
icon: <IconFilter />,
}}
- callback={(toolOutput: Record<string, any>) => {
- if (toolOutput.properties !== undefined) {
- const flattenedProperties = convertPropertyGroupToProperties(toolOutput.properties)
- setWebAnalyticsFilters(flattenedProperties?.filter(isEventPersonOrSessionPropertyFilter) ?? [])
- }
- if (toolOutput.date_from !== undefined && toolOutput.date_to !== undefined) {
- setDates(toolOutput.date_from, toolOutput.date_to)
- }
- if (toolOutput.doPathCleaning !== undefined) {
- setIsPathCleaningEnabled(toolOutput.doPathCleaning)
- }
- if (toolOutput.compareFilter !== undefined) {
- setCompareFilter(toolOutput.compareFilter)
- }
- }}
+ callback={applyFilters}
initialMaxPrompt="Filter web analytics data for "
suggestions={[
'Show mobile traffic from last 30 days for the US',
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index 0a696e274ae6..07374930b24a 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -112,7 +112,11 @@ PosthogMcpScopes = McpScopePreset | list[str]
MCP_SCOPE_PRESETS = ("read_only", "full", "signals_scout", "signals_scout_reports")
-def resolve_scopes(scopes: PosthogMcpScopes = "read_only", *, include_internal_scopes: bool = True) -> list[str]:
+def resolve_scopes(
+ scopes: PosthogMcpScopes = "read_only",
+ *,
+ include_internal_scopes: bool = True,
+) -> list[str]:
internal = list(INTERNAL_SCOPES) if include_internal_scopes else []
if isinstance(scopes, str):
if scopes == "full":
diff --git a/products/cdp/mcp/cdp_functions.yaml b/products/cdp/mcp/cdp_functions.yaml
index d8160afec2c5..f76687ccf3f2 100644
--- a/products/cdp/mcp/cdp_functions.yaml
+++ b/products/cdp/mcp/cdp_functions.yaml
@@ -88,6 +88,11 @@ tools:
ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is
available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do
not reference value, threshold_lower, or insight_url — those are not emitted.
+
+ After a successful create, do not stop at a silent success: in chat, tell the user the function was created
+ and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the
+ created function's id. Never share a URL read from the function's inputs — those are destination endpoints
+ (e.g. incoming webhook URLs) and may grant access to the destination.
exclude_params:
- _create_in_folder
- batch_export_id
@@ -139,6 +144,10 @@ tools:
description: >
Execution priority for transformation functions (lower runs first). Only applies to
type=transformation. If omitted, the function is appended at the end.
+ response:
+ exclude:
+ - inputs.*.value
+ - mappings.*.inputs.*.value
cdp-functions-delete:
operation: hog_functions_destroy
enabled: true
@@ -291,6 +300,10 @@ tools:
param_overrides:
enabled:
description: Set to true to activate or false to deactivate the function.
+ response:
+ exclude:
+ - inputs.*.value
+ - mappings.*.inputs.*.value
cdp-functions-rearrange-partial-update:
operation: hog_functions_rearrange_partial_update
enabled: true
diff --git a/products/error_tracking/frontend/components/IssueFilteringTool.tsx b/products/error_tracking/frontend/components/IssueFilteringTool.tsx
index ec82c06248d9..c7fed72d1ccf 100644
--- a/products/error_tracking/frontend/components/IssueFilteringTool.tsx
+++ b/products/error_tracking/frontend/components/IssueFilteringTool.tsx
@@ -6,15 +6,26 @@ import { taxonomicFilterLogic } from 'lib/components/TaxonomicFilter/taxonomicFi
import MaxTool from 'scenes/max/MaxTool'
import { ErrorTrackingIssueFilteringToolOutput } from '~/queries/schema/schema-general'
-import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'
-import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
+import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
+import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'
import { errorTrackingSceneLogic } from '../scenes/ErrorTrackingScene/errorTrackingSceneLogic'
import { TAXONOMIC_FILTER_LOGIC_KEY, TAXONOMIC_GROUP_TYPES } from './IssueFilters/consts'
import { issueFiltersLogic } from './IssueFilters/issueFiltersLogic'
import { isValidOrderBy, issueQueryOptionsLogic } from './IssueQueryOptions/issueQueryOptionsLogic'
+// Static instruction rendered into the trusted context block — never interpolate user or ingested data.
+const ISSUES_QUERY_TOOL_CONTEXT_ITEM: AttachedContextItem = {
+ type: 'instructions',
+ hidden: true,
+ value:
+ 'The user has the error tracking issue list open. When you call query-error-tracking-issues-list, the filters ' +
+ 'from your query (filter group, status, date range, search, ordering, assignee) are also applied to the open ' +
+ 'page, so the user sees matching issues both in this chat and on screen.',
+}
+
function updateFilterGroup(
removedFilterIndexes: number[] | undefined,
newFilters: any[] | undefined,
@@ -68,7 +79,7 @@ function updateFilterGroup(
export function ErrorTrackingIssueFilteringTool(): JSX.Element {
const { query } = useValues(errorTrackingSceneLogic)
const { setDateRange, setFilterGroup, setFilterTestAccounts } = useActions(issueFiltersLogic)
- const { setOrderBy, setOrderDirection, setStatus } = useActions(issueQueryOptionsLogic)
+ const { setAssignee, setOrderBy, setOrderDirection, setStatus } = useActions(issueQueryOptionsLogic)
const { filterGroup } = useValues(issueFiltersLogic)
const { setSearchQuery } = useActions(
taxonomicFilterLogic({
@@ -77,7 +88,10 @@ export function ErrorTrackingIssueFilteringTool(): JSX.Element {
})
)
- useAttachedContext([{ type: 'error_tracking_query', value: JSON.stringify(query), label: 'Current filters' }])
+ useAttachedContext([
+ { type: 'error_tracking_query', value: JSON.stringify(query), label: 'Current filters' },
+ ISSUES_QUERY_TOOL_CONTEXT_ITEM,
+ ])
const callback = (update: ErrorTrackingIssueFilteringToolOutput): void => {
if (update.orderBy && isValidOrderBy(update.orderBy)) {
@@ -106,6 +120,77 @@ export function ErrorTrackingIssueFilteringTool(): JSX.Element {
}
}
+ // The headless query tool's call input mirrored onto the open page. Unlike the incremental MaxTool
+ // patch above, the input is a complete query: every field is applied, with omitted fields set to the
+ // backend's request-serializer defaults so the page shows the same results the tool returned. The
+ // args are raw agent-sent JSON (never zod-validated), so fields are coerced and type/operator are
+ // defaulted. personId and release have no representation in the issue-filters UI;
+ // limit/offset/volumeResolution are scene-managed presentation options.
+ const applyIssuesListQuery = (input: Record<string, any>): void => {
+ setOrderBy(input.orderBy || 'occurrences')
+ setOrderDirection(input.orderDirection === 'ASC' ? 'ASC' : 'DESC')
+ setStatus(input.status || 'active')
+ setAssignee(input.assignee ?? null)
+ setDateRange(input.dateRange ?? { date_from: '-7d', date_to: null })
+ setFilterTestAccounts(input.filterTestAccounts === undefined ? true : !!input.filterTestAccounts)
+
+ // user/filePath fold into the free-text search, mirroring the backend's build_search_query.
+ // An empty result clears the page's search — the query ran without a search constraint.
+ const search = [input.searchQuery, input.user, input.filePath]
+ .filter((s): s is string => typeof s === 'string' && s.length > 0)
+ .join(' ')
+ setSearchQuery(search)
+
+ const flat: UniversalFiltersGroup['values'] = (Array.isArray(input.filterGroup) ? input.filterGroup : []).map(
+ (f: Record<string, any>) => ({
+ ...f,
+ type: f.type || PropertyFilterType.Event,
+ operator: f.operator || PropertyOperator.Exact,
+ })
+ )
+ // library/fingerprint accept a string or a string list — mirror the backend's as_list.
+ if (input.library) {
+ flat.push({
+ type: PropertyFilterType.Event,
+ key: '$lib',
+ operator: PropertyOperator.Exact,
+ value: Array.isArray(input.library) ? input.library : [input.library],
+ })
+ }
+ if (input.fingerprint) {
+ flat.push({
+ type: PropertyFilterType.Event,
+ key: '$exception_fingerprint',
+ operator: PropertyOperator.Exact,
+ value: Array.isArray(input.fingerprint) ? input.fingerprint : [input.fingerprint],
+ })
+ }
+ if (input.url) {
+ flat.push({
+ type: PropertyFilterType.Event,
+ key: '$current_url',
+ operator: PropertyOperator.IContains,
+ value: input.url,
+ })
+ }
+ // An empty group resets the page's filters (the logic falls back to its default group).
+ setFilterGroup({
+ type: FilterLogicalOperator.And,
+ values: [{ type: FilterLogicalOperator.And, values: flat }],
+ })
+ }
+
+ useMcpToolApplyBack({
+ tools: ['query-error-tracking-issues-list'],
+ targetKey: 'error-tracking-issues',
+ onApply: (_event, { innerInput }) => {
+ if (!innerInput) {
+ return
+ }
+ applyIssuesListQuery(innerInput)
+ },
+ })
+
return (
<MaxTool
identifier="filter_error_tracking_issues"
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 1fa31db6fb24..874d1c0cab9d 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -1535,7 +1535,7 @@
}
},
"cdp-functions-create": {
- "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.",
+ "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Create function",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 68fcce7b3007..9dbda2682a12 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -1564,7 +1564,7 @@
}
},
"cdp-functions-create": {
- "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.",
+ "description": "Create a new function. Requires 'type' (destination, site_destination, internal_destination, source_webhook, warehouse_source_webhook, site_app, or transformation) and either 'hog' source code or a 'template_id' to derive code from a template. Provide 'inputs_schema' to define configurable parameters and 'inputs' with their values. Use 'filters' to control which events trigger the function. Transformations run during ingestion and have an 'execution_order' field.\nRecipe — deliver an insight alert to Slack, a webhook, or Discord (canonical reference; alert-create / alert-update point here):\n1. Pick the integration. For Slack, call integrations-list (filter by kind=slack) to find the integration\n id, then call integrations-channels-retrieve with that id to list channels. For a webhook, the user\n provides the destination URL directly. For Discord, the user provides an incoming webhook URL\n (https://discord.com/api/webhooks/...) directly — no integration needed, like a webhook.\n\n2. Dedupe before creating. Call cdp-functions-list with type=internal_destination and limit=1000; the\n response now includes filters. Look for an existing function whose filters.properties has an entry\n with key=alert_id and value equal to <alert.id>. If one exists, call cdp-functions-partial-update on\n that id; if not, proceed to step 3. (Paginate until you have checked every page or found a match.)\n\n3. Create. Use type=internal_destination, template_id=template-slack (or template-webhook or\n template-discord), and:\n filters = {\n \"events\": [{\"id\": \"$insight_alert_firing\", \"type\": \"events\"}],\n \"properties\": [{\"key\": \"alert_id\", \"value\": \"<alert.id>\", \"operator\": \"exact\", \"type\": \"event\"}]\n }\n # Slack. Channel id is preferred (e.g. C0123ABC); \"#general\" is also accepted.\n # Override text + blocks with the same shape the alert-wizard UI uses, so\n # agent-created and UI-created alerts produce identical Slack messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-slack in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"slack_workspace\": {\"value\": <slack_integration_id_int>},\n \"channel\": {\"value\": \"<channel_id>\"},\n \"text\": {\"value\": \"Alert triggered: {event.properties.insight_name}\"},\n \"blocks\": {\"value\": [\n {\"type\": \"header\", \"text\": {\"type\": \"plain_text\",\n \"text\": \"Alert '{event.properties.alert_name}' firing for insight '{event.properties.insight_name}'\"}},\n {\"type\": \"section\", \"text\": {\"type\": \"plain_text\", \"text\": \"{event.properties.breaches}\"}},\n {\"type\": \"context\", \"elements\": [{\"type\": \"mrkdwn\",\n \"text\": \"Project: <{project.url}|{project.name}>\"}]},\n {\"type\": \"divider\"},\n {\"type\": \"actions\", \"elements\": [\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Insight\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}\"},\n {\"type\": \"button\", \"text\": {\"type\": \"plain_text\", \"text\": \"View Alert\"},\n \"url\": \"{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n ]}\n ]}\n }\n # Webhook — must be an https:// URL.\n inputs = {\"url\": {\"value\": \"<destination_url>\"}}\n # Discord — incoming webhook URL (https://discord.com/api/webhooks/...). No integration.\n # Override content with the same shape the alert-wizard UI uses, so agent-created and\n # UI-created alerts produce identical Discord messages.\n # Source of truth: HOG_FUNCTION_SUB_TEMPLATES['insight-alert-firing'] for\n # template-discord in frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.\n inputs = {\n \"webhookUrl\": {\"value\": \"<discord_webhook_url>\"},\n \"content\": {\"value\": \"**Alert '{event.properties.alert_name}' firing** for insight '{event.properties.insight_name}'\\n{event.properties.breaches}\\n{project.url}/insights/{event.properties.insight_id}/alerts?alert_id={event.properties.alert_id}\"}\n }\n\n4. $insight_alert_firing event properties available for templating: alert_id, alert_name, insight_name,\n insight_id (short_id), state (always \"Firing\" — the event is only emitted on a firing transition,\n not on recovery), last_checked_at (ISO 8601 string or null), breaches (human-readable summary, e.g.\n \"Series A is below 1000\"), and detector metadata: alert_mode (always present), detector_type and\n ensemble_operator (null for threshold alerts, set for anomaly detection). Project context is\n available as {project.url} (already includes /project/<team_id>), {project.id}, {project.name}. Do\n not reference value, threshold_lower, or insight_url — those are not emitted.\n\nAfter a successful create, do not stop at a silent success: in chat, tell the user the function was created and offer a link to it. Build the link with the generate-app-url tool, path template /functions/{id} and the created function's id. Never share a URL read from the function's inputs — those are destination endpoints (e.g. incoming webhook URLs) and may grant access to the destination.",
"category": "Functions",
"feature": "hog_functions",
"summary": "Create function",
diff --git a/services/mcp/src/tools/generated/cdp_functions.ts b/services/mcp/src/tools/generated/cdp_functions.ts
index 9341de807e4b..56788dd29a21 100644
--- a/services/mcp/src/tools/generated/cdp_functions.ts
+++ b/services/mcp/src/tools/generated/cdp_functions.ts
@@ -17,7 +17,7 @@ import {
HogFunctionsRearrangePartialUpdateBody,
HogFunctionsRetrieveParams,
} from '@/generated/cdp_functions/api'
-import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
+import { withPostHogUrl, omitResponseFields, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const CdpFunctionsCreateSchema = HogFunctionsCreateBody.extend({
@@ -86,7 +86,8 @@ const cdpFunctionsCreate = (): ToolBase<typeof CdpFunctionsCreateSchema, Schemas
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/`,
body,
})
- return result
+ const filtered = omitResponseFields(result, ['inputs.*.value', 'mappings.*.inputs.*.value']) as typeof result
+ return filtered
},
})
@@ -303,7 +304,8 @@ const cdpFunctionsPartialUpdate = (): ToolBase<typeof CdpFunctionsPartialUpdateS
path: `/api/projects/${encodeURIComponent(String(projectId))}/hog_functions/${encodeURIComponent(String(params.id))}/`,
body,
})
- return result
+ const filtered = omitResponseFields(result, ['inputs.*.value', 'mappings.*.inputs.*.value']) as typeof result
+ return filtered
},
})