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(signals): let scouts DM Slack members instead of posting to a channel (#80378)

Andrew Maguirec6587f93449b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f3798491c556..2238712b4068 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7037,17 +7037,17 @@ snapshots:
scenes-app-inbox-scene--triage--light:
hash: v1.k794b7964.1fcdda8455a45b636d29f42c681696c649b26a1339ba5b5890d166ec5bd98aaf.CejUDitmTV84DoeFjFwwFhrEP62iSRHVYAgYCu77zAM
scenes-app-inbox-scoutconfigform--disabled--dark:
- hash: v1.k794b7964.9b49aceb501b24b937fb242b5290a20812ba9d1a68f5819b4049220ce40b0074.67rDdrvt6-iadaCjuYvtCjoGbRHVFn6Td5fRII6fgjc
+ hash: v1.k794b7964.9e9e262f07b97a0b655fa6ca799ff35c3b37b42f211b11c6a8c3fbcc5adcd577.UoegfVUyhTCj8GE9rRIrVcmmNL8UxCXUrBi3A2A9Fgg
scenes-app-inbox-scoutconfigform--disabled--light:
- hash: v1.k794b7964.3551bd94142e1584eb64c788cdd1c37b1b664154852509cdbf003a82e483683c.0Na_Er5Fq7y-H-LZh2k4K6-jvu_j1U69Oimf8CjyepI
+ hash: v1.k794b7964.c72fe1c0eaed734d8a717e845e2cac8844b3d25028550f14fc85b045cf507b63.94Ly7oLXdu33YSM8HurGkh0rtEOWA3Vsof5a2YyOi0s
scenes-app-inbox-scoutconfigform--dry-run--dark:
- hash: v1.k794b7964.4508a21310bf182d8a86c99bcfe865b3176d67cbf678706044e36232c8588ebf.ITu2E780yQl1gLnVmIKa8czMB0LxwOhrLRJ1WU9niz4
+ hash: v1.k794b7964.e35e69dddd1ab502c263a195956afeca5dc804e29a776f561e179a08c007d202.kKe0rEPK3zMBTA8FYxju8TFiNYPTr-m1_avWpC3j_yA
scenes-app-inbox-scoutconfigform--dry-run--light:
- hash: v1.k794b7964.6f93b5f23db7bac689f3cbc4452d77a282723053b04da8932da70c12bad6fe5c.FCI_TejZOxrkMSIyRgm5F4i_INztRai9mVSPUkPF16U
+ hash: v1.k794b7964.9b5445debb3c3e8f0ff9b8da44cc1869765b12ad50280661cebb24e1c9b96cdc.dbiut5M8mR2-wwXQVXZtWH824OawCBrfJAdUpY5yl80
scenes-app-inbox-scoutconfigform--live--dark:
- hash: v1.k794b7964.61e1588992d3b7bdf882a50140a9765c4597ab77f068d1074198d9df153bbe6c.TxMowkDYiR56NSE3eC1x0T0EIW5cel3iAPsJahfx4Yc
+ hash: v1.k794b7964.47bfb32dffa10ff6bd2c2278dec2b09dc79ee47b1889749297c8399060c0b5ab.ivheHFGlHioXbXYYur2C0mJ0pF-R5sRodnaiDazvaxk
scenes-app-inbox-scoutconfigform--live--light:
- hash: v1.k794b7964.b93b42f9787af58980089a1c7817e3deaa8ae88436dba2f7bb820b09e2a7c318.uU7wU2nS8uaHOXEH9Lq6Cr5YYbC1Ef-KCP6akecrCGY
+ hash: v1.k794b7964.813f8f15eb8ca411579bfb532f78e247c810477c3893b2dd70de574dfe21fa19.soEpeg28h3M5JbJw71Sf5JmCXuWRZq6Ms6NXefJwUTU
scenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--dark:
hash: v1.k794b7964.afe2203f4dd53373a3203fcfa611b5b65555341bdc2fc7fd73c15c2d83914600.O4kSRnOgICuQDkyD2HJCwBXdzE-KwsfzWT98nm43_5A
scenes-app-inbox-scoutmcpserverspicker--create-dialog-variant--light:
diff --git a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
index efcf2f1f40a0..0309da4ba68e 100644
--- a/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
+++ b/frontend/src/lib/integrations/SlackIntegrationHelpers.tsx
@@ -19,6 +19,8 @@ import { IconSlackExternal } from 'lib/lemon-ui/icons'
import { IntegrationType, SlackChannelType } from '~/types'
+import type { SlackUserApi } from 'products/integrations/frontend/generated/api.schemas'
+
import { slackChannelId } from './slackChannel'
import { slackIntegrationLogic } from './slackIntegrationLogic'
@@ -83,6 +85,198 @@ const getSlackChannelOptions = (slackChannels?: SlackChannelType[] | null): Lemo
: null
}
+const getSlackUserOptions = (slackUsers: SlackUserApi[]): LemonInputSelectOption[] => {
+ return slackUsers.map((user) => {
+ // Display names are not unique in a workspace, so surface the unique handle alongside
+ // whenever it differs — otherwise two "@Alex" options are indistinguishable.
+ const showHandle = Boolean(user.name) && user.name.toLowerCase() !== user.display_name.toLowerCase()
+ return {
+ key: `${user.id}|@${user.display_name}`,
+ label: showHandle ? `@${user.display_name} (${user.name})` : `@${user.display_name}`,
+ labelComponent: (
+ <span className="flex items-center gap-1">
+ <span>@{user.display_name}</span>
+ {showHandle ? <span className="text-muted">({user.name})</span> : null}
+ </span>
+ ),
+ }
+ })
+}
+
+function SlackIntegrationInactiveBanner({ message }: { message: string }): JSX.Element {
+ // Reconnecting overwrites the existing integration, which the API reserves for project admins
+ // (`has_team_management_access`). Without this the banner would send a member through OAuth
+ // only to have the write rejected at the end.
+ const reconnectRestrictionReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: OrganizationMembershipLevel.Admin,
+ })
+ return (
+ <LemonBanner type="warning" className="mt-1">
+ <div className="flex justify-between gap-2 items-center">
+ <span>
+ {message}
+ {reconnectRestrictionReason ? ' Ask a project admin to reconnect it.' : ''}
+ </span>
+ {reconnectRestrictionReason ? null : (
+ <Link
+ to={api.integrations.authorizeUrl({
+ kind: 'slack',
+ next: window.location.pathname + '?target_type=slack',
+ })}
+ disableClientSideRouting
+ >
+ Reconnect Slack
+ </Link>
+ )}
+ </div>
+ </LemonBanner>
+ )
+}
+
+export type SlackUserPickerProps = {
+ integration: IntegrationType
+ /** Selected members in the `member_id|@display-name` composite format. */
+ values?: string[]
+ onChange?: (values: string[]) => void
+ disabled?: boolean
+ maxUsers?: number
+}
+
+export function SlackUserPicker({
+ onChange,
+ values,
+ integration,
+ disabled,
+ maxUsers,
+}: SlackUserPickerProps): JSX.Element {
+ const logic = slackIntegrationLogic({ id: integration.id })
+ const {
+ slackUsers,
+ allSlackUsers,
+ allSlackUsersLoading,
+ attemptedSlackUserIds,
+ slackIntegrationInactiveMessage,
+ getUsersRefreshButtonDisabledReason,
+ } = useValues(logic)
+ const { loadAllSlackUsers, loadSlackUserById } = useActions(logic)
+ // Gates the empty-val recovery reload, mirroring SlackChannelPicker: LemonInputSelect clears its
+ // input on blur/select, which must not re-trigger a full search round-trip every focus cycle.
+ const hasActiveSearchRef = useRef(false)
+ // The refresh action must keep the active query: LemonInputSelect filters options by the
+ // visible text, so an unfiltered reload under it would hide a searched-for member.
+ const activeSearchRef = useRef('')
+
+ const usersRefreshButtonDisabledReason = getUsersRefreshButtonDisabledReason()
+ // 1s tick while the cooldown is active so the countdown updates; otherwise idle the rerender.
+ usePeriodicRerender(usersRefreshButtonDisabledReason ? 1000 : 60_000)
+
+ useEffect(() => {
+ // Read live logic values rather than the render closure: sibling pickers can mount within
+ // the same commit, before the first one's dispatch is reflected in a re-render.
+ // Gate on the directory itself, not on `slackUsers`: that pool also holds members resolved
+ // by id, so a picker that resolved a saved recipient while disabled would otherwise count
+ // as loaded and never fetch the list once it becomes editable.
+ if (!disabled && !logic.values.allSlackUsers && !logic.values.allSlackUsersLoading) {
+ loadAllSlackUsers()
+ }
+ }, [logic, loadAllSlackUsers, disabled])
+
+ // Saved recipients absent from the loaded list (bare ids stored over the API, or members beyond
+ // the first page) get a direct lookup so their chips render a name instead of a raw id. A
+ // disabled picker (e.g. a disabled scout) never loads the directory, so its saved ids go
+ // straight to lookup; an enabled one waits for the list, which usually resolves them for free.
+ useEffect(() => {
+ if (allSlackUsersLoading || (!disabled && !allSlackUsers)) {
+ return
+ }
+ for (const value of values ?? []) {
+ const memberId = value.split('|')[0]
+ if (
+ memberId &&
+ !slackUsers.some((user: SlackUserApi) => user.id === memberId) &&
+ !attemptedSlackUserIds[memberId]
+ ) {
+ loadSlackUserById(memberId)
+ }
+ }
+ }, [values, slackUsers, allSlackUsers, allSlackUsersLoading, disabled, attemptedSlackUserIds, loadSlackUserById])
+
+ // Re-key saved values onto the freshly listed member so a stale saved display name still matches
+ // its option, keeping selection and options in sync by member id.
+ const selectedValues = useMemo(
+ () =>
+ (values ?? []).map((value) => {
+ const memberId = value.split('|')[0]
+ const match = slackUsers.find((user: SlackUserApi) => user.id === memberId)
+ return match ? `${match.id}|@${match.display_name}` : value
+ }),
+ [values, slackUsers]
+ )
+
+ const listedOptions = getSlackUserOptions(slackUsers)
+ // Saved members missing from the current list (e.g. filtered out by an active search) still need
+ // an option so their chips keep a readable label.
+ const fallbackOptions = selectedValues
+ .filter((value) => !listedOptions.some((option) => option.key === value))
+ // A bare id keeps rendering as the id itself, which still identifies the recipient while
+ // (or if) the direct lookup resolves a name for it.
+ .map((value) => ({ key: value, label: value.includes('|') ? value.split('|')[1] : value }))
+ const options = [...listedOptions, ...fallbackOptions]
+ const atLimit = maxUsers !== undefined && selectedValues.length >= maxUsers
+
+ return (
+ <>
+ <LemonInputSelect
+ onChange={(vals) => onChange?.(vals)}
+ onInputChange={(val) => {
+ if (val) {
+ loadAllSlackUsers(false, val)
+ hasActiveSearchRef.current = true
+ activeSearchRef.current = val
+ } else if (hasActiveSearchRef.current) {
+ loadAllSlackUsers()
+ hasActiveSearchRef.current = false
+ activeSearchRef.current = ''
+ }
+ }}
+ value={selectedValues}
+ onFocus={() => !allSlackUsers && !allSlackUsersLoading && loadAllSlackUsers()}
+ disabled={disabled}
+ mode="multiple"
+ data-attr="select-slack-users"
+ placeholder={atLimit ? undefined : 'Select people...'}
+ action={{
+ children: <span className="Link">Refresh members</span>,
+ onClick: () => loadAllSlackUsers(true, activeSearchRef.current),
+ // Also held while a load is in flight, so mashing the action can't stack
+ // concurrent full member enumerations against Slack.
+ disabledReason: allSlackUsersLoading ? 'Refreshing members…' : usersRefreshButtonDisabledReason,
+ }}
+ options={atLimit ? options.filter((option) => selectedValues.includes(option.key)) : options}
+ loading={allSlackUsersLoading}
+ emptyStateComponent={
+ <p className="text-secondary italic p-1 max-w-sm">
+ {atLimit
+ ? 'Recipient limit reached. Remove someone to add another person.'
+ : 'No members found.'}
+ </p>
+ }
+ />
+
+ {slackIntegrationInactiveMessage ? (
+ <SlackIntegrationInactiveBanner message={slackIntegrationInactiveMessage} />
+ ) : null}
+
+ {allSlackUsers?.has_more && !allSlackUsersLoading ? (
+ <p className="text-secondary text-xs mt-1 mb-0">
+ Only the first page of members is shown. Type to search for a specific person.
+ </p>
+ ) : null}
+ </>
+ )
+}
+
export type SlackChannelPickerProps = {
integration: IntegrationType
value?: string
@@ -104,13 +298,6 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S
slackIntegrationInactiveMessage,
} = useValues(logic)
const { loadAllSlackChannels, loadSlackChannelById, loadSlackChannelByIdSuccess } = useActions(logic)
- // Reconnecting overwrites the existing integration, which the API reserves for project admins
- // (`has_team_management_access`). Without this the banner would send a member through OAuth
- // only to have the write rejected at the end.
- const reconnectRestrictionReason = useRestrictedArea({
- scope: RestrictionScope.Project,
- minimumAccessLevel: OrganizationMembershipLevel.Admin,
- })
const [localValue, setLocalValue] = useState<string | null>(null)
// Gates the empty-val recovery reload: LemonInputSelect's setInputValue('') on blur and
// after-select would otherwise flicker the "first page of channels" hint on every focus cycle.
@@ -248,25 +435,7 @@ export function SlackChannelPicker({ onChange, value, integration, disabled }: S
/>
{slackIntegrationInactiveMessage ? (
- <LemonBanner type="warning" className="mt-1">
- <div className="flex justify-between gap-2 items-center">
- <span>
- {slackIntegrationInactiveMessage}
- {reconnectRestrictionReason ? ' Ask a project admin to reconnect it.' : ''}
- </span>
- {reconnectRestrictionReason ? null : (
- <Link
- to={api.integrations.authorizeUrl({
- kind: 'slack',
- next: window.location.pathname + '?target_type=slack',
- })}
- disableClientSideRouting
- >
- Reconnect Slack
- </Link>
- )}
- </div>
- </LemonBanner>
+ <SlackIntegrationInactiveBanner message={slackIntegrationInactiveMessage} />
) : null}
{allSlackChannels?.has_more && !allSlackChannelsLoading ? (
diff --git a/frontend/src/lib/integrations/slackIntegrationLogic.test.ts b/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
index e12a93df8590..eaa17d6a656c 100644
--- a/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
+++ b/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
@@ -336,7 +336,7 @@ describe('slackIntegrationLogic — inactive Slack integration', () => {
expect(logic.values.slackIntegrationInactiveMessage).toBe(inactiveDetail)
})
- it('clears the inline message on the next successful load (e.g. after reconnecting)', async () => {
+ it('keeps the message on a plain load and clears it only on a successful forced refresh', async () => {
respondInactive = true
await expectLogic(logic, () => {
logic.actions.loadAllSlackChannels()
@@ -344,9 +344,16 @@ describe('slackIntegrationLogic — inactive Slack integration', () => {
expect(logic.values.slackIntegrationInactiveMessage).toBe(inactiveDetail)
respondInactive = false
+ // A plain load can be served from the backend cache without touching Slack, so its
+ // success proves nothing about the token and must not hide the reconnect banner.
await expectLogic(logic, () => {
logic.actions.loadAllSlackChannels()
}).toFinishAllListeners()
+ expect(logic.values.slackIntegrationInactiveMessage).toBe(inactiveDetail)
+
+ await expectLogic(logic, () => {
+ logic.actions.loadAllSlackChannels(true)
+ }).toFinishAllListeners()
expect(logic.values.slackIntegrationInactiveMessage).toBeNull()
})
})
diff --git a/frontend/src/lib/integrations/slackIntegrationLogic.ts b/frontend/src/lib/integrations/slackIntegrationLogic.ts
index 157cec7573dc..b30a9facc19f 100644
--- a/frontend/src/lib/integrations/slackIntegrationLogic.ts
+++ b/frontend/src/lib/integrations/slackIntegrationLogic.ts
@@ -1,13 +1,16 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import api from 'lib/api'
+import api, { ApiConfig } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { getRecentSlackChannelIds, slackChannelId } from 'lib/integrations/slackChannel'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { SlackChannelType } from '~/types'
+import { integrationsUsersRetrieve } from 'products/integrations/frontend/generated/api'
+import type { SlackUserApi, SlackUsersResponseApi } from 'products/integrations/frontend/generated/api.schemas'
+
import type { PreflightStatus } from '../../types'
export const SLACK_CHANNELS_MIN_REFRESH_INTERVAL_SECONDS = 30
@@ -25,13 +28,18 @@ export interface slackIntegrationLogicValues {
siteUrlMisconfigured: boolean // preflightLogic
_fetchedSlackChannelById: SlackChannelType | null
_fetchedSlackChannels: SlackChannelType[]
+ _fetchedSlackUsersById: Record<string, SlackUserApi>
allSlackChannels: {
channels: SlackChannelType[]
has_more?: boolean
lastRefreshedAt: string
} | null
allSlackChannelsLoading: boolean
+ allSlackUsers: SlackUsersResponseApi | null
+ allSlackUsersLoading: boolean
+ attemptedSlackUserIds: Record<string, true>
getChannelRefreshButtonDisabledReason: () => string
+ getUsersRefreshButtonDisabledReason: () => string
isMemberOfSlackChannel: (channel: string) => boolean | null
isPrivateChannelWithoutAccess: (channel: string) => boolean
recentlySubscribedChannelIds: string[]
@@ -40,6 +48,9 @@ export interface slackIntegrationLogicValues {
slackChannels: SlackChannelType[]
slackChannelsForPicker: SlackChannelType[]
slackIntegrationInactiveMessage: string | null
+ slackUserById: SlackUserApi | null
+ slackUserByIdLoading: boolean
+ slackUsers: SlackUserApi[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -79,6 +90,33 @@ export interface slackIntegrationLogicActions {
search: string
}
}
+ loadAllSlackUsers: (
+ forceRefresh?: boolean,
+ search?: string
+ ) => {
+ forceRefresh: boolean
+ search: string
+ }
+ loadAllSlackUsersFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadAllSlackUsersSuccess: (
+ allSlackUsers: SlackUsersResponseApi | null,
+ payload?: {
+ forceRefresh: boolean
+ search: string
+ }
+ ) => {
+ allSlackUsers: SlackUsersResponseApi | null
+ payload?: {
+ forceRefresh: boolean
+ search: string
+ }
+ }
loadSlackChannelById: (channelId: string) => {
channelId: string
}
@@ -100,6 +138,27 @@ export interface slackIntegrationLogicActions {
channelId: string
}
}
+ loadSlackUserById: (userId: string) => {
+ userId: string
+ }
+ loadSlackUserByIdFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSlackUserByIdSuccess: (
+ slackUserById: SlackUserApi | null,
+ payload?: {
+ userId: string
+ }
+ ) => {
+ slackUserById: SlackUserApi | null
+ payload?: {
+ userId: string
+ }
+ }
setRecentlySubscribedChannelIds: (channelIds: string[]) => {
channelIds: string[]
}
@@ -121,6 +180,11 @@ export interface slackIntegrationLogicMeta {
_fetchedSlackChannels: SlackChannelType[],
_fetchedSlackChannelById: SlackChannelType | null
) => SlackChannelType[]
+ slackUsers: (
+ allSlackUsers: SlackUsersResponseApi | null,
+ _fetchedSlackUsersById: Record<string, SlackUserApi>
+ ) => SlackUserApi[]
+ getUsersRefreshButtonDisabledReason: (allSlackUsers: SlackUsersResponseApi | null) => () => string
slackChannelsForPicker: (
slackChannels: SlackChannelType[],
recentlySubscribedChannelIds: string[]
@@ -153,6 +217,8 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
})),
actions({
loadAllSlackChannels: (forceRefresh: boolean = false, search: string = '') => ({ forceRefresh, search }),
+ loadAllSlackUsers: (forceRefresh: boolean = false, search: string = '') => ({ forceRefresh, search }),
+ loadSlackUserById: (userId: string) => ({ userId }),
loadSlackChannelById: (channelId: string) => ({ channelId }),
setRecentlySubscribedChannelIds: (channelIds: string[]) => ({ channelIds }),
setSlackIntegrationInactive: (message: string | null) => ({ message }),
@@ -167,7 +233,13 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
await breakpoint(300)
}
try {
- return await api.integrations.slackChannels(props.id, forceRefresh, { search })
+ const response = await api.integrations.slackChannels(props.id, forceRefresh, { search })
+ if (forceRefresh) {
+ // Only a forced refresh provably reached Slack (a plain load can be
+ // served from the backend cache), so only it may hide the reconnect banner.
+ actions.setSlackIntegrationInactive(null)
+ }
+ return response
} catch (e: any) {
if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
// Keep whatever we had and surface guidance inline instead of throwing,
@@ -180,6 +252,61 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
},
},
],
+ allSlackUsers: [
+ null as SlackUsersResponseApi | null,
+ {
+ loadAllSlackUsers: async ({ forceRefresh, search }, breakpoint) => {
+ if (search) {
+ await breakpoint(300)
+ }
+ try {
+ const response = await integrationsUsersRetrieve(
+ String(ApiConfig.getCurrentProjectId()),
+ props.id,
+ {
+ ...(search ? { search } : {}),
+ ...(forceRefresh ? { force_refresh: true } : {}),
+ }
+ )
+ // A slower earlier search must not overwrite a newer one's results.
+ breakpoint()
+ if (forceRefresh) {
+ // Matches the channels loader: a cached-served search proves nothing
+ // about the token, so only a forced refresh clears the banner.
+ actions.setSlackIntegrationInactive(null)
+ }
+ return response
+ } catch (e: any) {
+ if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
+ actions.setSlackIntegrationInactive(e.detail ?? SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE)
+ return values.allSlackUsers
+ }
+ throw e
+ }
+ },
+ },
+ ],
+ slackUserById: [
+ null as SlackUserApi | null,
+ {
+ loadSlackUserById: async ({ userId }) => {
+ try {
+ const response = await integrationsUsersRetrieve(
+ String(ApiConfig.getCurrentProjectId()),
+ props.id,
+ { user_id: userId }
+ )
+ return response.users[0] ?? null
+ } catch (e: any) {
+ if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
+ actions.setSlackIntegrationInactive(e.detail ?? SLACK_INTEGRATION_INACTIVE_FALLBACK_MESSAGE)
+ return values.slackUserById
+ }
+ throw e
+ }
+ },
+ },
+ ],
slackChannelById: [
null as SlackChannelType | null,
{
@@ -187,6 +314,9 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
await breakpoint(500)
try {
const res = await api.integrations.slackChannelsById(props.id, channelId)
+ // The by-id endpoint always calls Slack live, so a success is real proof
+ // the connection works again.
+ actions.setSlackIntegrationInactive(null)
return res.channels[0] || null
} catch (e: any) {
if (e?.code === SLACK_INTEGRATION_INACTIVE_ERROR_CODE) {
@@ -215,6 +345,23 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
loadSlackChannelByIdSuccess: (_, { slackChannelById }) => slackChannelById,
},
],
+ attemptedSlackUserIds: [
+ {} as Record<string, true>,
+ {
+ loadSlackUserById: (state, { userId }) => ({ ...state, [userId]: true }),
+ // A failed lookup keeps its marker: the picker's resolver effect fires whenever a
+ // saved id is unmarked, so dropping it on failure would retry in an unbounded loop.
+ // "Refresh members" is the explicit retry, and it clears the whole map.
+ loadAllSlackUsers: (state, { forceRefresh }) => (forceRefresh ? {} : state),
+ },
+ ],
+ _fetchedSlackUsersById: [
+ {} as Record<string, SlackUserApi>,
+ {
+ loadSlackUserByIdSuccess: (state, { slackUserById, payload }) =>
+ slackUserById && payload ? { ...state, [payload.userId]: slackUserById } : state,
+ },
+ ],
recentlySubscribedChannelIds: [
getRecentSlackChannelIds(props.id),
{
@@ -224,9 +371,9 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
slackIntegrationInactiveMessage: [
null as string | null,
{
- // Cleared on each fresh fetch attempt so a later success (e.g. after reconnecting) hides the banner.
- loadAllSlackChannels: () => null,
- loadSlackChannelById: () => null,
+ // Only cleared by requests that provably reached Slack (forced refreshes, live
+ // by-id lookups) — the loaders dispatch the clear themselves. A cache-served search
+ // succeeding must not hide the banner while the token is still revoked.
setSlackIntegrationInactive: (_, { message }) => message,
},
],
@@ -252,6 +399,38 @@ export const slackIntegrationLogic = kea<slackIntegrationLogicType>([
return channels
},
],
+ slackUsers: [
+ (s) => [s.allSlackUsers, s._fetchedSlackUsersById],
+ (
+ allSlackUsers: SlackUsersResponseApi | null,
+ _fetchedSlackUsersById: Record<string, SlackUserApi>
+ ): SlackUserApi[] => {
+ const listed = allSlackUsers?.users ?? []
+ const listedIds = new Set(listed.map((user) => user.id))
+ // Members resolved by direct lookup (saved recipients beyond the listed page, or
+ // bare ids saved over the API) join the pool so their chips render a name.
+ return [...listed, ...Object.values(_fetchedSlackUsersById).filter((user) => !listedIds.has(user.id))]
+ },
+ ],
+ getUsersRefreshButtonDisabledReason: [
+ (s) => [s.allSlackUsers],
+ (allSlackUsers: SlackUsersResponseApi | null) => (): string => {
+ const now = dayjs()
+ if (allSlackUsers?.lastRefreshedAt) {
+ const earliestRefresh = dayjs(allSlackUsers.lastRefreshedAt).add(
+ SLACK_CHANNELS_MIN_REFRESH_INTERVAL_SECONDS,
+ 'seconds'
+ )
+ if (now.isBefore(earliestRefresh)) {
+ const secondsLeft = Math.ceil(earliestRefresh.diff(now) / 1000)
+ return `You can refresh the members again in ${secondsLeft} second${
+ secondsLeft === 1 ? '' : 's'
+ }`
+ }
+ }
+ return ''
+ },
+ ],
slackChannelsForPicker: [
(s) => [s.slackChannels, s.recentlySubscribedChannelIds],
(slackChannels: SlackChannelType[], recentlySubscribedChannelIds: string[]): SlackChannelType[] => {
diff --git a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
index 0a2c0c5ec130..12ec9f59d2b4 100644
--- a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
+++ b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx
@@ -397,6 +397,14 @@ export function LemonInputSelect<T = string>({
}
}, [showPopover])
+ // Close the popover when the control becomes disabled mid-interaction (e.g. a save kicked off
+ // by selecting an option) — an open popover's options would otherwise stay clickable.
+ useEffect(() => {
+ if (disabled) {
+ setShowPopover(false)
+ }
+ }, [disabled])
+
const setInputValue = (newValue: string): void => {
if (newValue) {
setFrozenOptions(null)
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 12e1749fcbfc..f7487759ef97 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -1,6 +1,7 @@
import os
import re
import json
+import time
from collections.abc import Iterable
from typing import Any, NoReturn, Protocol, cast
from urllib.parse import urlencode
@@ -12,13 +13,14 @@ from django.db.models import Q, QuerySet
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils import timezone
+from django.utils.dateparse import parse_datetime
import structlog
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, extend_schema_field, extend_schema_serializer
from prometheus_client import Counter
from rest_framework import mixins, serializers, status, viewsets
-from rest_framework.exceptions import APIException, PermissionDenied, ValidationError
+from rest_framework.exceptions import APIException, PermissionDenied, Throttled, ValidationError
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -139,6 +141,28 @@ class SlackIntegrationInactiveError(APIException):
)
+class SlackIntegrationMissingScopeError(SlackIntegrationInactiveError):
+ # Reuses the inactive error's code so the pickers' existing reconnect banner renders; only the
+ # copy differs, because what the admin has to do — reinstall the app — is the same either way.
+ default_detail = (
+ "Your Slack connection is missing the permission PostHog needs to list workspace members. "
+ "Reconnect Slack to grant it."
+ )
+
+
+def _reraise_slack_users_api_error(error: SlackApiError) -> NoReturn:
+ """Same as `_reraise_slack_api_error`, plus the member endpoints' own scope failure.
+
+ `users.list` and `users.info` need `users:read`, which an install predating that scope never
+ granted. Slack answers `missing_scope`, which is not an auth failure, so without this it would
+ surface as a 500 and dead-end the member picker instead of offering the reconnect that fixes it.
+ """
+ error_code = error.response.get("error") if error.response is not None else None
+ if error_code == "missing_scope":
+ raise SlackIntegrationMissingScopeError() from error
+ _reraise_slack_api_error(error)
+
+
def _reraise_slack_api_error(error: SlackApiError) -> NoReturn:
"""Translate an inactive-auth Slack error into an actionable 4xx; re-raise everything else.
@@ -428,6 +452,82 @@ class SlackChannelsResponseSerializer(serializers.Serializer):
)
+class SlackUserSerializer(serializers.Serializer):
+ id = serializers.CharField(help_text="Slack member ID (e.g. U0123ABC) — post to it to open a direct message.")
+ name = serializers.CharField(help_text="Slack username (handle) without the leading '@'.")
+ display_name = serializers.CharField(
+ help_text="Name to show in pickers: the member's display name, falling back to their real name or handle."
+ )
+
+
+# Server-side floor between forced member-list refreshes, matching the picker's visible cooldown.
+SLACK_USERS_MIN_REFRESH_SECONDS = 30
+
+# Cap on uncached per-id member lookups per integration per minute; each one reaches Slack's
+# users.info endpoint, so distinct fabricated ids must not be able to drain the workspace quota.
+SLACK_USERS_INFO_LOOKUPS_PER_MINUTE = 30
+
+# How long a request that lost the member-list fill waits for the winner's result before
+# enumerating Slack itself. Bounds a cold-cache burst to one enumeration without failing the
+# request outright, at the cost of holding the losing requests for at most this long.
+SLACK_USERS_FILL_WAIT_SECONDS = 3.0
+SLACK_USERS_FILL_POLL_SECONDS = 0.1
+
+
+class SlackUsersQuerySerializer(serializers.Serializer):
+ search = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text="Optional case-insensitive member name or ID search query.",
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ default=50,
+ min_value=1,
+ max_value=200,
+ help_text="Maximum number of members to return per request (max 200).",
+ )
+ offset = serializers.IntegerField(
+ required=False,
+ default=0,
+ min_value=0,
+ help_text="Number of members to skip before returning results.",
+ )
+ # Deliberately not nullable: generated clients serialize an explicit null as the literal
+ # query string "user_id=null", which would then be looked up as a member id. Omit to skip.
+ user_id = serializers.CharField(
+ required=False,
+ default="",
+ allow_blank=True,
+ help_text=(
+ "Look up one member directly by Slack member ID (e.g. U0123ABC). When set, `search`, `limit`, and "
+ "`offset` are ignored and the response holds at most that member."
+ ),
+ )
+ force_refresh = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Bypass the 1 hour member cache. Honored only for browser session callers; API key, OAuth, and MCP "
+ "callers always read through the cache."
+ ),
+ )
+
+
+class SlackUsersResponseSerializer(serializers.Serializer):
+ users = SlackUserSerializer(many=True, help_text="Human Slack workspace members the PostHog Slack app can DM.")
+ lastRefreshedAt = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="ISO 8601 timestamp of the last full Slack API refresh (only set on full lists, not single-member lookups).",
+ )
+ has_more = serializers.BooleanField(
+ required=False,
+ help_text="Whether more members match the current search beyond this page.",
+ )
+
+
class IntegrationAccessRequestSerializer(serializers.Serializer):
kind = serializers.ChoiceField(
choices=Integration.IntegrationKind.choices,
@@ -1134,6 +1234,7 @@ class IntegrationViewSet(
"list",
"retrieve",
"channels",
+ "users",
"github_repos",
"github_branches",
"github_teams",
@@ -1434,6 +1535,144 @@ class IntegrationViewSet(
}
)
+ @staticmethod
+ def _serialize_slack_user(member: dict) -> dict:
+ profile = member.get("profile") or {}
+ return {
+ "id": member["id"],
+ "name": member.get("name", ""),
+ "display_name": profile.get("display_name") or member.get("real_name") or member.get("name", ""),
+ }
+
+ @staticmethod
+ def _filter_slack_users_for_search(users: list[dict], search: str) -> list[dict]:
+ query = search.strip()
+ if not query:
+ return users
+ # Fuzzy-rank by display name and handle, then union in any member whose id contains the query
+ # so pasting an id still resolves.
+ ranked = fuzzy_filter(query, users, key=lambda member: f"{member['display_name']} {member['name']}")
+ ranked_ids = {member["id"] for member in ranked}
+ id_matches = [
+ member for member in users if query.lower() in member["id"].lower() and member["id"] not in ranked_ids
+ ]
+ return ranked + id_matches
+
+ @extend_schema(
+ parameters=[SlackUsersQuerySerializer],
+ responses={200: SlackUsersResponseSerializer},
+ )
+ @action(methods=["GET"], detail=True, url_path="users")
+ def users(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ instance = self.get_object()
+ if instance.kind not in SLACK_INTEGRATION_KINDS:
+ raise ValidationError("users endpoint is only supported for Slack integrations")
+ slack = SlackIntegration(instance)
+ query_serializer = SlackUsersQuerySerializer(data=request.query_params)
+ query_serializer.is_valid(raise_exception=True)
+ # force_refresh is only honored for cookie-session callers — MCP / API-key / OAuth
+ # callers always read through the 1h cache so an agent loop can't bypass it.
+ is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
+ force_refresh: bool = is_session_auth and query_serializer.validated_data["force_refresh"]
+
+ # Key on the Integration row PK (unique per PostHog team × Slack workspace), not
+ # integration_id (the Slack workspace id, shared across teams).
+ key = f"slack/{instance.id}/users"
+
+ user_id = query_serializer.validated_data["user_id"]
+ if user_id:
+ data = cache.get(key)
+ if data is not None:
+ for member in data["users"]:
+ if member["id"] == user_id:
+ return Response({"users": [member]})
+ # Cache hits AND misses per id, so a loop over arbitrary ids can't spend the
+ # workspace's Slack API quota one uncached users.info call at a time.
+ lookup_key = f"slack/{instance.id}/users/{user_id}"
+ cached_lookup = cache.get(lookup_key)
+ if cached_lookup is not None:
+ return Response({"users": cached_lookup})
+ # The per-id cache doesn't bound a caller cycling through distinct fabricated ids, so
+ # also cap how many uncached lookups an integration can send to Slack per minute.
+ budget_key = f"slack/{instance.id}/users_info_budget"
+ try:
+ lookups = 1 if cache.add(budget_key, 1, 60) else cache.incr(budget_key)
+ except ValueError:
+ lookups = 1
+ if lookups > SLACK_USERS_INFO_LOOKUPS_PER_MINUTE:
+ raise Throttled(detail="Too many Slack member lookups. Try again in a minute.")
+ try:
+ member = slack.get_user_by_id(user_id)
+ except SlackApiError as e:
+ _reraise_slack_users_api_error(e)
+ serialized_lookup = [self._serialize_slack_user(member)] if member else []
+ cache.set(lookup_key, serialized_lookup, 60 * 60)
+ return Response({"users": serialized_lookup})
+
+ search = query_serializer.validated_data["search"]
+ limit = query_serializer.validated_data["limit"]
+ offset = query_serializer.validated_data["offset"]
+
+ data = cache.get(key)
+
+ if data is not None and force_refresh:
+ # Server-side floor under the picker's cooldown: a session user mashing refresh must
+ # not spend up to ten Slack API pages per click.
+ last_refreshed = parse_datetime(data.get("lastRefreshedAt") or "")
+ if (
+ last_refreshed is not None
+ and (timezone.now() - last_refreshed).total_seconds() < SLACK_USERS_MIN_REFRESH_SECONDS
+ ):
+ force_refresh = False
+
+ # The refresh floor above compares a value that concurrent requests all read before any of
+ # them writes, so it alone can't stop parallel forced refreshes from each enumerating the
+ # workspace. Whoever claims this sentinel refreshes; the rest serve the list they have.
+ needs_fill = data is None or force_refresh
+ filling_key = f"{key}/filling"
+ claimed_fill = needs_fill and cache.add(filling_key, 1, 60)
+
+ if needs_fill and not claimed_fill and data is None:
+ # Nothing to serve, so a cold-cache burst would otherwise have every request enumerate
+ # the workspace at once. Wait for the winner instead, and only enumerate if it never
+ # lands — a winner that died must not leave the rest waiting on a list that never comes.
+ deadline = time.monotonic() + SLACK_USERS_FILL_WAIT_SECONDS
+ while data is None and time.monotonic() < deadline:
+ time.sleep(SLACK_USERS_FILL_POLL_SECONDS)
+ data = cache.get(key)
+ if data is None:
+ claimed_fill = cache.add(filling_key, 1, 60)
+
+ if needs_fill and (claimed_fill or data is None):
+ try:
+ members = slack.list_users()
+ except SlackApiError as e:
+ _reraise_slack_users_api_error(e)
+ finally:
+ if claimed_fill:
+ cache.delete(filling_key)
+ serialized = sorted(
+ (self._serialize_slack_user(member) for member in members),
+ key=lambda member: member["display_name"].lower(),
+ )
+ data = {
+ "users": serialized,
+ "lastRefreshedAt": timezone.now().isoformat(),
+ }
+ cache.set(key, data, 60 * 60) # one hour
+
+ filtered_users = self._filter_slack_users_for_search(data["users"], search)
+ page = filtered_users[offset : offset + limit]
+ has_more = offset + limit < len(filtered_users)
+
+ return Response(
+ {
+ "users": page,
+ "lastRefreshedAt": data.get("lastRefreshedAt"),
+ "has_more": has_more,
+ }
+ )
+
@action(methods=["GET"], detail=True, url_path="twilio_phone_numbers")
def twilio_phone_numbers(self, request: Request, *args: Any, **kwargs: Any) -> Response:
instance = self.get_object()
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index e6059509071e..9c48defb7d87 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -126,6 +126,72 @@ class TestSlackIntegration:
assert channels[3]["id"] == "CP123"
assert channels[3]["name"] == "d_private_channel"
+ @patch("posthog.models.integration.slack.WebClient")
+ def test_list_users_excludes_ineligible_members(self, mock_webclient_class):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+
+ mock_client.users_list.return_value = {
+ "members": [
+ {"id": "U1", "name": "member", "team_id": "T_HOME"},
+ {"id": "U2", "name": "deleted", "deleted": True},
+ {"id": "U3", "name": "bot", "is_bot": True},
+ {"id": "USLACKBOT", "name": "slackbot"},
+ # Guests are often external people; scout output must not be DM-able to them.
+ {"id": "U4", "name": "guest", "is_restricted": True},
+ {"id": "U5", "name": "single-channel-guest", "is_ultra_restricted": True},
+ # Members outside the connected workspace would be saveable in the picker but
+ # rejected by the delivery-time get_user_by_id recheck, so filter them here too.
+ {"id": "U6", "name": "connect-external", "team_id": "T_OTHER"},
+ {"id": "U7", "name": "stranger", "team_id": "T_HOME", "is_stranger": True},
+ ],
+ "response_metadata": {"next_cursor": ""},
+ }
+ self.integration.integration_id = "T_HOME"
+
+ slack = SlackIntegration(self.integration)
+
+ assert [member["id"] for member in slack.list_users()] == ["U1"]
+
+ @parameterized.expand(
+ [
+ ("workspace_member", {"id": "U1", "team_id": "T_HOME"}, True),
+ # Slack Connect externals resolve through users.info once the bot shares a channel with
+ # them; their home workspace differs so they must not become DM recipients.
+ ("external_workspace", {"id": "U2", "team_id": "T_OTHER"}, False),
+ ("stranger", {"id": "U3", "team_id": "T_HOME", "is_stranger": True}, False),
+ (
+ "grid_member_of_this_workspace",
+ {"id": "U4", "team_id": "T_OTHER", "enterprise_user": {"teams": ["T_HOME", "T_OTHER"]}},
+ True,
+ ),
+ ]
+ )
+ @patch("posthog.models.integration.slack.WebClient")
+ def test_get_user_by_id_workspace_membership(self, _name, member, expected_found, mock_webclient_class):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.return_value = {"user": member}
+ self.integration.integration_id = "T_HOME"
+
+ slack = SlackIntegration(self.integration)
+
+ result = slack.get_user_by_id(member["id"])
+ assert (result is not None) is expected_found
+
+ # user_not_visible must resolve to "no such recipient" like user_not_found — raising instead
+ # would make scout delivery retry a lookup that can never succeed.
+ @parameterized.expand([("user_not_found",), ("user_not_visible",)])
+ @patch("posthog.models.integration.slack.WebClient")
+ def test_get_user_by_id_terminal_lookup_errors_return_none(self, error_code, mock_webclient_class):
+ mock_client = MagicMock()
+ mock_webclient_class.return_value = mock_client
+ mock_client.users_info.side_effect = SlackApiError("lookup failed", {"error": error_code})
+
+ slack = SlackIntegration(self.integration)
+
+ assert slack.get_user_by_id("U123") is None
+
@patch("posthog.models.integration.slack.WebClient")
def test_list_channels_without_access(self, mock_webclient_class):
mock_client = MagicMock()
@@ -2056,6 +2122,249 @@ class TestIntegrationAPIKeyAccess:
data = response.json()
assert [channel["id"] for channel in data["channels"]] == expected_ids
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_users_action_lists_sorted_searched_and_paginated(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_USERS",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.list_users.return_value = [
+ {"id": "U2", "name": "robbie", "real_name": "Robbie C", "profile": {"display_name": "robbie"}},
+ # Empty display name falls back to real_name, which also sorts this member first.
+ {"id": "U1", "name": "andy.m", "real_name": "Andy Maguire", "profile": {"display_name": ""}},
+ ]
+ mock_slack_class.return_value = mock_slack_instance
+
+ key_value = "test_key_slack_users"
+ PersonalAPIKey.objects.create(
+ label="Test Key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["integration:read"],
+ )
+ base_url = f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/users/"
+
+ response = client.get(base_url, HTTP_AUTHORIZATION=f"Bearer {key_value}")
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert data["users"] == [
+ {"id": "U1", "name": "andy.m", "display_name": "Andy Maguire"},
+ {"id": "U2", "name": "robbie", "display_name": "robbie"},
+ ]
+ assert data["has_more"] is False
+
+ response = client.get(f"{base_url}?search=rob", HTTP_AUTHORIZATION=f"Bearer {key_value}")
+ assert response.status_code == status.HTTP_200_OK
+ assert [member["id"] for member in response.json()["users"]] == ["U2"]
+
+ response = client.get(f"{base_url}?limit=1", HTTP_AUTHORIZATION=f"Bearer {key_value}")
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ assert [member["id"] for member in data["users"]] == ["U1"]
+ assert data["has_more"] is True
+
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_users_action_direct_lookup_and_kind_guard(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_USERS_LOOKUP",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.get_user_by_id.return_value = {
+ "id": "U42",
+ "name": "andy.m",
+ "real_name": "Andy Maguire",
+ "profile": {"display_name": "andy"},
+ }
+ mock_slack_class.return_value = mock_slack_instance
+
+ key_value = "test_key_slack_users_lookup"
+ PersonalAPIKey.objects.create(
+ label="Test Key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["integration:read"],
+ )
+
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/users/?user_id=U42",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["users"] == [{"id": "U42", "name": "andy.m", "display_name": "andy"}]
+ mock_slack_instance.get_user_by_id.assert_called_once_with("U42")
+
+ # Lookups are cached per id — hits and misses alike — so repeated probes can't spend the
+ # workspace's Slack API quota one users.info call at a time.
+ mock_slack_instance.get_user_by_id.reset_mock()
+ mock_slack_instance.get_user_by_id.return_value = None
+ for _ in range(2):
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/users/?user_id=UMISSING",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["users"] == []
+ mock_slack_instance.get_user_by_id.assert_called_once_with("UMISSING")
+
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{self.github_integration.id}/users/",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "Slack" in response.json()["detail"]
+
+ @patch("posthog.api.integration.SLACK_USERS_INFO_LOOKUPS_PER_MINUTE", 2)
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_users_action_throttles_distinct_uncached_lookups(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_USERS_BUDGET",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.get_user_by_id.return_value = None
+ mock_slack_class.return_value = mock_slack_instance
+
+ key_value = "test_key_slack_users_budget"
+ PersonalAPIKey.objects.create(
+ label="Test Key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["integration:read"],
+ )
+
+ # Distinct ids each miss the per-id cache; the per-integration budget is what stops them.
+ for index, expected_status in enumerate(
+ [status.HTTP_200_OK, status.HTTP_200_OK, status.HTTP_429_TOO_MANY_REQUESTS]
+ ):
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/users/?user_id=UPROBE{index}",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+ assert response.status_code == expected_status
+ assert mock_slack_instance.get_user_by_id.call_count == 2
+
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_users_action_maps_missing_scope_to_reconnect(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_USERS_SCOPE",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ # An install predating the `users:read` scope never granted it.
+ mock_slack_instance.list_users.side_effect = SlackApiError(
+ "Slack request failed", {"ok": False, "error": "missing_scope"}
+ )
+ mock_slack_class.return_value = mock_slack_instance
+
+ key_value = "test_key_slack_users_scope"
+ PersonalAPIKey.objects.create(
+ label="Test Key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["integration:read"],
+ )
+
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/users/",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ body = response.json()
+ assert body["code"] == "slack_integration_inactive"
+ assert "reconnect slack" in body["detail"].lower()
+
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_users_action_serves_cached_list_while_a_refresh_is_in_flight(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_USERS_INFLIGHT",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ mock_slack_class.return_value = mock_slack_instance
+
+ key = f"slack/{slack_integration.id}/users"
+ cache.set(
+ key,
+ {
+ "users": [{"id": "U1", "name": "andy.m", "display_name": "Andy Maguire"}],
+ # Older than the refresh floor, so only the in-flight sentinel can hold this back.
+ "lastRefreshedAt": (timezone.now() - timedelta(minutes=5)).isoformat(),
+ },
+ 3600,
+ )
+ cache.add(f"{key}/filling", 1, 60)
+
+ client.force_login(self.user)
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/users/?force_refresh=true"
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [user["id"] for user in response.json()["users"]] == ["U1"]
+ mock_slack_instance.list_users.assert_not_called()
+
+ @patch("posthog.api.integration.SLACK_USERS_FILL_WAIT_SECONDS", 0.05)
+ @patch("posthog.api.integration.SlackIntegration")
+ def test_users_action_fills_when_a_cold_cache_fill_never_lands(self, mock_slack_class, client: HttpClient):
+ slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_USERS_COLD",
+ config={"authed_user": {"id": "test_user_id"}},
+ sensitive_config={"access_token": "test-token-123"},
+ created_by=self.user,
+ )
+ mock_slack_instance = MagicMock()
+ mock_slack_instance.list_users.return_value = [
+ {"id": "U1", "name": "andy.m", "real_name": "Andy Maguire", "profile": {"display_name": "Andy Maguire"}},
+ ]
+ mock_slack_class.return_value = mock_slack_instance
+
+ key_value = "test_key_slack_users_cold"
+ PersonalAPIKey.objects.create(
+ label="Test Key",
+ user=self.user,
+ secure_value=hash_key_value(key_value),
+ scopes=["integration:read"],
+ )
+
+ # Someone else holds the fill sentinel but never publishes a list — the loser has to fall
+ # through and enumerate rather than answer from the empty cache it waited on.
+ cache.delete(f"slack/{slack_integration.id}/users")
+ cache.add(f"slack/{slack_integration.id}/users/filling", 1, 60)
+
+ response = client.get(
+ f"/api/environments/{self.team.pk}/integrations/{slack_integration.id}/users/",
+ HTTP_AUTHORIZATION=f"Bearer {key_value}",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [user["id"] for user in response.json()["users"]] == ["U1"]
+ mock_slack_instance.list_users.assert_called_once()
+
def test_channels_action_with_missing_authed_user_returns_400(self, client: HttpClient):
slack_integration = Integration.objects.create(
team=self.team,
diff --git a/posthog/models/integration/slack.py b/posthog/models/integration/slack.py
index bc89a96bd56f..c39fb46d112a 100644
--- a/posthog/models/integration/slack.py
+++ b/posthog/models/integration/slack.py
@@ -128,6 +128,66 @@ class SlackIntegration:
return None
raise
+ def list_users(self) -> list[dict]:
+ """Human workspace members the bot can DM, as raw Slack member payloads."""
+ max_page = SLACK_CHANNELS_MAX_PAGES
+ users: list[dict] = []
+ cursor = None
+
+ while max_page > 0:
+ max_page -= 1
+ res = self.client.users_list(limit=SLACK_CHANNELS_PAGE_SIZE, cursor=cursor)
+ users.extend(
+ member
+ for member in res["members"]
+ if self._belongs_to_workspace(member) and self._is_dmable_user(member)
+ )
+ cursor = res["response_metadata"]["next_cursor"]
+ if not cursor:
+ break
+
+ return users
+
+ def get_user_by_id(self, user_id: str) -> dict | None:
+ try:
+ response = self.client.users_info(user=user_id)
+ member = response["user"]
+ if not self._belongs_to_workspace(member):
+ return None
+ return member if self._is_dmable_user(member) else None
+ except SlackApiError as e:
+ # user_not_visible is terminal too: the token can't see the member, so retrying the
+ # same lookup can never succeed.
+ if e.response["error"] in ("user_not_found", "user_not_visible"):
+ return None
+ raise
+
+ def _belongs_to_workspace(self, member: dict) -> bool:
+ # Slack also surfaces Connect externals the bot shares a channel with (users.info always,
+ # users.list depending on workspace shape), so reject members whose home workspace isn't
+ # this integration's: internal scout/DM output must never be routable outside the
+ # connected workspace. Enterprise Grid members may carry another primary team_id while
+ # still belonging to this workspace via enterprise_user.teams.
+ member_team_id = member.get("team_id")
+ enterprise_teams = (member.get("enterprise_user") or {}).get("teams") or []
+ return not member.get("is_stranger") and (
+ member_team_id is None
+ or member_team_id == self.integration.integration_id
+ or self.integration.integration_id in enterprise_teams
+ )
+
+ @staticmethod
+ def _is_dmable_user(member: dict) -> bool:
+ # Guests (single/multi-channel, often external people) are excluded like bots: DM surfaces
+ # deliver internal content, matching the slack_app onboarding and unfurl eligibility rules.
+ return (
+ not member.get("deleted")
+ and not member.get("is_bot")
+ and not member.get("is_restricted")
+ and not member.get("is_ultra_restricted")
+ and member.get("id") != "USLACKBOT"
+ )
+
def _list_channels_by_type(
self,
type: Literal["public_channel", "private_channel"],
diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.ts
index b774b1a66425..0c7f72cfc7d1 100644
--- a/products/integrations/frontend/generated/api.schemas.ts
+++ b/products/integrations/frontend/generated/api.schemas.ts
@@ -431,6 +431,27 @@ export interface LinearTeamsResponseApi {
teams: LinearTeamApi[]
}
+export interface SlackUserApi {
+ /** Slack member ID (e.g. U0123ABC) — post to it to open a direct message. */
+ id: string
+ /** Slack username (handle) without the leading '@'. */
+ name: string
+ /** Name to show in pickers: the member's display name, falling back to their real name or handle. */
+ display_name: string
+}
+
+export interface SlackUsersResponseApi {
+ /** Human Slack workspace members the PostHog Slack app can DM. */
+ users: SlackUserApi[]
+ /**
+ * ISO 8601 timestamp of the last full Slack API refresh (only set on full lists, not single-member lookups).
+ * @nullable
+ */
+ lastRefreshedAt?: string | null
+ /** Whether more members match the current search beyond this page. */
+ has_more?: boolean
+}
+
export interface GitHubAvailableInstallationApi {
/** GitHub installation ID to pass to github/link_existing when linking this installation. */
installation_id: string
@@ -853,3 +874,29 @@ export type IntegrationsGithubTeamsRetrieveParams = {
*/
search?: string
}
+
+export type IntegrationsUsersRetrieveParams = {
+ /**
+ * Bypass the 1 hour member cache. Honored only for browser session callers; API key, OAuth, and MCP callers always read through the cache.
+ */
+ force_refresh?: boolean
+ /**
+ * Maximum number of members to return per request (max 200).
+ * @minimum 1
+ * @maximum 200
+ */
+ limit?: number
+ /**
+ * Number of members to skip before returning results.
+ * @minimum 0
+ */
+ offset?: number
+ /**
+ * Optional case-insensitive member name or ID search query.
+ */
+ search?: string
+ /**
+ * Look up one member directly by Slack member ID (e.g. U0123ABC). When set, `search`, `limit`, and `offset` are ignored and the response holds at most that member.
+ */
+ user_id?: string
+}
diff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.ts
index 86b72f60ba85..74c5d1d2ed75 100644
--- a/products/integrations/frontend/generated/api.ts
+++ b/products/integrations/frontend/generated/api.ts
@@ -26,6 +26,7 @@ import type {
IntegrationsGithubReposRetrieveParams,
IntegrationsGithubTeamsRetrieveParams,
IntegrationsListParams,
+ IntegrationsUsersRetrieveParams,
JiraProjectsResponseApi,
LinearTeamsResponseApi,
OrganizationIntegrationApi,
@@ -41,6 +42,7 @@ import type {
RoleExternalReferencesLookupRetrieveParams,
RoleLookupResponseApi,
SlackChannelsResponseApi,
+ SlackUsersResponseApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -624,6 +626,38 @@ export const integrationsTwilioPhoneNumbersRetrieve = async (
})
}
+export const getIntegrationsUsersRetrieveUrl = (
+ projectId: string,
+ id: number,
+ params?: IntegrationsUsersRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/integrations/${id}/users/?${stringifiedParams}`
+ : `/api/projects/${projectId}/integrations/${id}/users/`
+}
+
+export const integrationsUsersRetrieve = async (
+ projectId: string,
+ id: number,
+ params?: IntegrationsUsersRetrieveParams,
+ options?: RequestInit
+): Promise<SlackUsersResponseApi> => {
+ return apiMutator<SlackUsersResponseApi>(getIntegrationsUsersRetrieveUrl(projectId, id, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getIntegrationsAuthorizeRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/integrations/authorize/`
}
diff --git a/products/integrations/mcp/tools.yaml b/products/integrations/mcp/tools.yaml
index 32731337c6b6..1704942ff0ae 100644
--- a/products/integrations/mcp/tools.yaml
+++ b/products/integrations/mcp/tools.yaml
@@ -207,6 +207,26 @@ tools:
integrations-twilio-phone-numbers-retrieve:
operation: integrations_twilio_phone_numbers_retrieve
enabled: false
+ integrations-users-retrieve:
+ operation: integrations_users_retrieve
+ enabled: true
+ scopes:
+ - integration:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: List integration Slack members
+ description: >
+ List the Slack workspace members a Slack integration can send direct messages to. Slack-only — non-Slack
+ integration ids return an error (400 if the integration is otherwise visible, 404 if it isn't). Returns each
+ member's id (e.g. U0123ABC), name (handle without the leading @), and display_name; bots, deactivated
+ accounts, and Slackbot are excluded. Supports `search` (fuzzy match on display name and handle, plus
+ id-contains), `limit`, `offset`, and a `user_id` query parameter for a direct lookup. Results are cached for
+ 1 hour (no force-refresh exposed via MCP). Use this to find member ids when configuring a scout's Slack DM
+ destination — pass them as `output_destinations.slack.users` entries (`member_id|@display-name`) via
+ scout-config-update or scout-create. Requires the Slack integration's id; use integrations-list (filter by
+ kind=slack) to find it.
posthog-connection-forward:
operation: posthog_connections_forward_create
enabled: true
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 45ac476247f2..69fbd231c4f8 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -2087,11 +2087,20 @@ export interface SignalScoutSlackDestinationApi {
*/
integration_id: number
/**
- * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set.
+ * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set.
* @maxLength 255
* @nullable
*/
channel?: string | null
+ /**
+ * Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.
+ * @minItems 1
+ * @maxItems 5
+ * @nullable
+ * @items.maxLength 255
+ * @items.pattern ^[UW][A-Z0-9]{4,}\s*(\|.*)?$
+ */
+ users?: string[] | null
/** When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post. */
thread_reports?: boolean
}
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index f3ba532f0ce8..5a0eaf701659 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -1304,6 +1304,13 @@ export const visionScannersScoutsCreateBodyConfigOneRunIntervalMinutesMax = 4320
export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax = 255
+export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemMax = 255
+
+export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemRegExp = new RegExp(
+ '^[UW][A-Z0-9]{4,}\\s\*(\\|.\*)?$'
+)
+export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneUsersMax = 5
+
export const visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault = false
export const visionScannersScoutsCreateBodyConfigOneRunCronScheduleMax = 100
@@ -1366,7 +1373,26 @@ export const VisionScannersScoutsCreateBody = /* @__PURE__ */ zod
)
.nullish()
.describe(
- "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
+ ),
+ users: zod
+ .array(
+ zod
+ .string()
+ .max(
+ visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemMax
+ )
+ .regex(
+ visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemRegExp
+ )
+ )
+ .min(1)
+ .max(
+ visionScannersScoutsCreateBodyConfigOneOutputDestinationsOneSlackOneUsersMax
+ )
+ .nullish()
+ .describe(
+ 'Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.'
),
thread_reports: zod
.boolean()
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 9d7ca36c0847..850a4c45d374 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1459,8 +1459,8 @@ class SignalScoutConfig(ModelActivityMixin, TeamScopedRootMixin, UUIDModel):
model = models.CharField(max_length=200, null=True, blank=True)
# Optional destinations for each finding or report this scout emits. Kept as a typed JSON object at
# the API boundary so adding another destination does not require another pair of nullable
- # config columns. A Slack destination is active only when both its integration and channel
- # are present; the UI may persist the integration first while the user chooses a channel.
+ # config columns. A Slack destination is active only when its integration and a target — a channel,
+ # or a member to DM — are present; the UI may persist the integration first while the user chooses.
output_destinations = models.JSONField(default=dict, db_default={})
# Free-form labels for grouping the fleet ("revenue", "on-call", "experimental"). Normalized
# to lowercase and deduped at the API boundary, so a tag means the same thing whoever typed
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 04496fbaf4df..d8af3f22904a 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -23,7 +23,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
- `config_registry.py`
`register_missing_configs(team_id)` — auto-creates an enabled, default-schedule `SignalScoutConfig` for any `signals-scout-*` skill lacking one ("author a skill, get a scout"). Called by the coordinator tick; the HTTP surface registers explicitly via the write-scoped config `create` endpoint instead (reads stay side-effect free). A canonical scout's `scout-tags` frontmatter (read through `lazy_seed.canonical_config_tags_for`) is stamped on the row it creates, which is how a product surface claims its scouts by tag instead of by hardcoded skill name — AI observability's self-driving tab lists the `ai-observability`-tagged configs. Forward-only like the rest of the seed posture: adding the key to an already-seeded scout leaves that team's existing config untagged until someone tags it through the config API.
- `slack_delivery.py` / `slack_delivery_queue.py` / `slack_charts.py`
- Best-effort direct Slack delivery for configured scout outputs. Finding emissions and surfaced report emits/edits snapshot the run config's destination after their database write commits, then enqueue the shared retrying Celery worker. Integrations are project-scoped, so a workspace connected from any environment in the project can receive the canonical parent team's scout output.
+ Best-effort direct Slack delivery for configured scout outputs. Finding emissions and surfaced report emits/edits snapshot the run config's destination after their database write commits, then enqueue the shared retrying Celery worker. The destination targets a single channel or up to `MAX_SCOUT_SLACK_DM_TARGETS` members who each get an individual DM (one Celery task per recipient, so retries and permanent failures stay independent; a group DM would need the `mpim:write` scope the Slack app doesn't request). Integrations are project-scoped, so a workspace connected from any environment in the project can receive the canonical parent team's scout output.
A report message renders its `charts` through the exports facade (`render_png_export`, attributed to the run's acting user, so the insight access check applies; a system render that expires with its delivery url, so it stays out of the user's export quota and does not outlive its only reference) and appends them as `image` blocks pointing at a signed delivery url; chart links in the prose still reduce to their label. A threaded report carries its charts on the lead message, since the replies only hold the summary's tail. Only `InsightVizNode` / `SavedInsightNode` charts render, capped per report and by a render-time budget (a render only starts if it can finish inside the budget), with rendered assets remembered per delivery so a Slack retry does not re-render, and every failure is skipped rather than failing the delivery — the whole chart build is best effort, not only the render. The Slack integration row is resolved again after the build, since a workspace reconnected during the render window replaces the token on the same row.
A threaded report splits its summary at the shallowest Markdown heading level that summary repeats at, so a sub-heading rides in its parent's reply and the thread mirrors the outline the reader sees in the inbox; a level used once is the report's own title rather than a seam, so the split descends past it. The split runs at any length, because a typical digest fits inside one Slack section and a length test leaves it in the channel as the wall of text threading exists to break up. A summary with no heading has no seam and stays one message, hard-chunked only past the section cap.
Slack fetches each image url itself and rejects the whole message when it cannot reach one, so a rejected message is posted again without its charts, which carry `CHART_BLOCK_ID_PREFIX` block ids to be dropped as whole units; a deployment Slack cannot reach still gets the prose and the report link.
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.py
index 42a5cb01ff6f..d26dc579c3e4 100644
--- a/products/signals/backend/scout_harness/serializers.py
+++ b/products/signals/backend/scout_harness/serializers.py
@@ -9,6 +9,7 @@ shape and Python shape stay in lockstep.
from __future__ import annotations
+import re
from datetime import UTC, datetime
from typing import Any
from uuid import UUID
@@ -38,6 +39,7 @@ from products.signals.backend.scout_harness.derived_metadata import DERIVED_FLAG
from products.signals.backend.scout_harness.model_selection import scout_model_config_enabled, scout_model_pin_catalog
from products.signals.backend.scout_harness.note_targets import PIPELINE_AUDIENCES
from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX
+from products.signals.backend.scout_harness.slack_delivery import MAX_SCOUT_SLACK_DM_TARGETS
from products.signals.backend.scout_harness.tags import slugify_tag
from products.signals.backend.scout_harness.tools.emit import (
MAX_FINDING_ID_LENGTH,
@@ -2043,6 +2045,13 @@ class ProjectProfileSerializer(serializers.Serializer):
# --- Scout config ----------------------------------------------------------
+# A Slack member target: the member ID alone, or the picker's `U0123ABC456|@display name` composite.
+SLACK_MEMBER_TARGET_RE = r"^[UW][A-Z0-9]{4,}\s*(\|.*)?$"
+SLACK_MEMBER_TARGET_ERROR = (
+ "Expected a Slack member ID starting with U or W, e.g. `U0123ABC456` or `U0123ABC456|@name`."
+)
+
+
class SignalScoutSlackDestinationSerializer(serializers.Serializer):
integration_id = serializers.IntegerField(
min_value=1,
@@ -2056,9 +2065,34 @@ class SignalScoutSlackDestinationSerializer(serializers.Serializer):
trim_whitespace=True,
help_text=(
"Slack channel target in the channel picker's `channel_id|#channel-name` format. "
- "Null while choosing a channel; no messages are sent until it is set."
+ "Null while choosing a channel; no messages are sent until a channel or user is set."
+ ),
+ )
+ users = serializers.ListField(
+ # The pattern reaches the OpenAPI schema (unlike `validate_users` below, which stays the
+ # authority), so generated MCP/Zod clients reject a handle or channel id before the API 400s.
+ child=serializers.RegexField(
+ SLACK_MEMBER_TARGET_RE,
+ allow_blank=False,
+ max_length=255,
+ trim_whitespace=True,
+ error_messages={"invalid": SLACK_MEMBER_TARGET_ERROR},
+ ),
+ required=False,
+ allow_null=True,
+ allow_empty=False,
+ # `allow_empty` alone doesn't reach the OpenAPI schema; `min_length` emits `minItems: 1` so
+ # generated MCP/Zod clients can't construct an empty list the API would 400.
+ min_length=1,
+ max_length=MAX_SCOUT_SLACK_DM_TARGETS,
+ help_text=(
+ "Slack members to send output to as direct messages, each in `member_id|@display-name` format "
+ "(a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the "
+ f"PostHog app; at most {MAX_SCOUT_SLACK_DM_TARGETS}. Set either this or `channel`, not both. "
+ "Useful for personal scouts where a DM beats a channel."
),
)
+
thread_reports = serializers.BooleanField(
required=False,
default=False,
@@ -2069,6 +2103,29 @@ class SignalScoutSlackDestinationSerializer(serializers.Serializer):
),
)
+ def validate_users(self, value: list[str] | None) -> list[str] | None:
+ if value is None:
+ return value
+ deduped: list[str] = []
+ seen_ids: set[str] = set()
+ for target in value:
+ member_id = target.split("|", 1)[0].strip()
+ if not re.fullmatch(r"[UW][A-Z0-9]{4,}", member_id):
+ raise serializers.ValidationError(
+ f"{target!r} is not a Slack member target. Expected a member ID starting with U or W, "
+ "e.g. `U0123ABC456` or `U0123ABC456|@name`."
+ )
+ if member_id in seen_ids:
+ continue
+ seen_ids.add(member_id)
+ deduped.append(target)
+ return deduped
+
+ def validate(self, attrs: dict) -> dict:
+ if attrs.get("channel") and attrs.get("users"):
+ raise serializers.ValidationError("Set either `channel` or `users`, not both.")
+ return attrs
+
class SignalScoutWebhookDestinationSerializer(serializers.Serializer):
hog_function_id = serializers.CharField(
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.py
index 94cc3ddbd771..6c87a18d2b89 100644
--- a/products/signals/backend/scout_harness/slack_delivery.py
+++ b/products/signals/backend/scout_harness/slack_delivery.py
@@ -37,16 +37,19 @@ logger = structlog.get_logger(__name__)
_PERMANENT_SLACK_ERROR_CODES = frozenset(
{
"account_inactive",
+ "cannot_dm_bot",
"channel_not_found",
"ekm_access_denied",
"invalid_auth",
"is_archived",
+ "messages_tab_disabled",
"missing_scope",
"not_authed",
"not_in_channel",
"org_login_required",
"restricted_action",
"token_revoked",
+ "user_not_found",
}
)
@@ -57,6 +60,10 @@ _BLOCK_REJECTION_ERROR_CODES = frozenset({"invalid_blocks", "invalid_blocks_form
ScoutSlackOutputType = Literal["finding", "report"]
+# Each member gets an individual DM (a group DM would need the `mpim:write` scope the Slack app
+# doesn't request), so this bounds the per-output Slack API fan-out.
+MAX_SCOUT_SLACK_DM_TARGETS = 5
+
# A report only reaches Slack while it is surfaced. Checked both before enqueue and again just
# before posting, since chart rendering can hold the worker long enough for the report to change.
DELIVERABLE_REPORT_STATUSES = frozenset((SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT))
@@ -73,7 +80,10 @@ _SCOUT_SLACK_REPLY_TEXT = "💬 If you have questions, reply in this thread and
@dataclass(frozen=True)
class ScoutSlackDestination:
integration_id: int
- channel: str
+ # Conversation targets in the picker's `id|name` composite form: a single channel (`C…|#name`)
+ # or one or more members to DM individually (`U…|@name`) — Slack's chat.postMessage accepts
+ # either id as its `channel` argument, opening the DM for a member id.
+ targets: tuple[str, ...]
thread_reports: bool = False
@@ -91,15 +101,24 @@ def get_scout_slack_destination(output_destinations: object) -> ScoutSlackDestin
if not isinstance(slack, dict):
return None
integration_id = slack.get("integration_id")
- channel = slack.get("channel")
if not isinstance(integration_id, int) or isinstance(integration_id, bool) or integration_id < 1:
return None
- if not isinstance(channel, str) or not channel.strip():
+ thread_reports = slack.get("thread_reports") is True
+ channel = slack.get("channel")
+ if isinstance(channel, str) and channel.strip():
+ return ScoutSlackDestination(
+ integration_id=integration_id, targets=(channel.strip(),), thread_reports=thread_reports
+ )
+ users = slack.get("users")
+ if not isinstance(users, list):
+ return None
+ targets = tuple(dict.fromkeys(user.strip() for user in users if isinstance(user, str) and user.strip()))
+ if not targets:
return None
return ScoutSlackDestination(
integration_id=integration_id,
- channel=channel.strip(),
- thread_reports=slack.get("thread_reports") is True,
+ targets=targets[:MAX_SCOUT_SLACK_DM_TARGETS],
+ thread_reports=thread_reports,
)
@@ -165,6 +184,24 @@ def _slack_integration_for_project(*, integration_id: int, project_id: int) -> I
return integration
+def _ensure_dm_recipient_eligible(slack: SlackIntegration, target_id: str) -> None:
+ """Re-resolve a DM recipient's eligibility at send time.
+
+ Config validation only checks the ID shape, so an API/MCP caller can persist any well-formed
+ member ID, and a member who was eligible at config time can later become a guest or leave.
+ `get_user_by_id` applies the same eligibility rules as the picker (no bots, guests, or
+ members from outside the connected workspace), so an ineligible recipient fails permanently
+ here instead of leaking internal output.
+ """
+ if not target_id.startswith(("U", "W")):
+ return
+ if slack.get_user_by_id(target_id) is None:
+ raise ScoutSlackPermanentDeliveryError(
+ "The configured Slack member can no longer receive scout output",
+ error_code="recipient_not_eligible",
+ )
+
+
def _slack_channel_id(channel: str) -> str:
channel_id = slack_channel_id_from_target(channel)
if not channel_id:
@@ -224,6 +261,7 @@ def build_scout_slack_message(emission: SignalScoutEmission) -> tuple[list[dict]
def post_scout_emission_to_slack(
emission: SignalScoutEmission,
*,
+ delivery_id: str,
integration_id: int,
channel: str,
) -> None:
@@ -234,13 +272,17 @@ def post_scout_emission_to_slack(
channel_id = _slack_channel_id(channel)
blocks, fallback = build_scout_slack_message(emission)
- client = SlackIntegration(integration).client
+ slack = SlackIntegration(integration)
+ client = slack.client
try:
+ _ensure_dm_recipient_eligible(slack, channel_id)
response = client.chat_postMessage(
channel=channel_id,
blocks=blocks,
text=fallback,
- client_msg_id=str(emission.id),
+ # The queue derives one delivery_id per recipient, so each DM keeps its own
+ # Slack idempotency key instead of every recipient sharing the emission id.
+ client_msg_id=delivery_id,
unfurl_links=False,
unfurl_media=False,
)
@@ -642,8 +684,10 @@ def post_scout_report_to_slack(
integration_id=integration_id,
project_id=report.team.project_id,
)
- client = SlackIntegration(integration).client
+ slack = SlackIntegration(integration)
+ client = slack.client
try:
+ _ensure_dm_recipient_eligible(slack, channel_id)
response = _post_scout_report_lead_message(
client,
channel_id=channel_id,
diff --git a/products/signals/backend/scout_harness/slack_delivery_queue.py b/products/signals/backend/scout_harness/slack_delivery_queue.py
index c94c151c0969..3ee18ae87c8e 100644
--- a/products/signals/backend/scout_harness/slack_delivery_queue.py
+++ b/products/signals/backend/scout_harness/slack_delivery_queue.py
@@ -44,21 +44,30 @@ def queue_configured_scout_slack_delivery(
if destination is None:
return
- transaction.on_commit(
- partial(
- enqueue_scout_slack_delivery,
- team_id=run.team_id,
- output_type=output_type,
- output_id=output_id,
- run_id=str(run.id),
- delivery_id=delivery_id or str(uuid.uuid4()),
- integration_id=destination.integration_id,
- channel=destination.channel,
- edit_note=edit_note[:MAX_SLACK_NOTE_SNAPSHOT_LEN] if edit_note is not None else None,
- thread_reports=destination.thread_reports,
- ),
- robust=True,
- )
+ base_delivery_id = delivery_id or str(uuid.uuid4())
+ note_snapshot = edit_note[:MAX_SLACK_NOTE_SNAPSHOT_LEN] if edit_note is not None else None
+ for index, target in enumerate(destination.targets):
+ transaction.on_commit(
+ partial(
+ enqueue_scout_slack_delivery,
+ team_id=run.team_id,
+ output_type=output_type,
+ output_id=output_id,
+ run_id=str(run.id),
+ # Extra DM recipients get their own derived id so each Slack message keeps a
+ # distinct client_msg_id — a UUID, since Slack rejects non-UUID values there.
+ delivery_id=(
+ base_delivery_id
+ if index == 0
+ else str(uuid.uuid5(uuid.NAMESPACE_OID, f"{base_delivery_id}:{index}"))
+ ),
+ integration_id=destination.integration_id,
+ channel=target,
+ edit_note=note_snapshot,
+ thread_reports=destination.thread_reports,
+ ),
+ robust=True,
+ )
except Exception as exc:
capture_exception(
exc,
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index a28fa47ad880..2f1b755fb092 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -143,6 +143,7 @@ def deliver_scout_slack_output(
return
post_scout_emission_to_slack(
emission,
+ delivery_id=delivery_id,
integration_id=integration_id,
channel=channel,
)
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index deede1a2a4f2..36e4a0f5eeb3 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -49,7 +49,10 @@ from products.signals.backend.scout_harness.lazy_seed import (
from products.signals.backend.scout_harness.limits import STALE_RUN_CUTOFF_S
from products.signals.backend.scout_harness.note_targets import PIPELINE_AUDIENCE_REPORT_RESEARCH as PIPELINE_AUDIENCE
from products.signals.backend.scout_harness.prompt import FOLLOWUP_KEY_PREFIX
-from products.signals.backend.scout_harness.serializers import SignalScoutConfigUpdateSerializer
+from products.signals.backend.scout_harness.serializers import (
+ SignalScoutConfigUpdateSerializer,
+ SignalScoutSlackDestinationSerializer,
+)
from products.signals.backend.scout_harness.team_limits import MAX_RUNS_PER_TEAM_PER_TICK
from products.signals.backend.scout_harness.tools import structured_output as structured_output_tool
from products.signals.backend.scout_harness.tools.profile import compute_project_profile
@@ -2289,7 +2292,27 @@ class TestScoutHarnessConfigAPI(APIBaseTest):
# A partial update skips the `thread_reports` default, so the flag reaches the reader
# through the response only and the stored destination keeps the shape it was sent in.
assert response.json()["output_destinations"] == {
- "slack": {**destination["slack"], "thread_reports": False},
+ "slack": {**destination["slack"], "users": None, "thread_reports": False},
+ "webhook": None,
+ }
+ config.refresh_from_db()
+ assert config.output_destinations == destination
+
+ def test_partial_update_slack_dm_destination_round_trips(self) -> None:
+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo")
+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
+ destination = {"slack": {"integration_id": integration.id, "users": ["U0123ABC456|@andy"]}}
+
+ response = self.client.patch(
+ self._detail_url(str(config.id)),
+ data={"output_destinations": destination},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ # Reads render both target keys, null when unset; the stored JSON keeps only what was sent.
+ assert response.json()["output_destinations"] == {
+ "slack": {**destination["slack"], "channel": None, "thread_reports": False},
"webhook": None,
}
config.refresh_from_db()
@@ -3390,3 +3413,25 @@ class TestScoutRunDerivedMetadata(APIBaseTest):
metadata = response.json()["metadata"]
assert metadata["model"] == "some-model"
assert metadata[DERIVED_METADATA_KEY]["has_emit_report"] is False
+
+
+class TestSignalScoutSlackDestinationSerializerValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("both_channel_and_users", {"integration_id": 1, "channel": "C1|#alerts", "users": ["U0123ABC|@a"]}),
+ ("not_a_member_id", {"integration_id": 1, "users": ["andy"]}),
+ ("channel_id_in_users", {"integration_id": 1, "users": ["C0123ABC456|#alerts"]}),
+ ("lowercase_member_id", {"integration_id": 1, "users": ["u0123abc456|@a"]}),
+ ("too_many_users", {"integration_id": 1, "users": [f"U0{index}ABCDE|@u{index}" for index in range(6)]}),
+ ]
+ )
+ def test_rejects_invalid_dm_destinations(self, _name: str, data: dict) -> None:
+ serializer = SignalScoutSlackDestinationSerializer(data=data)
+ assert not serializer.is_valid()
+
+ def test_dedupes_users_by_member_id(self) -> None:
+ serializer = SignalScoutSlackDestinationSerializer(
+ data={"integration_id": 1, "users": ["U0123ABC|@a", "U0123ABC", "W0456DEF|@b"]}
+ )
+ assert serializer.is_valid(), serializer.errors
+ assert serializer.validated_data["users"] == ["U0123ABC|@a", "W0456DEF|@b"]
diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.py
index af6378ef17a8..d337d8ee4f32 100644
--- a/products/signals/backend/test/test_scout_slack_delivery.py
+++ b/products/signals/backend/test/test_scout_slack_delivery.py
@@ -17,6 +17,8 @@ from posthog.redis import get_client
from products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRun
from products.signals.backend.scout_harness.slack_charts import CHART_BLOCK_ID_PREFIX as PREFIX
from products.signals.backend.scout_harness.slack_delivery import (
+ MAX_SCOUT_SLACK_DM_TARGETS,
+ ScoutSlackDestination,
ScoutSlackPermanentDeliveryError,
_latest_report_delivery_key,
get_scout_slack_destination,
@@ -27,7 +29,47 @@ from products.signals.backend.scout_harness.slack_delivery_queue import queue_co
from products.signals.backend.tasks import deliver_scout_slack_output, enqueue_scout_slack_delivery
+class FakeSlackResponse(dict):
+ def __init__(self, data: dict, headers: dict | None = None) -> None:
+ super().__init__(data)
+ self.headers = headers or {}
+
+
class TestGetScoutSlackDestination(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("channel", {"integration_id": 5, "channel": "C123|#alerts"}, ("C123|#alerts",)),
+ ("single_user", {"integration_id": 5, "users": ["U123|@andy"]}, ("U123|@andy",)),
+ ("multiple_users", {"integration_id": 5, "users": ["U1|@a", "U2|@b"]}, ("U1|@a", "U2|@b")),
+ ("channel_wins_over_users", {"integration_id": 5, "channel": "C1|#a", "users": ["U1|@a"]}, ("C1|#a",)),
+ (
+ "users_deduped_and_garbage_filtered",
+ {"integration_id": 5, "users": ["U1|@a", " ", None, "U1|@a", 7]},
+ ("U1|@a",),
+ ),
+ ]
+ )
+ def test_parses_active_destination(self, _name: str, slack: dict, expected_targets: tuple[str, ...]) -> None:
+ destination = get_scout_slack_destination({"slack": slack})
+ assert destination == ScoutSlackDestination(integration_id=5, targets=expected_targets)
+
+ @parameterized.expand(
+ [
+ ("no_target", {"integration_id": 5}),
+ ("empty_users", {"integration_id": 5, "users": []}),
+ ("users_not_a_list", {"integration_id": 5, "users": "U1|@a"}),
+ ("bad_integration_id", {"integration_id": True, "users": ["U1|@a"]}),
+ ]
+ )
+ def test_returns_none_for_inactive_or_malformed(self, _name: str, slack: dict) -> None:
+ assert get_scout_slack_destination({"slack": slack}) is None
+
+ def test_caps_dm_targets(self) -> None:
+ users = [f"U{index}|@user{index}" for index in range(MAX_SCOUT_SLACK_DM_TARGETS + 3)]
+ destination = get_scout_slack_destination({"slack": {"integration_id": 5, "users": users}})
+ assert destination is not None
+ assert destination.targets == tuple(users[:MAX_SCOUT_SLACK_DM_TARGETS])
+
@parameterized.expand(
[
("explicit_true", {"thread_reports": True}, True),
@@ -44,12 +86,6 @@ class TestGetScoutSlackDestination(SimpleTestCase):
assert destination.thread_reports is expected
-class FakeSlackResponse(dict):
- def __init__(self, data: dict, headers: dict | None = None) -> None:
- super().__init__(data)
- self.headers = headers or {}
-
-
class TestScoutSlackDelivery(BaseTest):
def _make_emission(self, description: str = "**Checkout** failures") -> SignalScoutEmission:
Task = apps.get_model("tasks", "Task")
@@ -97,6 +133,7 @@ class TestScoutSlackDelivery(BaseTest):
slack_integration.return_value.client = fake_client
post_scout_emission_to_slack(
emission,
+ delivery_id=str(emission.id),
integration_id=integration.id,
channel="CSCOUTS|#scout-findings",
)
@@ -452,12 +489,53 @@ class TestScoutSlackDelivery(BaseTest):
slack_integration.return_value.client = fake_client
post_scout_emission_to_slack(
emission,
+ delivery_id=str(emission.id),
integration_id=integration.id,
channel="CSCOUTS|#scout-findings",
)
assert fake_client.chat_postMessage.call_count == 2
+ @parameterized.expand(
+ [
+ ("eligible_member", {"id": "U123ABC45"}, True),
+ # None covers every ineligibility get_user_by_id enforces: unknown id, guest,
+ # bot, or a member from outside the connected workspace.
+ ("ineligible_member", None, False),
+ ]
+ )
+ def test_dm_delivery_revalidates_recipient_eligibility(self, _name, member, expect_sent) -> None:
+ emission = self._make_emission()
+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
+ fake_client = MagicMock()
+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000600"}
+
+ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:
+ slack_integration.return_value.client = fake_client
+ slack_integration.return_value.get_user_by_id.return_value = member
+ if expect_sent:
+ post_scout_emission_to_slack(
+ emission,
+ delivery_id=str(emission.id),
+ integration_id=integration.id,
+ channel="U123ABC45|@andy",
+ )
+ else:
+ with pytest.raises(ScoutSlackPermanentDeliveryError) as err:
+ post_scout_emission_to_slack(
+ emission,
+ delivery_id=str(emission.id),
+ integration_id=integration.id,
+ channel="U123ABC45|@andy",
+ )
+ assert err.value.error_code == "recipient_not_eligible"
+
+ slack_integration.return_value.get_user_by_id.assert_called_once_with("U123ABC45")
+ if expect_sent:
+ assert fake_client.chat_postMessage.call_args_list[0].kwargs["channel"] == "U123ABC45"
+ else:
+ fake_client.chat_postMessage.assert_not_called()
+
def test_task_skips_report_suppressed_before_delivery(self) -> None:
emission = self._make_emission()
report = SignalReport.objects.create(
diff --git a/products/signals/backend/test/test_signal_scout_models.py b/products/signals/backend/test/test_signal_scout_models.py
index 72b5d9dbab52..560450161b78 100644
--- a/products/signals/backend/test/test_signal_scout_models.py
+++ b/products/signals/backend/test/test_signal_scout_models.py
@@ -1,9 +1,10 @@
+import uuid
from contextlib import AbstractContextManager
from typing import TYPE_CHECKING
import pytest
from posthog.test.base import BaseTest
-from unittest.mock import patch
+from unittest.mock import call, patch
from django.apps import apps
from django.db import IntegrityError
@@ -123,6 +124,62 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):
thread_reports=False,
)
+ def test_record_emit_enqueues_dm_destination_per_recipient(self) -> None:
+ config = SignalScoutConfig.objects.create(
+ team=self.team,
+ skill_name="signals-scout-errors",
+ output_destinations={"slack": {"integration_id": 17, "users": ["U1|@andy", "U2|@robbie"]}},
+ )
+ run = SignalScoutRun.objects.create(
+ task_run=self._make_task_run(),
+ team=self.team,
+ scout_config=config,
+ skill_name=config.skill_name,
+ skill_version=1,
+ )
+
+ with patch(
+ "products.signals.backend.scout_harness.slack_delivery_queue.enqueue_scout_slack_delivery"
+ ) as enqueue:
+ with self.captureOnCommitCallbacks(execute=True):
+ _record_emit(
+ run_id=run.id,
+ finding_id="finding-1",
+ description="A finding",
+ weight=1.0,
+ confidence=0.8,
+ severity="P1",
+ source_id=f"run:{run.id}:finding:finding-1",
+ tags=["checkout"],
+ )
+
+ emission = run.emissions.get(finding_id="finding-1")
+ assert enqueue.call_args_list == [
+ call(
+ team_id=self.team.id,
+ output_type="finding",
+ output_id=str(emission.id),
+ run_id=str(run.id),
+ delivery_id=str(emission.id),
+ integration_id=17,
+ channel="U1|@andy",
+ edit_note=None,
+ thread_reports=False,
+ ),
+ call(
+ team_id=self.team.id,
+ output_type="finding",
+ output_id=str(emission.id),
+ run_id=str(run.id),
+ # Extra recipients get a derived-but-valid UUID: Slack rejects non-UUID client_msg_ids.
+ delivery_id=str(uuid.uuid5(uuid.NAMESPACE_OID, f"{emission.id}:1")),
+ integration_id=17,
+ channel="U2|@robbie",
+ edit_note=None,
+ thread_reports=False,
+ ),
+ ]
+
def test_enabling_scout_logs_activity(self) -> None:
config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-foo", enabled=False)
config.enabled = True
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index e8da82ba6d8c..7cffe4315a4c 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -1840,11 +1840,20 @@ export interface SignalScoutSlackDestinationApi {
*/
integration_id: number
/**
- * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set.
+ * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set.
* @maxLength 255
* @nullable
*/
channel?: string | null
+ /**
+ * Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.
+ * @minItems 1
+ * @maxItems 5
+ * @nullable
+ * @items.maxLength 255
+ * @items.pattern ^[UW][A-Z0-9]{4,}\s*(\|.*)?$
+ */
+ users?: string[] | null
/** When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post. */
thread_reports?: boolean
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index a00778db9eeb..c9365b8a1abe 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -336,6 +336,13 @@ export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200
export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax = 255
+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemMax = 255
+
+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemRegExp = new RegExp(
+ '^[UW][A-Z0-9]{4,}\\s\*(\\|.\*)?$'
+)
+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersMax = 5
+
export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault = false
export const signalsScoutCreateBodyConfigOneRunCronScheduleMax = 100
@@ -415,7 +422,24 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod
.max(signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax)
.nullish()
.describe(
- "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
+ ),
+ users: zod
+ .array(
+ zod
+ .string()
+ .max(
+ signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemMax
+ )
+ .regex(
+ signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemRegExp
+ )
+ )
+ .min(1)
+ .max(signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersMax)
+ .nullish()
+ .describe(
+ 'Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.'
),
thread_reports: zod
.boolean()
@@ -530,6 +554,13 @@ export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200
export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax = 255
+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersItemMax = 255
+
+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersItemRegExp = new RegExp(
+ '^[UW][A-Z0-9]{4,}\\s\*(\\|.\*)?$'
+)
+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersMax = 5
+
export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneThreadReportsDefault = false
export const signalsScoutConfigCreateBodyRunCronScheduleMax = 100
@@ -572,7 +603,20 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.max(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax)
.nullish()
.describe(
- "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
+ ),
+ users: zod
+ .array(
+ zod
+ .string()
+ .max(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersItemMax)
+ .regex(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersItemRegExp)
+ )
+ .min(1)
+ .max(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersMax)
+ .nullish()
+ .describe(
+ 'Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.'
),
thread_reports: zod
.boolean()
@@ -674,6 +718,13 @@ export const signalsScoutConfigUpdateBodyRunCronScheduleMax = 100
export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax = 255
+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersItemMax = 255
+
+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersItemRegExp = new RegExp(
+ '^[UW][A-Z0-9]{4,}\\s\*(\\|.\*)?$'
+)
+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersMax = 5
+
export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneThreadReportsDefault = false
export const signalsScoutConfigUpdateBodyModelMax = 200
@@ -724,7 +775,20 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
.max(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax)
.nullish()
.describe(
- "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
+ ),
+ users: zod
+ .array(
+ zod
+ .string()
+ .max(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersItemMax)
+ .regex(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersItemRegExp)
+ )
+ .min(1)
+ .max(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersMax)
+ .nullish()
+ .describe(
+ 'Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.'
),
thread_reports: zod
.boolean()
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx
index 795be3ad1041..101a9208ad4d 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx
@@ -1,10 +1,11 @@
import { useMountedLogic, useValues } from 'kea'
+import { useState } from 'react'
import { IconTrash } from '@posthog/icons'
-import { LemonButton, LemonSelect, LemonSwitch, Link } from '@posthog/lemon-ui'
+import { LemonButton, LemonSegmentedButton, LemonSelect, LemonSwitch, Link } from '@posthog/lemon-ui'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
-import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'
+import { SlackChannelPicker, SlackUserPicker } from 'lib/integrations/SlackIntegrationHelpers'
import { urls } from 'scenes/urls'
import type {
@@ -12,6 +13,11 @@ import type {
SignalScoutSlackDestinationApi,
} from 'products/signals/frontend/generated/api.schemas'
+// Mirrors MAX_SCOUT_SLACK_DM_TARGETS on the backend serializer.
+const MAX_DM_RECIPIENTS = 5
+
+type SlackTargetMode = 'channel' | 'dm'
+
interface ScoutSlackDestinationProps {
destination?: SignalScoutSlackDestinationApi | null
disabledReason?: string
@@ -31,13 +37,33 @@ export function ScoutSlackDestination({
: undefined
const selectedIntegration = configuredIntegration ?? (integrations.length === 1 ? integrations[0] : null)
+ const hasChannel = Boolean(destination?.channel)
+ const hasUsers = Boolean(destination?.users?.length)
+ const hasTarget = hasChannel || hasUsers
+
+ // The toggle is view state only: switching it must never write, or an exploratory click would
+ // wipe a live destination. The saved target is replaced only when a new target is picked.
+ const [pendingMode, setPendingMode] = useState<SlackTargetMode | null>(null)
+ const mode: SlackTargetMode = pendingMode ?? (hasUsers ? 'dm' : 'channel')
+
const selectWorkspace = (integrationId: number): void => {
+ // Switching workspace clears the target, so pin the toggle to the mode the user was in.
+ setPendingMode(mode)
onChange({ slack: { integration_id: integrationId, channel: null } })
}
+ const selectMode = (nextMode: SlackTargetMode): void => {
+ setPendingMode(nextMode)
+ }
+
const selectChannel = (channel: string | null): void => {
if (!channel || !selectedIntegration) {
- onChange({})
+ // An empty picker still emits clears (e.g. Backspace in its input), so only a picker
+ // whose own target is saved may clear — otherwise viewing the alternate mode while the
+ // other target is live would wipe that target.
+ if (hasChannel) {
+ onChange({})
+ }
return
}
onChange({
@@ -65,17 +91,38 @@ export function ScoutSlackDestination({
})
}
+ const selectUsers = (users: string[]): void => {
+ if (!selectedIntegration) {
+ return
+ }
+ if (!users.length) {
+ if (!hasUsers) {
+ // Same guard as selectChannel: an empty DM picker's clear must not wipe a saved channel.
+ return
+ }
+ // Removing the last recipient empties the saved destination; without pinning the mode
+ // the toggle would fall back to its channel default and swap the picker mid-edit.
+ setPendingMode('dm')
+ onChange({ slack: { integration_id: selectedIntegration.id, channel: null } })
+ return
+ }
+ onChange({
+ slack: { integration_id: selectedIntegration.id, users: users.slice(0, MAX_DM_RECIPIENTS) },
+ })
+ }
+
const disableSlack = (): void => {
+ setPendingMode(mode)
onChange({})
}
- const hasChannel = Boolean(destination?.channel)
-
return (
<div className="flex flex-col gap-2 border-t border-primary pt-2">
<div className="flex flex-col min-w-0">
<span className="text-xs text-default">Slack destination</span>
- <span className="text-[11.5px] text-muted">Post each scout run's output to a channel</span>
+ <span className="text-[11.5px] text-muted">
+ Post each scout run's output to a channel, or send it as a direct message
+ </span>
</div>
{integrationsLoading && slackIntegrations === undefined ? (
<span className="text-xs text-muted">Loading Slack workspaces…</span>
@@ -99,44 +146,81 @@ export function ScoutSlackDestination({
/>
) : null}
{selectedIntegration ? (
- <div className="flex items-center gap-2">
- <div className="flex-1 min-w-0">
- <SlackChannelPicker
- integration={selectedIntegration}
- value={configuredIntegration ? (destination?.channel ?? undefined) : undefined}
- onChange={selectChannel}
- disabled={disabledReason !== undefined}
- />
+ <>
+ <LemonSegmentedButton
+ size="small"
+ value={mode}
+ onChange={(nextMode) => selectMode(nextMode as SlackTargetMode)}
+ options={[
+ { value: 'channel', label: 'Channel', disabledReason },
+ { value: 'dm', label: 'Direct message', disabledReason },
+ ]}
+ />
+ <div className="flex items-center gap-2">
+ <div className="flex-1 min-w-0">
+ {mode === 'channel' ? (
+ <SlackChannelPicker
+ integration={selectedIntegration}
+ value={
+ configuredIntegration ? (destination?.channel ?? undefined) : undefined
+ }
+ onChange={selectChannel}
+ disabled={disabledReason !== undefined}
+ />
+ ) : (
+ <SlackUserPicker
+ integration={selectedIntegration}
+ values={configuredIntegration ? (destination?.users ?? []) : []}
+ onChange={selectUsers}
+ disabled={disabledReason !== undefined}
+ maxUsers={MAX_DM_RECIPIENTS}
+ />
+ )}
+ </div>
+ {hasTarget ? (
+ <LemonButton
+ size="small"
+ icon={<IconTrash />}
+ onClick={disableSlack}
+ tooltip="Turn off Slack notifications for this scout"
+ disabledReason={disabledReason}
+ aria-label="Turn off Slack notifications"
+ />
+ ) : null}
</div>
- {hasChannel ? (
- <LemonButton
+ </>
+ ) : null}
+ {mode === 'channel' ? (
+ <>
+ <span className="text-[11.5px] text-muted">
+ {hasChannel
+ ? 'PostHog must be in the channel. Invite it with '
+ : hasUsers
+ ? 'Direct messages stay on until you pick a channel to replace them. PostHog must be in the channel. Invite it with '
+ : 'Pick a channel to turn notifications on. PostHog must be in the channel. Invite it with '}
+ <code>/invite @PostHog</code>.
+ </span>
+ {configuredIntegration && hasChannel ? (
+ <LemonSwitch
size="small"
- icon={<IconTrash />}
- onClick={disableSlack}
- tooltip="Turn off Slack notifications for this scout"
+ checked={destination?.thread_reports ?? false}
+ onChange={setThreadReports}
disabledReason={disabledReason}
- aria-label="Turn off Slack notifications"
+ label="Post reports as a thread"
+ tooltip="Post a short lead in the channel and split the rest by the report's headings into replies, so the channel stays readable and a long summary is not cut off."
+ bordered
/>
) : null}
- </div>
- ) : null}
- <span className="text-[11.5px] text-muted">
- {hasChannel
- ? 'PostHog must be in the channel. Invite it with '
- : 'Pick a channel to turn notifications on. PostHog must be in the channel. Invite it with '}
- <code>/invite @PostHog</code>.
- </span>
- {configuredIntegration && hasChannel ? (
- <LemonSwitch
- size="small"
- checked={destination?.thread_reports ?? false}
- onChange={setThreadReports}
- disabledReason={disabledReason}
- label="Post reports as a thread"
- tooltip="Post a short lead in the channel and split the rest by the report's headings into replies, so the channel stays readable and a long summary is not cut off."
- bordered
- />
- ) : null}
+ </>
+ ) : (
+ <span className="text-[11.5px] text-muted">
+ {hasUsers
+ ? `Each person gets their own direct message from the PostHog app (up to ${MAX_DM_RECIPIENTS} people).`
+ : hasChannel
+ ? `The channel stays on until you pick up to ${MAX_DM_RECIPIENTS} people to replace it. Each person gets their own direct message from the PostHog app.`
+ : `Pick up to ${MAX_DM_RECIPIENTS} people to turn notifications on. Each person gets their own direct message from the PostHog app.`}
+ </span>
+ )}
</div>
)}
</div>
diff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yaml
index b30e05de44fd..8cb72ad859f0 100644
--- a/products/signals/mcp/tools.yaml
+++ b/products/signals/mcp/tools.yaml
@@ -441,8 +441,10 @@ tools:
precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to
the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30
minutes apart; set null to return to the rolling interval. You can also configure
- `output_destinations.slack` with a Slack integration and channel. `skill_name` is fixed. Enabling records
- who flipped it on and is activity-logged, since running a scout drives spend.
+ `output_destinations.slack` with a Slack integration plus either a `channel` to post into or `users` to DM
+ directly (handy for personal scouts) — find channel ids with integrations-channels-retrieve and member ids
+ with integrations-users-retrieve. `skill_name` is fixed. Enabling records who flipped it on and is
+ activity-logged, since running a scout drives spend.
scout-create:
operation: signals_scout_create
enabled: true
@@ -459,8 +461,9 @@ tools:
markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps,
and report criteria there. The server always grants the report-channel tools. Optional `files` bundle
reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and
- typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied
- config fields. Reusing the name for a different definition returns a conflict.
+ typed output destinations such as Slack (a channel to post into, or users to DM directly). Repeating the
+ same definition is safe and applies any supplied config fields. Reusing the name for a different definition
+ returns a conflict.
confirmed_action:
message: >
About to create scout '{name}', a persistent automation that can run unattended on its configured
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 456d93a2c63a..ef5e97b181eb 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5794,6 +5794,20 @@
"readOnlyHint": true
}
},
+ "integrations-users-retrieve": {
+ "description": "List the Slack workspace members a Slack integration can send direct messages to. Slack-only — non-Slack integration ids return an error (400 if the integration is otherwise visible, 404 if it isn't). Returns each member's id (e.g. U0123ABC), name (handle without the leading @), and display_name; bots, deactivated accounts, and Slackbot are excluded. Supports `search` (fuzzy match on display name and handle, plus id-contains), `limit`, `offset`, and a `user_id` query parameter for a direct lookup. Results are cached for 1 hour (no force-refresh exposed via MCP). Use this to find member ids when configuring a scout's Slack DM destination — pass them as `output_destinations.slack.users` entries (`member_id|@display-name`) via scout-config-update or scout-create. Requires the Slack integration's id; use integrations-list (filter by kind=slack) to find it.",
+ "category": "Integrations",
+ "feature": "integrations",
+ "summary": "List integration Slack members",
+ "title": "List integration Slack members",
+ "required_scopes": ["integration:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"llma-clustering-config-get": {
"description": "Retrieve the team's clustering event-filter configuration for automated AI observability clustering. New scheduled clustering should usually use clustering jobs, but this remains useful when auditing existing automation.",
"category": "AI observability",
@@ -9072,7 +9086,7 @@
}
},
"scout-config-update": {
- "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration and channel. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
+ "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration plus either a `channel` to post into or `users` to DM directly (handy for personal scouts) — find channel ids with integrations-channels-retrieve and member ids with integrations-users-retrieve. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
"category": "Signals",
"feature": "signals",
"summary": "Update a scout config",
@@ -9086,7 +9100,7 @@
}
},
"scout-create-execute": {
- "description": "Step 2 of 2 for create scout. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
+ "description": "Step 2 of 2 for create scout. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack (a channel to post into, or users to DM directly). Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
"category": "Signals",
"feature": "signals",
"summary": "Create a scout (execute)",
@@ -9100,7 +9114,7 @@
}
},
"scout-create-prepare": {
- "description": "Step 1 of 2 for create scout. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
+ "description": "Step 1 of 2 for create scout. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack (a channel to post into, or users to DM directly). Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
"category": "Signals",
"feature": "signals",
"summary": "Create a scout (prepare)",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index bd403f7e5ae6..e9bdbc82d42a 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6005,6 +6005,20 @@
"readOnlyHint": true
}
},
+ "integrations-users-retrieve": {
+ "description": "List the Slack workspace members a Slack integration can send direct messages to. Slack-only — non-Slack integration ids return an error (400 if the integration is otherwise visible, 404 if it isn't). Returns each member's id (e.g. U0123ABC), name (handle without the leading @), and display_name; bots, deactivated accounts, and Slackbot are excluded. Supports `search` (fuzzy match on display name and handle, plus id-contains), `limit`, `offset`, and a `user_id` query parameter for a direct lookup. Results are cached for 1 hour (no force-refresh exposed via MCP). Use this to find member ids when configuring a scout's Slack DM destination — pass them as `output_destinations.slack.users` entries (`member_id|@display-name`) via scout-config-update or scout-create. Requires the Slack integration's id; use integrations-list (filter by kind=slack) to find it.",
+ "category": "Integrations",
+ "feature": "integrations",
+ "summary": "List integration Slack members",
+ "title": "List integration Slack members",
+ "required_scopes": ["integration:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ }
+ },
"llma-clustering-config-get": {
"description": "Retrieve the team's clustering event-filter configuration for automated AI observability clustering. New scheduled clustering should usually use clustering jobs, but this remains useful when auditing existing automation.",
"category": "AI observability",
@@ -9627,7 +9641,7 @@
}
},
"scout-config-update": {
- "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration and channel. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
+ "description": "Tune one scout by its config `id`: change its schedule (rolling `run_interval_minutes`, 30–43200, or a five-field cron `run_cron_schedule` like '30 9 * * *', '0 9,17 * * *', or '0 9 * * 1-5' that takes precedence when set), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). Cron schedules use the project timezone automatically and occurrences must be at least 30 minutes apart; set null to return to the rolling interval. You can also configure `output_destinations.slack` with a Slack integration plus either a `channel` to post into or `users` to DM directly (handy for personal scouts) — find channel ids with integrations-channels-retrieve and member ids with integrations-users-retrieve. `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.",
"category": "Signals",
"feature": "signals",
"summary": "Update a scout config",
@@ -9641,7 +9655,7 @@
}
},
"scout-create-execute": {
- "description": "Step 2 of 2 for create scout. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
+ "description": "Step 2 of 2 for create scout. Verifies the confirmation_hash from -prepare and the literal \"confirm\" string typed by the user, then performs the action. ONLY call this after the user has explicitly typed \"confirm\" in chat. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack (a channel to post into, or users to DM directly). Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
"category": "Signals",
"feature": "signals",
"summary": "Create a scout (execute)",
@@ -9655,7 +9669,7 @@
}
},
"scout-create-prepare": {
- "description": "Step 1 of 2 for create scout. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack. Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
+ "description": "Step 1 of 2 for create scout. Validates the arguments and returns a signed confirmation_hash plus a message to surface to the user. The user must reply with the literal word \"confirm\" before you call the matching -execute tool with the hash. Original action: Create a custom `signals-scout-*` skill and its runnable config in one atomic call. Pass the complete markdown prompt in `body`; include project-specific event or signal names, thresholds, investigation steps, and report criteria there. The server always grants the report-channel tools. Optional `files` bundle reference material, while `config` controls the rolling or cron schedule, enabled and dry-run posture, and typed output destinations such as Slack (a channel to post into, or users to DM directly). Repeating the same definition is safe and applies any supplied config fields. Reusing the name for a different definition returns a conflict.",
"category": "Signals",
"feature": "signals",
"summary": "Create a scout (prepare)",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1232e034d5d2..50936aee77f3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -65548,11 +65548,20 @@ export namespace Schemas {
*/
integration_id: number;
/**
- * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set.
+ * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set.
* @maxLength 255
* @nullable
*/
channel?: string | null;
+ /**
+ * Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.
+ * @minItems 1
+ * @maxItems 5
+ * @nullable
+ * @items.maxLength 255
+ * @items.pattern ^[UW][A-Z0-9]{4,}\s*(\|.*)?$
+ */
+ users?: string[] | null;
/** When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post. */
thread_reports?: boolean;
}
@@ -77230,6 +77239,27 @@ export namespace Schemas {
runs: SlackThreadContextRun[];
}
+ export interface SlackUser {
+ /** Slack member ID (e.g. U0123ABC) — post to it to open a direct message. */
+ id: string;
+ /** Slack username (handle) without the leading '@'. */
+ name: string;
+ /** Name to show in pickers: the member's display name, falling back to their real name or handle. */
+ display_name: string;
+ }
+
+ export interface SlackUsersResponse {
+ /** Human Slack workspace members the PostHog Slack app can DM. */
+ users: SlackUser[];
+ /**
+ * ISO 8601 timestamp of the last full Slack API refresh (only set on full lists, not single-member lookups).
+ * @nullable
+ */
+ lastRefreshedAt?: string | null;
+ /** Whether more members match the current search beyond this page. */
+ has_more?: boolean;
+ }
+
/**
* * `Snowflake` - Snowflake
*/
@@ -95103,6 +95133,32 @@ export namespace Schemas {
search?: string;
};
+ export type IntegrationsUsersRetrieveParams = {
+ /**
+ * Bypass the 1 hour member cache. Honored only for browser session callers; API key, OAuth, and MCP callers always read through the cache.
+ */
+ force_refresh?: boolean;
+ /**
+ * Maximum number of members to return per request (max 200).
+ * @minimum 1
+ * @maximum 200
+ */
+ limit?: number;
+ /**
+ * Number of members to skip before returning results.
+ * @minimum 0
+ */
+ offset?: number;
+ /**
+ * Optional case-insensitive member name or ID search query.
+ */
+ search?: string;
+ /**
+ * Look up one member directly by Slack member ID (e.g. U0123ABC). When set, `search`, `limit`, and `offset` are ignored and the response holds at most that member.
+ */
+ user_id?: string;
+ };
+
export type JsSnippetResolveRetrieve200 = { [key: string]: unknown };
export type JsSnippetVersionRetrieve200 = { [key: string]: unknown };
diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.ts
index a74647a39153..48021f5f43ac 100644
--- a/services/mcp/src/generated/integrations/api.ts
+++ b/services/mcp/src/generated/integrations/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 8 enabled ops
+ * PostHog API - MCP 9 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -181,6 +181,55 @@ export const IntegrationsLinearTeamsRetrieveParams = /* @__PURE__ */ zod.object(
),
})
+export const IntegrationsUsersRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.number().describe('A unique integer value identifying this integration.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const integrationsUsersRetrieveQueryForceRefreshDefault = false
+export const integrationsUsersRetrieveQueryLimitDefault = 50
+export const integrationsUsersRetrieveQueryLimitMax = 200
+
+export const integrationsUsersRetrieveQueryOffsetDefault = 0
+export const integrationsUsersRetrieveQueryOffsetMin = 0
+
+export const integrationsUsersRetrieveQuerySearchDefault = ``
+export const integrationsUsersRetrieveQueryUserIdDefault = ``
+
+export const IntegrationsUsersRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ force_refresh: zod
+ .boolean()
+ .default(integrationsUsersRetrieveQueryForceRefreshDefault)
+ .describe(
+ 'Bypass the 1 hour member cache. Honored only for browser session callers; API key, OAuth, and MCP callers always read through the cache.'
+ ),
+ limit: zod
+ .number()
+ .min(1)
+ .max(integrationsUsersRetrieveQueryLimitMax)
+ .default(integrationsUsersRetrieveQueryLimitDefault)
+ .describe('Maximum number of members to return per request (max 200).'),
+ offset: zod
+ .number()
+ .min(integrationsUsersRetrieveQueryOffsetMin)
+ .default(integrationsUsersRetrieveQueryOffsetDefault)
+ .describe('Number of members to skip before returning results.'),
+ search: zod
+ .string()
+ .default(integrationsUsersRetrieveQuerySearchDefault)
+ .describe('Optional case-insensitive member name or ID search query.'),
+ user_id: zod
+ .string()
+ .default(integrationsUsersRetrieveQueryUserIdDefault)
+ .describe(
+ 'Look up one member directly by Slack member ID (e.g. U0123ABC). When set, `search`, `limit`, and `offset` are ignored and the response holds at most that member.'
+ ),
+})
+
/**
* Replay an API request against the connected PostHog project. The server injects the connection's token; the response is passed through.
* @summary Forward a request through a PostHog connection
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index f09e5e363fb3..e7a76b420e7a 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -436,6 +436,13 @@ export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200
export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax = 255
+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemMax = 255
+
+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemRegExp = new RegExp(
+ '^[UW][A-Z0-9]{4,}\\s\*(\\|.\*)?$'
+)
+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersMax = 5
+
export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault = false
export const signalsScoutCreateBodyConfigOneRunCronScheduleMax = 100
@@ -515,7 +522,24 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod
.max(signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax)
.nullish()
.describe(
- "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
+ ),
+ users: zod
+ .array(
+ zod
+ .string()
+ .max(
+ signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemMax
+ )
+ .regex(
+ signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersItemRegExp
+ )
+ )
+ .min(1)
+ .max(signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneUsersMax)
+ .nullish()
+ .describe(
+ 'Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.'
),
thread_reports: zod
.boolean()
@@ -645,6 +669,13 @@ export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200
export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax = 255
+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersItemMax = 255
+
+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersItemRegExp = new RegExp(
+ '^[UW][A-Z0-9]{4,}\\s\*(\\|.\*)?$'
+)
+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersMax = 5
+
export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneThreadReportsDefault = false
export const signalsScoutConfigCreateBodyRunCronScheduleMax = 100
@@ -687,7 +718,20 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod
.max(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax)
.nullish()
.describe(
- "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
+ ),
+ users: zod
+ .array(
+ zod
+ .string()
+ .max(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersItemMax)
+ .regex(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersItemRegExp)
+ )
+ .min(1)
+ .max(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneUsersMax)
+ .nullish()
+ .describe(
+ 'Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.'
),
thread_reports: zod
.boolean()
@@ -798,6 +842,13 @@ export const signalsScoutConfigUpdateBodyRunCronScheduleMax = 100
export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax = 255
+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersItemMax = 255
+
+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersItemRegExp = new RegExp(
+ '^[UW][A-Z0-9]{4,}\\s\*(\\|.\*)?$'
+)
+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersMax = 5
+
export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneThreadReportsDefault = false
export const signalsScoutConfigUpdateBodyModelMax = 200
@@ -848,7 +899,20 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod
.max(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax)
.nullish()
.describe(
- "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
+ ),
+ users: zod
+ .array(
+ zod
+ .string()
+ .max(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersItemMax)
+ .regex(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersItemRegExp)
+ )
+ .min(1)
+ .max(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneUsersMax)
+ .nullish()
+ .describe(
+ 'Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.'
),
thread_reports: zod
.boolean()
diff --git a/services/mcp/src/tools/generated/integrations.ts b/services/mcp/src/tools/generated/integrations.ts
index 595bf34a8708..6ad5c47ce239 100644
--- a/services/mcp/src/tools/generated/integrations.ts
+++ b/services/mcp/src/tools/generated/integrations.ts
@@ -12,6 +12,8 @@ import {
IntegrationsLinearTeamsRetrieveParams,
IntegrationsListQueryParams,
IntegrationsRetrieveParams,
+ IntegrationsUsersRetrieveParams,
+ IntegrationsUsersRetrieveQueryParams,
PosthogConnectionsForwardCreateBody,
PosthogConnectionsForwardCreateParams,
} from '@/generated/integrations/api'
@@ -171,6 +173,30 @@ const integrationsList = (): ToolBase<
},
})
+const IntegrationsUsersRetrieveSchema = IntegrationsUsersRetrieveParams.omit({ project_id: true }).extend(
+ IntegrationsUsersRetrieveQueryParams.shape
+)
+
+const integrationsUsersRetrieve = (): ToolBase<typeof IntegrationsUsersRetrieveSchema, Schemas.SlackUsersResponse> => ({
+ name: 'integrations-users-retrieve',
+ schema: IntegrationsUsersRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof IntegrationsUsersRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.SlackUsersResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/integrations/${encodeURIComponent(String(params.id))}/users/`,
+ query: {
+ force_refresh: params.force_refresh,
+ limit: params.limit,
+ offset: params.offset,
+ search: params.search,
+ user_id: params.user_id,
+ },
+ })
+ return result
+ },
+})
+
const PosthogConnectionForwardSchema = PosthogConnectionsForwardCreateParams.omit({ project_id: true }).extend(
PosthogConnectionsForwardCreateBody.shape
)
@@ -213,5 +239,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'integrations-jira-projects-retrieve': integrationsJiraProjectsRetrieve,
'integrations-linear-teams-retrieve': integrationsLinearTeamsRetrieve,
'integrations-list': integrationsList,
+ 'integrations-users-retrieve': integrationsUsersRetrieve,
'posthog-connection-forward': posthogConnectionForward,
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-users-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-users-retrieve.json
new file mode 100644
index 000000000000..283b21411a2b
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-users-retrieve.json
@@ -0,0 +1,39 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "force_refresh": {
+ "default": false,
+ "description": "Bypass the 1 hour member cache. Honored only for browser session callers; API key, OAuth, and MCP callers always read through the cache.",
+ "type": "boolean"
+ },
+ "id": {
+ "description": "A unique integer value identifying this integration.",
+ "type": "number"
+ },
+ "limit": {
+ "default": 50,
+ "description": "Maximum number of members to return per request (max 200).",
+ "maximum": 200,
+ "minimum": 1,
+ "type": "number"
+ },
+ "offset": {
+ "default": 0,
+ "description": "Number of members to skip before returning results.",
+ "minimum": 0,
+ "type": "number"
+ },
+ "search": {
+ "default": "",
+ "description": "Optional case-insensitive member name or ID search query.",
+ "type": "string"
+ },
+ "user_id": {
+ "default": "",
+ "description": "Look up one member directly by Slack member ID (e.g. U0123ABC). When set, `search`, `limit`, and `offset` are ignored and the response holds at most that member.",
+ "type": "string"
+ }
+ },
+ "required": ["id"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
index a70bea011e11..632cc74b4ab7 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json
@@ -56,7 +56,7 @@
"type": "null"
}
],
- "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
},
"integration_id": {
"description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
@@ -67,6 +67,24 @@
"default": false,
"description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",
"type": "boolean"
+ },
+ "users": {
+ "anyOf": [
+ {
+ "items": {
+ "maxLength": 255,
+ "pattern": "^[UW][A-Z0-9]{4,}\\s*(\\|.*)?$",
+ "type": "string"
+ },
+ "maxItems": 5,
+ "minItems": 1,
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel."
}
},
"required": ["integration_id"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
index c1df82cc3885..d98893980ff6 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json
@@ -59,7 +59,7 @@
"type": "null"
}
],
- "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
},
"integration_id": {
"description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
@@ -70,6 +70,24 @@
"default": false,
"description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",
"type": "boolean"
+ },
+ "users": {
+ "anyOf": [
+ {
+ "items": {
+ "maxLength": 255,
+ "pattern": "^[UW][A-Z0-9]{4,}\\s*(\\|.*)?$",
+ "type": "string"
+ },
+ "maxItems": 5,
+ "minItems": 1,
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel."
}
},
"required": ["integration_id"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json
index 714c680a4f9e..3a39dafbfec8 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json
@@ -63,7 +63,7 @@
"type": "null"
}
],
- "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
},
"integration_id": {
"description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
@@ -74,6 +74,24 @@
"default": false,
"description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",
"type": "boolean"
+ },
+ "users": {
+ "anyOf": [
+ {
+ "items": {
+ "maxLength": 255,
+ "pattern": "^[UW][A-Z0-9]{4,}\\s*(\\|.*)?$",
+ "type": "string"
+ },
+ "maxItems": 5,
+ "minItems": 1,
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel."
}
},
"required": ["integration_id"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
index a70bea011e11..632cc74b4ab7 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json
@@ -56,7 +56,7 @@
"type": "null"
}
],
- "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
},
"integration_id": {
"description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
@@ -67,6 +67,24 @@
"default": false,
"description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",
"type": "boolean"
+ },
+ "users": {
+ "anyOf": [
+ {
+ "items": {
+ "maxLength": 255,
+ "pattern": "^[UW][A-Z0-9]{4,}\\s*(\\|.*)?$",
+ "type": "string"
+ },
+ "maxItems": 5,
+ "minItems": 1,
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel."
}
},
"required": ["integration_id"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
index c1df82cc3885..d98893980ff6 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json
@@ -59,7 +59,7 @@
"type": "null"
}
],
- "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."
+ "description": "Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set."
},
"integration_id": {
"description": "ID of the Slack integration whose bot posts this scout's findings and reports.",
@@ -70,6 +70,24 @@
"default": false,
"description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",
"type": "boolean"
+ },
+ "users": {
+ "anyOf": [
+ {
+ "items": {
+ "maxLength": 255,
+ "pattern": "^[UW][A-Z0-9]{4,}\\s*(\\|.*)?$",
+ "type": "string"
+ },
+ "maxItems": 5,
+ "minItems": 1,
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel."
}
},
"required": ["integration_id"],