:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(activity-log): tag rows written by a scout run (#100934)
posthog[bot]7407d176645f
diff --git a/docs/published/handbook/engineering/ai/sandboxed-agents.md b/docs/published/handbook/engineering/ai/sandboxed-agents.mdindex 8239a043fc3b..2acc175f48d9 100644--- a/docs/published/handbook/engineering/ai/sandboxed-agents.md+++ b/docs/published/handbook/engineering/ai/sandboxed-agents.md@@ -171,6 +171,16 @@ See `posthog/temporal/oauth.py` for the full list.> **Principle of least privilege**: default to `"read_only"` unless your agent genuinely needs to create or modify resources.> This limits blast radius if the agent misbehaves.+### Activity attribution++A sandboxed agent authenticates as a person, so the activity log names that person as the actor.+The client tag on the row is what says an agent made the change.++A Signals scout run writes the tag `scout:<skill_name>`, which the activity log and the audit log render as `via scout <skill_name>`.+The tag is derived from the task binding on the run's own token, not from the `x-posthog-client` request header.+The `scout:` prefix is reserved for that path, and a header value claiming it is dropped, so an agent cannot claim to be a scout it is not.+Every other client keeps the self-reported header value.+## PostHog MCP serverThe sandbox comes with access to the PostHog MCP server,diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 882865470042..332c77a9b8fe 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -80,6 +80,18 @@ snapshots:hash: v1.k794b7964.6c5cd88f5aa3d41c98e0eeeff971b922bbccf36f60403a84b580a61f9aa29afb.rEnc5arM9Mv69K2iPjoLgoW7dy7xruBpLLXaYMZlyb0components-action-step-description--summary-with-tooltip--light:hash: v1.k794b7964.3bce9d23f964dddb8aa880ac92507478730c02653598580c051d620f99eaaf65.HeFECSKIWtxNuvm1I3nU8WsJfXcgS2PMRcDfMf9eOZU+ components-activityclienttag--mcp--dark:+ hash: v1.k794b7964.d496faf4dc9010b9cd91b18f4c5eadc0002ab8f34c040661a6f6832e3df85918.YT1F9GQDBg005k0t-pxqxJzcFo_2S3vjHMEAH3yHO3w+ components-activityclienttag--mcp--light:+ hash: v1.k794b7964.4d0a6238b50eacc49ab9f63018544c145f492897ef62e2c562d168866ec8de21.ZVCV-mvozxQ79TtUyFoeWZmqGTQyjNuykP7OEbNjya0+ components-activityclienttag--scout--dark:+ hash: v1.k794b7964.e40563d181f3a781c4442e0999a6b192225d9bb5f4fd49a392091f432c32db4b.LJy0ij53eoAedhB73UDyoSDq-Bj65T1VJrgJPO6xQWU+ components-activityclienttag--scout--light:+ hash: v1.k794b7964.a3977b2ed40e208ded39015273e1d9112881140e613a922aba112594d113f68c.B7x5QlJdkHFTHN4mbZHvKO-vr9IzRWZIu7--Kf3ZA7A+ components-activityclienttag--sdk--dark:+ hash: v1.k794b7964.24d72c6225b22c25d415eea21df5dfb4836c2322c5c2bfcf34aff3d8f7b99f33.5jeGXKRvqCby_ZRnJAiqIcdnghfJ_m7Qm-7dprW0lZs+ components-activityclienttag--sdk--light:+ hash: v1.k794b7964.9c2107c79242cdf242289e892425279ec458cdd52bd7db647511edc9e201ef82.0RLoWz3N9SJu232VDLYehttumTHmbRhxGd3zOqY311Icomponents-activitylog--data-management-activity--dark:hash: v1.k794b7964.c0fd7565eccb2a1b348b4e994751489c4d2922648e7bd2aafed432a72e979e44.D18rmt5xbd-90izaBhP2OrO9uNIGf_4PKa_f2Mogmykcomponents-activitylog--data-management-activity--light:diff --git a/frontend/src/lib/components/ActivityLog/ActivityClientTag.stories.tsx b/frontend/src/lib/components/ActivityLog/ActivityClientTag.stories.tsxnew file mode 100644index 000000000000..d4311a7478aa--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/ActivityClientTag.stories.tsx@@ -0,0 +1,23 @@+import type { Meta, StoryObj } from '@storybook/react'++import { ActivityClientTag, ActivityClientTagProps } from './ActivityClientTag'++type Story = StoryObj<ActivityClientTagProps>+const meta: Meta<ActivityClientTagProps> = {+ title: 'Components/ActivityClientTag',+ component: ActivityClientTag,+ parameters: {},+}+export default meta++export const Mcp: Story = {+ args: { client: 'mcp' },+}++export const Scout: Story = {+ args: { client: 'scout:self-driving-dwh' },+}++export const Sdk: Story = {+ args: { client: 'posthog-js/1.234.0' },+}diff --git a/frontend/src/lib/components/ActivityLog/ActivityClientTag.tsx b/frontend/src/lib/components/ActivityLog/ActivityClientTag.tsxnew file mode 100644index 000000000000..fef91acee365--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/ActivityClientTag.tsx@@ -0,0 +1,20 @@+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import { activityClientLabel, isScoutClient } from 'lib/components/ActivityLog/activityClientLabel'++const SELF_REPORTED_TOOLTIP = 'Self-reported by the API client in the x-posthog-client request header'+const SCOUT_TOOLTIP = 'PostHog recognized this scout from the token its run used, so it is not self-reported'++export interface ActivityClientTagProps {+ client: string+}++export function ActivityClientTag({ client }: ActivityClientTagProps): JSX.Element {+ return (+ <Tooltip title={isScoutClient(client) ? SCOUT_TOOLTIP : SELF_REPORTED_TOOLTIP}>+ <LemonTag size="small" type="muted">+ via {activityClientLabel(client)}+ </LemonTag>+ </Tooltip>+ )+}diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsxindex eb338de51259..2be2cddfedb1 100644--- a/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsx+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.test.tsx@@ -32,4 +32,25 @@ describe('ActivityLogRow', () => {expect(screen.getByText('Release conditions').closest('[role="tab"]')).toHaveAttribute('aria-selected', 'true')expect(screen.getByText('the release conditions')).toBeInTheDocument()})++ test.each([+ ['mcp', 'via MCP'],+ ['scout:self-driving-dwh', 'via scout self-driving-dwh'],+ ['posthog-js/1.234.0', 'via posthog-js/1.234.0'],+ ])('names %s as the client behind the change', (client, expected) => {+ const logItem: HumanizedActivityLogItem = {+ name: 'peter',+ description: <>changed the rollout</>,+ created_at: dayjs('2022-02-05T16:28:39.594Z'),+ client,+ }++ render(+ <Provider>+ <ActivityLogRow logItem={logItem} />+ </Provider>+ )++ expect(screen.getByText(expected)).toBeInTheDocument()+ })})diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.tsxindex b3d90426a900..a0c982f9abdf 100644--- a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.tsx@@ -7,8 +7,9 @@ import { router } from 'kea-router'import { Suspense, useEffect, useRef, useState } from 'react'import { IconCollapse, IconExpand } from '@posthog/icons'-import { LemonButton, LemonDivider, LemonTabs, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonDivider, LemonTabs, Spinner, Tooltip } from '@posthog/lemon-ui'+import { ActivityClientTag } from 'lib/components/ActivityLog/ActivityClientTag'import {ACTIVITY_SEARCH_PARAM,ActivityLogLogicProps,@@ -208,13 +209,7 @@ export const ActivityLogRow = ({<AgentAttribution logItem={logItem} /><div className="text-secondary flex items-center gap-1.5"><TZLabel time={logItem.created_at} />- {logItem.client && (- <Tooltip title="Self-reported by the API client in the x-posthog-client request header">- <LemonTag size="small" type="muted">- via {logItem.client === 'mcp' ? 'MCP' : logItem.client}- </LemonTag>- </Tooltip>- )}+ {logItem.client && <ActivityClientTag client={logItem.client} />}</div></div>{logItem.id && (diff --git a/frontend/src/lib/components/ActivityLog/activityClientLabel.ts b/frontend/src/lib/components/ActivityLog/activityClientLabel.tsnew file mode 100644index 000000000000..fafb947f914e--- /dev/null+++ b/frontend/src/lib/components/ActivityLog/activityClientLabel.ts@@ -0,0 +1,18 @@+/**+ * Reserved for the backend, which derives it from the authenticated scout run. The API drops+ * an `x-posthog-client` header that claims this prefix, so a stored tag that carries it came+ * from the server.+ */+export const SCOUT_CLIENT_PREFIX = 'scout:'++export function isScoutClient(client: string): boolean {+ return client.startsWith(SCOUT_CLIENT_PREFIX)+}++/** How a stored `client` value reads to a person. The stored value stays the filter key. */+export function activityClientLabel(client: string): string {+ if (isScoutClient(client)) {+ return `scout ${client.slice(SCOUT_CLIENT_PREFIX.length)}`+ }+ return client === 'mcp' ? 'MCP' : client+}diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsxindex 77ff457bba97..6a63c86de896 100644--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx@@ -54,7 +54,7 @@ export type ActivityLogItem = {is_system?: boolean/** Whether a PostHog team member was impersonating the user when this activity was logged. */was_impersonated?: boolean- /** SDK or integration that triggered this action (from x-posthog-client header). */+ /** SDK, integration, or scout that triggered this action. Self-reported through the x-posthog-client header, except for a scout, which the server names. */client?: string | null/** Client IP address captured at request time. Null for non-HTTP activity (system, background jobs). */ip_address?: string | null@@ -86,7 +86,7 @@ export type HumanizedActivityLogItem = {name?: stringisSystem?: booleanwasImpersonated?: boolean- /** SDK or integration that triggered this action (from x-posthog-client header). */+ /** SDK, integration, or scout that triggered this action. Self-reported through the x-posthog-client header, except for a scout, which the server names. */client?: string | nulldescription: DescriptionextendedDescription?: ExtendedDescription // e.g. an insight's filters summarydiff --git a/frontend/src/scenes/audit-logs/AuditLogTable.tsx b/frontend/src/scenes/audit-logs/AuditLogTable.tsxindex 8fb52eff3949..ff5bcbc21aad 100644--- a/frontend/src/scenes/audit-logs/AuditLogTable.tsx+++ b/frontend/src/scenes/audit-logs/AuditLogTable.tsx@@ -1,7 +1,8 @@import { useState } from 'react'-import { LemonTag, LemonTabs, Tooltip } from '@posthog/lemon-ui'+import { LemonTabs } from '@posthog/lemon-ui'+import { ActivityClientTag } from 'lib/components/ActivityLog/ActivityClientTag'import { AGENT_INTENT_TOOLTIP } from 'lib/components/ActivityLog/AgentAttribution'import { HumanizedActivityLogItem, humanizeActivity, humanizeScope } from 'lib/components/ActivityLog/humanizeActivity'import { parseAgentAttribution } from 'lib/components/ActivityLog/parseAgentAttribution'@@ -11,6 +12,7 @@ import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'import { Link } from 'lib/lemon-ui/Link'import { PaginationManual } from 'lib/lemon-ui/PaginationControl'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { Tooltip } from 'lib/lemon-ui/Tooltip'import { urls } from 'scenes/urls'export interface AuditLogTableProps {@@ -51,13 +53,7 @@ const baseColumns: LemonTableColumns<HumanizedActivityLogItem> = [type={logItem.isSystem ? 'system' : 'person'}size="md"/>- {logItem.unprocessed?.client === 'mcp' && (- <Tooltip title="This action was performed via the MCP (Model Context Protocol) integration">- <LemonTag type="muted" size="small">- mcp- </LemonTag>- </Tooltip>- )}+ {logItem.unprocessed?.client && <ActivityClientTag client={logItem.unprocessed.client} />}</div>),width: '20%',diff --git a/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx b/frontend/src/scenes/audit-logs/BasicFiltersTab.tsxindex e372ae8b7e74..906f147a6695 100644--- a/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx+++ b/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx@@ -3,6 +3,7 @@ import { useActions, useValues } from 'kea'import { IconCollapse, IconExpand, IconInfo } from '@posthog/icons'import { LemonBadge, LemonButton, LemonSelect, Tooltip } from '@posthog/lemon-ui'+import { activityClientLabel } from 'lib/components/ActivityLog/activityClientLabel'import { humanizeActivity, humanizeScope } from 'lib/components/ActivityLog/humanizeActivity'import { AnimatedCollapsible } from 'lib/components/AnimatedCollapsible'import { DateFilter } from 'lib/components/DateFilter/DateFilter'@@ -244,7 +245,7 @@ export const BasicFiltersTab = (): JSX.Element => {<div className="flex flex-col gap-1"><div className="flex items-center gap-1 mb-1"><label className="block text-sm font-medium">Client</label>- <Tooltip title="The SDK or integration that triggered the action (e.g. MCP).">+ <Tooltip title="The SDK, integration, or agent that made the change, such as MCP or a scout."><IconInfo className="w-4 h-4 text-muted-alt cursor-help" /></Tooltip></div>@@ -257,7 +258,7 @@ export const BasicFiltersTab = (): JSX.Element => {options={availableFilters?.static_filters?.clients?.map((c: any) => ({key: c.value,- label: c.value,+ label: activityClientLabel(c.value),})) || []}loading={availableFiltersLoading}diff --git a/posthog/api/advanced_activity_logs/ocsf.py b/posthog/api/advanced_activity_logs/ocsf.pyindex acef512342c2..4ec10690b2cd 100644--- a/posthog/api/advanced_activity_logs/ocsf.py+++ b/posthog/api/advanced_activity_logs/ocsf.py@@ -138,7 +138,8 @@ class ActivityLogOCSFSerializer(serializers.ModelSerializer):}if instance.client:# `app_name` is "the client application or service that initiated the activity", which is- # what the x-posthog-client header records.+ # what the client tag holds: either the self-reported x-posthog-client header, or the+ # scout the server named from the authenticated run.actor["app_name"] = instance.clientif actor:event["actor"] = actordiff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.pyindex 2b8e2cf7f600..ca862bc12af9 100644--- a/posthog/api/advanced_activity_logs/viewset.py+++ b/posthog/api/advanced_activity_logs/viewset.py@@ -404,7 +404,7 @@ class AdvancedActivityLogFiltersSerializer(serializers.Serializer):child=serializers.CharField(),required=False,default=[],- help_text="Filter by API clients that generated the activity (from x-posthog-client header).",+ help_text="Filter by API clients that generated the activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run).",)ip_addresses = JSONTolerantListField(child=serializers.CharField(validators=[_validate_ip_or_wildcard]),@@ -543,7 +543,7 @@ class StaticFiltersSerializer(serializers.Serializer):activities = serializers.ListField(child=serializers.DictField(), help_text="Available activity types.")clients = serializers.ListField(child=serializers.DictField(),- help_text="API clients that have generated activity (from x-posthog-client header).",+ help_text="API clients that have generated activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run).",)diff --git a/posthog/auth.py b/posthog/auth.pyindex 89f39514aaf5..c72763df5db6 100644--- a/posthog/auth.py+++ b/posthog/auth.py@@ -68,6 +68,7 @@ from posthog.synthetic_user import SyntheticUserfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.exports.backend.facade.auth import get_export_renderer_asset_context+from products.signals.backend.facade.activity_client import resolve_scout_client_tagclass WebAuthnAuthenticationResponse(TypedDict):@@ -983,9 +984,34 @@ class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):if access_token.impersonated_by_id is not None:activity_storage.set_was_impersonated(True)_record_agent_attribution(request, access_token)+ self._set_scout_activity_client(access_token)return user, None+ def _set_scout_activity_client(self, access_token: OAuthAccessToken) -> None:+ """Name the scout behind a sandbox token's writes, in place of the self-reported client.++ A scout acts as the person who owns its config, so the acting user alone cannot tell a+ scout's edit from that person's own MCP edit. The task binding on the token is written+ server-side at mint time, so it overrides the caller-settable `x-posthog-client` header+ that `ActivityLoggingMiddleware` read earlier in the request.++ The scout is looked up when an activity row first needs it, not here, because most+ requests a sandbox token makes are reads that write no row.+ """+ if access_token.sandbox_task_id is None:+ return+ # Sandbox tokens are minted against exactly one team. Anything else cannot say which+ # team's runs to look in, and attribution must not guess.+ scoped_teams = access_token.scoped_teams or []+ if len(scoped_teams) != 1:+ return+ sandbox_task_id = access_token.sandbox_task_id+ team_id = scoped_teams[0]+ activity_storage.set_client_resolver(+ lambda: resolve_scout_client_tag(sandbox_task_id=sandbox_task_id, team_id=team_id)+ )+def _extract_token(self, request: Union[HttpRequest, Request]) -> Optional[str]:if "authorization" in request.headers:authorization_match = re.match(rf"^{self.keyword}\s+(\S.+)$", request.headers["authorization"])diff --git a/posthog/middleware.py b/posthog/middleware.pyindex efe38ba4ae98..86cf84f619bb 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -48,11 +48,7 @@ from posthog.helpers.impersonation import get_original_user_from_sessionfrom posthog.helpers.sso import sso_failure_redirect_urlfrom posthog.helpers.user_devices import set_known_device_cookiefrom posthog.models import Organization, Team, User-from posthog.models.activity_logging.utils import (- ACTIVITY_LOG_CLIENT_HEADER,- ACTIVITY_LOG_CLIENT_MAX_LENGTH,- activity_storage,-)+from posthog.models.activity_logging.utils import ACTIVITY_LOG_CLIENT_HEADER, activity_storage, client_from_headerfrom posthog.models.utils import generate_random_tokenfrom posthog.ph_client import PH_US_API_KEY, PH_US_HOSTfrom posthog.settings import PROJECT_SWITCHING_TOKEN_ALLOWLIST, SITE_URL@@ -1123,7 +1119,7 @@ class ActivityLoggingMiddleware:client_header = request.headers.get(ACTIVITY_LOG_CLIENT_HEADER)if client_header:- activity_storage.set_client(client_header[:ACTIVITY_LOG_CLIENT_MAX_LENGTH])+ activity_storage.set_client(client_from_header(client_header))activity_storage.set_ip_address(get_ip_address(request) or None)diff --git a/posthog/migrations/1367_widen_activitylog_client.py b/posthog/migrations/1367_widen_activitylog_client.pynew file mode 100644index 000000000000..f51410d82f28--- /dev/null+++ b/posthog/migrations/1367_widen_activitylog_client.py@@ -0,0 +1,24 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ """+ Widen `posthog_activitylog.client` so a server-derived client tag fits.++ A scout run's writes are tagged `scout:<skill_name>`, which does not fit the 32 characters+ the column held: a scout name alone can fill most of them, and `SignalScoutRun.skill_name`+ holds up to 200. The new width takes the prefix plus that whole name.++ Postgres stores varchar(n) with the length as a catalog check, so raising n rewrites no rows.+ The ALTER still takes a brief ACCESS EXCLUSIVE lock on the table.+ """++ dependencies = [("posthog", "1366_project_deletion_scheduled_at")]++ operations = [+ migrations.AlterField(+ model_name="activitylog",+ name="client",+ field=models.CharField(blank=True, max_length=256, null=True),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 6ebe1e9e392a..41c0f2f38080 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1366_project_deletion_scheduled_at+1367_widen_activitylog_clientdiff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 150aeda190af..ced3106af088 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -240,7 +240,10 @@ class ActivityLog(UUIDTModel):was_impersonated = models.BooleanField(null=True)# If truthy, user can be unset and this indicates a 'system' user made activity asynchronouslyis_system = models.BooleanField(null=True)- # Value of the x-posthog-client request header captured when the activity was logged+ # Which API client the activity arrived through. Usually the self-reported x-posthog-client+ # request header, which is capped shorter than this column. A sandbox OAuth token bound to a+ # scout run overrides it with the scout's own `scout:<skill_name>` tag, which the caller+ # cannot set and which needs the full width.client = models.CharField(max_length=ACTIVITY_LOG_CLIENT_MAX_LENGTH, null=True, blank=True)# Client IP captured at request time. Null for non-HTTP activity (system, Celery).ip_address = models.GenericIPAddressField(null=True, blank=True)diff --git a/posthog/models/activity_logging/serializers.py b/posthog/models/activity_logging/serializers.pyindex 92f88911bd7c..0e0f9710f038 100644--- a/posthog/models/activity_logging/serializers.py+++ b/posthog/models/activity_logging/serializers.py@@ -60,7 +60,7 @@ class ActivityLogSerializer(serializers.Serializer):client = serializers.CharField(read_only=True,allow_null=True,- help_text="API client that triggered the activity, from the x-posthog-client request header (e.g. 'mcp'). Null for requests that did not send the header.",+ help_text="API client that triggered the activity. Self-reported through the x-posthog-client request header (e.g. 'mcp'), or 'scout:<skill_name>' when a scout run made the change, which the server derives from the run's own token. Null for requests that did neither.",)@extend_schema_field({"type": "object", "nullable": True})diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.pyindex 549460bfe84a..e3cfc9890291 100644--- a/posthog/models/activity_logging/utils.py+++ b/posthog/models/activity_logging/utils.py@@ -1,4 +1,5 @@import traceback+from collections.abc import Callablefrom typing import TYPE_CHECKING, Any, Optional, castfrom django.db import models@@ -15,11 +16,36 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)ACTIVITY_LOG_CLIENT_HEADER = "x-posthog-client"-ACTIVITY_LOG_CLIENT_MAX_LENGTH = 32# The MCP server forwards the same intent it sends to analytics as `$mcp_intent`. It is the# caller's own claim and does not establish a verified sandbox task binding.ACTIVITY_LOG_INTENT_HEADER = "x-posthog-intent"ACTIVITY_LOG_INTENT_MAX_LENGTH = 500+# Sized for a server-derived tag, which is the long case: `scout:` plus the longest name a scout+# row can hold (`SignalScoutRun.skill_name`, 200 characters). A tag cut mid-name would both+# misname the scout and split one scout across two values of the audit log client filter.+ACTIVITY_LOG_CLIENT_MAX_LENGTH = 256+# A self-reported header names an SDK or an integration, so it needs far less room than a derived+# tag, and the activity log renders it as it arrived. Capping it separately keeps a caller from+# filling the wider column.+ACTIVITY_LOG_CLIENT_HEADER_MAX_LENGTH = 32+# Set by `OAuthAccessTokenAuthentication` from the scout run bound to a sandbox token.+SCOUT_CLIENT_PREFIX = "scout:"+# Prefixes only the server may write. The activity log tells a reader that a tag carrying one of+# them comes from the authenticated request rather than from the client, so the two kinds of tag+# must not share a name.+SERVER_DERIVED_CLIENT_PREFIXES = (SCOUT_CLIENT_PREFIX,)+++def client_from_header(value: str) -> Optional[str]:+ """The client to store for a self-reported header, or None when the value cannot be stored.++ A header that claims a server-derived prefix is dropped whole rather than trimmed down,+ because a trimmed value would still read as the client that made the change.+ """+ client = value.strip()[:ACTIVITY_LOG_CLIENT_HEADER_MAX_LENGTH]+ if not client or client.lower().startswith(SERVER_DERIVED_CLIENT_PREFIXES):+ return None+ return client@frozen@@ -74,12 +100,36 @@ class ActivityLoggingStorage:def set_client(self, client: Optional[str]) -> None:self._local.client = client+ def set_client_resolver(self, resolver: Callable[[], Optional[str]]) -> None:+ """Hand over a server-derived client to look up when one is first needed.++ `log_activity` is the only reader, so a request that writes no activity row never pays+ for the lookup. A resolved client replaces whatever the client header reported.+ """+ self._local.client_resolver = resolver+def get_client(self) -> Optional[str]:+ """The client for this request, running a pending resolver the first time it is needed."""+ resolver = getattr(self._local, "client_resolver", None)+ if resolver is not None:+ # Drop the resolver before running it, so one lookup covers every later read and a+ # failing lookup is not retried for each activity row in the request.+ delattr(self._local, "client_resolver")+ try:+ resolved = resolver()+ except Exception:+ # Attribution is not worth failing a write for: the row keeps the reported client.+ logger.warning("activity_log.client_resolver_failed", exc_info=True)+ resolved = None+ if resolved:+ self._local.client = resolved[:ACTIVITY_LOG_CLIENT_MAX_LENGTH]return getattr(self._local, "client", None)def clear_client(self) -> None:if hasattr(self._local, "client"):delattr(self._local, "client")+ if hasattr(self._local, "client_resolver"):+ delattr(self._local, "client_resolver")def set_agent_intent(self, intent: Optional[str]) -> None:self._local.agent_intent = intentdiff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex e991dab023eb..c5d640050faf 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -1906,13 +1906,26 @@ class TestActivityLoggingMiddleware(APIBaseTest):self.assertIsNone(self.captured["client"])def test_long_header_value_is_truncated(self):- from posthog.models.activity_logging.utils import ACTIVITY_LOG_CLIENT_MAX_LENGTH+ from posthog.models.activity_logging.utils import ACTIVITY_LOG_CLIENT_HEADER_MAX_LENGTH- long_value = "x" * (ACTIVITY_LOG_CLIENT_MAX_LENGTH * 4)+ long_value = "x" * (ACTIVITY_LOG_CLIENT_HEADER_MAX_LENGTH * 4)request = self.factory.get("/", HTTP_X_POSTHOG_CLIENT=long_value)request.user = self.userself.middleware(request)- self.assertEqual(self.captured["client"], "x" * ACTIVITY_LOG_CLIENT_MAX_LENGTH)+ self.assertEqual(self.captured["client"], "x" * ACTIVITY_LOG_CLIENT_HEADER_MAX_LENGTH)++ @parameterized.expand(+ [+ ("lowercase prefix", "scout:signals-scout-errors"),+ ("upper case prefix", "SCOUT:signals-scout-errors"),+ ("padded prefix", " scout:signals-scout-errors "),+ ]+ )+ def test_header_claiming_a_server_derived_prefix_is_dropped(self, _name: str, header_value: str):+ request = self.factory.get("/", HTTP_X_POSTHOG_CLIENT=header_value)+ request.user = self.user+ self.middleware(request)+ self.assertIsNone(self.captured["client"])def test_captures_ip_address_from_remote_addr(self):request = self.factory.get("/", REMOTE_ADDR="203.0.113.42")diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex 815e492f8da8..138bbf099785 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -1929,7 +1929,7 @@ export interface ActivityLogEntryApi {/** Whether the acting user was being impersonated by PostHog staff. */readonly was_impersonated: boolean/**- * API client that triggered the activity, from the x-posthog-client request header (e.g. 'mcp'). Null for requests that did not send the header.+ * API client that triggered the activity. Self-reported through the x-posthog-client request header (e.g. 'mcp'), or 'scout:<skill_name>' when a scout run made the change, which the server derives from the run's own token. Null for requests that did neither.* @nullable*/readonly client: string | nulldiff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex efe77a80c3d9..0cc99967a93f 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1188,7 +1188,7 @@ export interface ActivityLogEntryApi {/** Whether the acting user was being impersonated by PostHog staff. */readonly was_impersonated: boolean/**- * API client that triggered the activity, from the x-posthog-client request header (e.g. 'mcp'). Null for requests that did not send the header.+ * API client that triggered the activity. Self-reported through the x-posthog-client request header (e.g. 'mcp'), or 'scout:<skill_name>' when a scout run made the change, which the server derives from the run's own token. Null for requests that did neither.* @nullable*/readonly client: string | nulldiff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 667b1aba53e3..6d36c8b97e49 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -794,7 +794,7 @@ export interface ActivityLogApi {/** @nullable */is_system?: boolean | null/**- * @maxLength 32+ * @maxLength 256* @nullable*/client?: string | null@@ -842,7 +842,7 @@ export interface StaticFiltersApi {scopes: StaticFiltersApiScopesItem[]/** Available activity types. */activities: StaticFiltersApiActivitiesItem[]- /** API clients that have generated activity (from x-posthog-client header). */+ /** API clients that have generated activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run). */clients: StaticFiltersApiClientsItem[]}@@ -1689,7 +1689,7 @@ export type AdvancedActivityLogsListParams = {*/activities?: string[]/**- * Filter by API clients that generated the activity (from x-posthog-client header).+ * Filter by API clients that generated the activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run).*/clients?: string[]/**diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.tsindex 5ac2042612d8..104d78968ade 100644--- a/products/platform_features/frontend/generated/api.zod.ts+++ b/products/platform_features/frontend/generated/api.zod.ts@@ -274,7 +274,7 @@ export const advancedActivityLogsExportCreateBodyUserEmailMax = 254export const advancedActivityLogsExportCreateBodyTeamIdMin = 0export const advancedActivityLogsExportCreateBodyTeamIdMax = 2147483647-export const advancedActivityLogsExportCreateBodyClientMax = 32+export const advancedActivityLogsExportCreateBodyClientMax = 256export const advancedActivityLogsExportCreateBodyActivityMax = 79diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 8a77c49996b1..f2ba0f533daf 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -8687,7 +8687,7 @@ export interface ActivityLogEntryApi {/** Whether the acting user was being impersonated by PostHog staff. */readonly was_impersonated: boolean/**- * API client that triggered the activity, from the x-posthog-client request header (e.g. 'mcp'). Null for requests that did not send the header.+ * API client that triggered the activity. Self-reported through the x-posthog-client request header (e.g. 'mcp'), or 'scout:<skill_name>' when a scout run made the change, which the server derives from the run's own token. Null for requests that did neither.* @nullable*/readonly client: string | nulldiff --git a/products/signals/backend/facade/activity_client.py b/products/signals/backend/facade/activity_client.pynew file mode 100644index 000000000000..3438b80f4fe8--- /dev/null+++ b/products/signals/backend/facade/activity_client.py@@ -0,0 +1,37 @@+"""The activity-log client tag for the API writes a scout run makes.++A scout authenticates as the person who owns its config, so the acting user on an+activity-log row cannot tell a scout's edit from that person's own MCP edit. The sandbox+OAuth token carries the id of the task the run happens in, and that binding is written+server-side at mint time, which is what makes a tag derived from it trustworthy where the+caller-settable `x-posthog-client` header is not. The `scout:` prefix is reserved for this+path: `client_from_header` drops a header value that claims it, so only the server writes one.++Core reads the tag through this module so `posthog.auth` never imports a signals model.+"""++from __future__ import annotations++from uuid import UUID++from posthog.models.activity_logging.utils import SCOUT_CLIENT_PREFIX++from products.signals.backend.models import SignalScoutRun+++def resolve_scout_client_tag(*, sandbox_task_id: UUID, team_id: int) -> str | None:+ """`scout:<skill_name>` when a scout run owns this task, None when no scout run does.++ A task with several runs (a retry) is still one scout, so any of its rows answers the+ question. The ordering only keeps repeated reads of the same task consistent.+ """+ skill_name = (+ SignalScoutRun.objects.for_team(team_id)+ .filter(task_run__task_id=sandbox_task_id)+ .order_by("-created_at")+ .values_list("skill_name", flat=True)+ .first()+ )+ if not skill_name:+ return None+ return f"{SCOUT_CLIENT_PREFIX}{skill_name}"diff --git a/products/signals/backend/test/test_scout_activity_client.py b/products/signals/backend/test/test_scout_activity_client.pynew file mode 100644index 000000000000..17e6b4210cc5--- /dev/null+++ b/products/signals/backend/test/test_scout_activity_client.py@@ -0,0 +1,125 @@+from datetime import timedelta++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.test import RequestFactory+from django.utils import timezone++from parameterized import parameterized++from posthog.auth import OAuthAccessTokenAuthentication+from posthog.models import OAuthApplication, Team+from posthog.models.activity_logging.utils import activity_storage+from posthog.models.oauth import OAuthAccessToken++from products.signals.backend.facade.activity_client import resolve_scout_client_tag+from products.signals.backend.models import SignalScoutRun+from products.tasks.backend.models import Task, TaskRun++SELF_REPORTED_CLIENT = "mcp"+SKILL_NAME = "signals-scout-self-driving-dwh"+++class TestScoutActivityClient(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.factory = RequestFactory()+ self.application = OAuthApplication.objects.create(+ client_id="scout-sandbox-client",+ redirect_uris="http://localhost/cb",+ client_type=OAuthApplication.CLIENT_PUBLIC,+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,+ algorithm="RS256",+ organization=self.organization,+ )+ activity_storage.mark_request_scoped()+ activity_storage.set_client(SELF_REPORTED_CLIENT)++ def tearDown(self) -> None:+ activity_storage.clear_all()+ super().tearDown()++ def _make_task(self) -> Task:+ return Task.objects.create(+ team=self.team,+ title="scout run",+ description="scout run",+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,+ )++ def _make_scout_run(self, task: Task) -> SignalScoutRun:+ return SignalScoutRun.objects.create(+ task_run=TaskRun.objects.create(task=task, team=self.team),+ team=self.team,+ skill_name=SKILL_NAME,+ skill_version=1,+ )++ def _authenticate_with_sandbox_token(+ self, sandbox_task_id: str | None, scoped_teams: list[int] | None = None+ ) -> None:+ OAuthAccessToken.objects.create(+ user=self.user,+ application=self.application,+ token="pha_scout_sandbox_token",+ scope="dashboard:write",+ expires=timezone.now() + timedelta(hours=1),+ scoped_teams=[self.team.id] if scoped_teams is None else scoped_teams,+ scoped_organizations=[],+ sandbox_task_id=sandbox_task_id,+ )+ request = self.factory.get("/", HTTP_AUTHORIZATION="Bearer pha_scout_sandbox_token")+ OAuthAccessTokenAuthentication().authenticate(request)++ def test_scout_run_token_tags_activity_with_the_scout_name(self) -> None:+ task = self._make_task()+ self._make_scout_run(task)++ self._authenticate_with_sandbox_token(str(task.id))++ assert activity_storage.get_client() == f"scout:{SKILL_NAME}"++ def test_the_scout_is_looked_up_only_when_a_client_is_read(self) -> None:+ task = self._make_task()+ self._make_scout_run(task)++ # The auth module binds the facade function by name, so patch it where it is used.+ with patch("posthog.auth.resolve_scout_client_tag", wraps=resolve_scout_client_tag) as resolve:+ self._authenticate_with_sandbox_token(str(task.id))+ assert resolve.call_count == 0++ assert activity_storage.get_client() == f"scout:{SKILL_NAME}"+ assert activity_storage.get_client() == f"scout:{SKILL_NAME}"+ assert resolve.call_count == 1++ @parameterized.expand(+ [+ ("no task bound to the token", False),+ ("task is not a scout run", True),+ ]+ )+ def test_token_without_a_scout_run_keeps_the_self_reported_client(self, _name: str, bind_task: bool) -> None:+ sandbox_task_id = str(self._make_task().id) if bind_task else None++ self._authenticate_with_sandbox_token(sandbox_task_id)++ assert activity_storage.get_client() == SELF_REPORTED_CLIENT++ @parameterized.expand(+ [+ ("scoped to two teams", "two"),+ ("scoped to no team", "none"),+ ]+ )+ def test_token_that_does_not_name_one_team_keeps_the_self_reported_client(self, _name: str, scoping: str) -> None:+ # Which team's runs to search is not a guess to make, so a token that does not name+ # exactly one team is left with the client it reported, scout run or not.+ task = self._make_task()+ self._make_scout_run(task)+ other_team = Team.objects.create(organization=self.organization, name="Other")+ scoped_teams = [self.team.id, other_team.id] if scoping == "two" else []++ self._authenticate_with_sandbox_token(str(task.id), scoped_teams=scoped_teams)++ assert activity_storage.get_client() == SELF_REPORTED_CLIENTdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d2ac4088802c..de35f3a62826 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3576,7 +3576,7 @@ export namespace Schemas {/** @nullable */is_system?: boolean | null;/**- * @maxLength 32+ * @maxLength 256* @nullable*/client?: string | null;@@ -3644,7 +3644,7 @@ export namespace Schemas {/** Whether the acting user was being impersonated by PostHog staff. */readonly was_impersonated: boolean;/**- * API client that triggered the activity, from the x-posthog-client request header (e.g. 'mcp'). Null for requests that did not send the header.+ * API client that triggered the activity. Self-reported through the x-posthog-client request header (e.g. 'mcp'), or 'scout:<skill_name>' when a scout run made the change, which the server derives from the run's own token. Null for requests that did neither.* @nullable*/readonly client: string | null;@@ -11878,7 +11878,7 @@ export namespace Schemas {scopes: StaticFiltersScopesItem[];/** Available activity types. */activities: StaticFiltersActivitiesItem[];- /** API clients that have generated activity (from x-posthog-client header). */+ /** API clients that have generated activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run). */clients: StaticFiltersClientsItem[];}@@ -97798,7 +97798,7 @@ export namespace Schemas {*/activities?: string[];/**- * Filter by API clients that generated the activity (from x-posthog-client header).+ * Filter by API clients that generated the activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run).*/clients?: string[];/**@@ -99052,7 +99052,7 @@ export namespace Schemas {*/activities?: string[];/**- * Filter by API clients that generated the activity (from x-posthog-client header).+ * Filter by API clients that generated the activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run).*/clients?: string[];/**diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.tsindex 90414541ba19..c72bcdb01e04 100644--- a/services/mcp/src/generated/platform_features/api.ts+++ b/services/mcp/src/generated/platform_features/api.ts@@ -201,7 +201,9 @@ export const AdvancedActivityLogsListQueryParams = () => zod.object({clients: zod.array(zod.string()).default(advancedActivityLogsListQueryClientsDefault)- .describe('Filter by API clients that generated the activity (from x-posthog-client header).'),+ .describe(+ "Filter by API clients that generated the activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run)."+ ),detail_filters: zod.string().optional()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.jsonindex 88c4c9e30358..71fbd5672279 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/advanced-activity-logs-list.json@@ -11,7 +11,7 @@},"clients": {"default": [],- "description": "Filter by API clients that generated the activity (from x-posthog-client header).",+ "description": "Filter by API clients that generated the activity (the x-posthog-client header, or 'scout:<skill_name>' for a scout run).","items": {"type": "string"},