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.

fix(analytics): align source attribution with product surfaces (#72941)

Georgiy Tarasovd5b9be59551a
diff --git a/ee/api/max_tools.py b/ee/api/max_tools.py
index c6885767a6eb..c5c5697abd8d 100644
--- a/ee/api/max_tools.py
+++ b/ee/api/max_tools.py
@@ -13,6 +13,7 @@ from rest_framework.viewsets import GenericViewSet
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
+from posthog.event_usage import get_event_source
from posthog.models.user import User
from posthog.rate_limit import AIBurstRateThrottle, AISustainedRateThrottle
from posthog.renderers import SafeJSONRenderer
@@ -69,6 +70,10 @@ class MaxToolsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
is_new_conversation=False, # we don't care about the conversation id being sent back to the client
initial_state=serializer.validated_data["state"],
is_agent_billable=False,
+ # This endpoint has no session auth, so it is never the web assistant — it is reached
+ # only by an agent through the MCP server. Resolving from the request rather than
+ # pinning `mcp` keeps the surface that wrapped MCP (desktop, Slack, the CLI) visible.
+ event_source=get_event_source(request),
)
return Response(
diff --git a/ee/api/test/test_max_tools.py b/ee/api/test/test_max_tools.py
index 938eb4cd61c9..2d6dbeaa5c6b 100644
--- a/ee/api/test/test_max_tools.py
+++ b/ee/api/test/test_max_tools.py
@@ -2,6 +2,9 @@ from posthog.test.base import APIBaseTest
from unittest.mock import patch
from mistralai_azure import AssistantMessage
+from parameterized import parameterized
+
+from posthog.event_usage import EventSource
from ee.hogai.insights_assistant import InsightsAssistant
@@ -26,6 +29,32 @@ class TestMaxToolsAPI(APIBaseTest):
mock_generate.assert_called_once()
+ @parameterized.expand(
+ [
+ ("mcp_client_header", {"HTTP_X_POSTHOG_CLIENT": "mcp"}, EventSource.MCP),
+ (
+ "cli_wrapping_mcp",
+ {"HTTP_X_POSTHOG_CLIENT": "mcp", "HTTP_X_POSTHOG_MCP_CONSUMER": "posthog-cli"},
+ EventSource.CLI,
+ ),
+ ]
+ )
+ @patch("ee.hogai.insights_assistant.InsightsAssistant")
+ def test_create_and_query_insight_attributes_to_the_calling_surface(
+ self, _name, headers, expected_source, mock_assistant
+ ):
+ mock_assistant.return_value.invoke.return_value = []
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/max_tools/create_and_query_insight/",
+ {"query": "Show me daily active users", "insight_type": "trends"},
+ format="json",
+ **headers,
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(mock_assistant.call_args.kwargs["event_source"], expected_source)
+
def test_create_and_query_insight_missing_insight_type(self):
response = self.client.post(
f"/api/environments/{self.team.id}/max_tools/create_and_query_insight/",
diff --git a/ee/hogai/chat_agent/memory/nodes.py b/ee/hogai/chat_agent/memory/nodes.py
index c37dac41ce58..965d58475119 100644
--- a/ee/hogai/chat_agent/memory/nodes.py
+++ b/ee/hogai/chat_agent/memory/nodes.py
@@ -109,6 +109,7 @@ class MemoryInitializerContextMixin(AssistantContextMixin):
)
return runner.run(
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
+ user=self._user,
analytics_props={"source": EventSource.POSTHOG_AI},
)
diff --git a/ee/hogai/chat_agent/query_executor/nodes.py b/ee/hogai/chat_agent/query_executor/nodes.py
index 7dc273c51792..cab59f1647e3 100644
--- a/ee/hogai/chat_agent/query_executor/nodes.py
+++ b/ee/hogai/chat_agent/query_executor/nodes.py
@@ -34,6 +34,7 @@ class QueryExecutorNode(AssistantNode):
name=content.name,
description=content.description,
insight_id=artifact.artifact_id,
+ event_source=self.context_manager.event_source,
)
formatted_query_result = await context.execute_and_format()
except MaxToolRetryableError as err:
diff --git a/ee/hogai/chat_agent/query_planner/nodes.py b/ee/hogai/chat_agent/query_planner/nodes.py
index 7e2cc3340943..4f6e014be08c 100644
--- a/ee/hogai/chat_agent/query_planner/nodes.py
+++ b/ee/hogai/chat_agent/query_planner/nodes.py
@@ -108,7 +108,9 @@ class QueryPlannerNode(TaxonomyUpdateDispatcherNodeMixin, AssistantNode):
"react_property_filters": self._get_react_property_filters_prompt(),
"react_human_in_the_loop": HUMAN_IN_THE_LOOP_PROMPT,
"groups": self._team_group_types,
- "events": format_events_yaml(events_in_context, self._team, self._user),
+ "events": format_events_yaml(
+ events_in_context, self._team, self._user, event_source=self.context_manager.event_source
+ ),
"project_datetime": self.project_now,
"project_timezone": self.project_timezone,
"project_name": self._team.name,
@@ -244,7 +246,7 @@ class QueryPlannerToolsNode(AssistantNode, ABC):
"""
def run(self, state: AssistantState, config: RunnableConfig) -> PartialAssistantState:
- toolkit = TaxonomyAgentToolkit(self._team, self._user)
+ toolkit = TaxonomyAgentToolkit(self._team, self._user, event_source=self.context_manager.event_source)
intermediate_steps = state.intermediate_steps or []
action, _output = intermediate_steps[-1]
diff --git a/ee/hogai/chat_agent/query_planner/toolkit.py b/ee/hogai/chat_agent/query_planner/toolkit.py
index a7cd99c52b37..8ddde2df1eca 100644
--- a/ee/hogai/chat_agent/query_planner/toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/toolkit.py
@@ -107,9 +107,10 @@ class TaxonomyAgentToolkit:
_team: Team
_user: User
- def __init__(self, team: Team, user: User):
+ def __init__(self, team: Team, user: User, event_source: EventSource = EventSource.POSTHOG_AI):
self._team = team
self._user = user
+ self._event_source = event_source
def _restricted_property_names(self, property_type: PropertyDefinition.Type) -> set[str]:
return restricted_property_names(self._team, self._user, property_type)
@@ -281,7 +282,8 @@ class TaxonomyAgentToolkit:
):
response = runner.run(
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
- analytics_props={"source": EventSource.POSTHOG_AI},
+ user=self._user,
+ analytics_props={"source": self._event_source},
)
return response, verbose_name
@@ -485,7 +487,8 @@ class TaxonomyAgentToolkit:
):
response = ActorsPropertyTaxonomyQueryRunner(query, self._team, user=self._user).run(
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
- analytics_props={"source": EventSource.POSTHOG_AI},
+ user=self._user,
+ analytics_props={"source": self._event_source},
)
if not isinstance(response, CachedActorsPropertyTaxonomyQueryResponse):
diff --git a/ee/hogai/chat_agent/rag/nodes.py b/ee/hogai/chat_agent/rag/nodes.py
index 0717e9d9fe02..5237dfcd93f2 100644
--- a/ee/hogai/chat_agent/rag/nodes.py
+++ b/ee/hogai/chat_agent/rag/nodes.py
@@ -13,7 +13,7 @@ from prometheus_client import Histogram
from posthog.schema import CachedVectorSearchQueryResponse, MaxActionContext, TeamTaxonomyQuery, VectorSearchQuery
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
-from posthog.event_usage import EventSource, report_user_action
+from posthog.event_usage import report_user_action
from posthog.hogql_queries.ai.team_taxonomy_query_runner import TeamTaxonomyQueryRunner
from posthog.hogql_queries.ai.vector_search_query_runner import (
LATEST_ACTIONS_EMBEDDING_VERSION,
@@ -134,7 +134,8 @@ class InsightRagContextNode(AssistantNode):
):
response = runner.run(
ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
- analytics_props={"source": EventSource.POSTHOG_AI},
+ user=self._user,
+ analytics_props={"source": self.context_manager.event_source},
)
if isinstance(response, CachedVectorSearchQueryResponse) and response.results:
ids = list({row.id for row in response.results} | set(ids))
@@ -181,7 +182,8 @@ class InsightRagContextNode(AssistantNode):
"""
TeamTaxonomyQueryRunner(TeamTaxonomyQuery(), self._team, user=self._user).run(
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE,
- analytics_props={"source": EventSource.POSTHOG_AI},
+ user=self._user,
+ analytics_props={"source": self.context_manager.event_source},
)
def _report_metrics(self, config: RunnableConfig, distances: list[float]):
@@ -202,4 +204,5 @@ class InsightRagContextNode(AssistantNode):
"$ai_metric_value": metric_value,
},
team=self._team,
+ analytics_props={"source": self.context_manager.event_source},
)
diff --git a/ee/hogai/chat_agent/rag/test/test_nodes.py b/ee/hogai/chat_agent/rag/test/test_nodes.py
index a3c7875bd615..500b70d62cbd 100644
--- a/ee/hogai/chat_agent/rag/test/test_nodes.py
+++ b/ee/hogai/chat_agent/rag/test/test_nodes.py
@@ -69,7 +69,7 @@ class TestInsightRagContextNode(ClickhouseTestMixin, BaseTest):
# Check run was called with the correct execution mode
mock_runner_instance.run.assert_called_once_with(
- ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE, analytics_props=ANY
+ ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE, user=self.user, analytics_props=ANY
)
def test_injects_action(self, cohere_mock, embed_mock):
diff --git a/ee/hogai/chat_agent/taxonomy/nodes.py b/ee/hogai/chat_agent/taxonomy/nodes.py
index 2103f0112642..4e9782a92489 100644
--- a/ee/hogai/chat_agent/taxonomy/nodes.py
+++ b/ee/hogai/chat_agent/taxonomy/nodes.py
@@ -110,7 +110,9 @@ class TaxonomyAgentNode(
Generate the output format for events. Can be overridden by subclasses.
Default implementation uses YAML format but it can be overridden to use XML format.
"""
- return format_events_yaml(events_in_context, self._team, self._user)
+ return format_events_yaml(
+ events_in_context, self._team, self._user, event_source=self.context_manager.event_source
+ )
def run(self, state: TaxonomyStateType, config: RunnableConfig) -> TaxonomyPartialStateType:
"""Process the state and return filtering options."""
diff --git a/ee/hogai/chat_agent/taxonomy/toolkit.py b/ee/hogai/chat_agent/taxonomy/toolkit.py
index 0c67f0d583eb..bb8c1478796c 100644
--- a/ee/hogai/chat_agent/taxonomy/toolkit.py
+++ b/ee/hogai/chat_agent/taxonomy/toolkit.py
@@ -137,7 +137,7 @@ class TaxonomyTaskExecutorNode(
"""
async def _aget_input_tuples(self, tool_calls: list[AssistantToolCall]) -> list[TaskExecutionInputTuple]:
- taxonomy_toolkit = TaxonomyAgentToolkit(self._team, self._user)
+ taxonomy_toolkit = TaxonomyAgentToolkit(self._team, self._user, event_source=self.context_manager.event_source)
input_tuples: list[TaskExecutionInputTuple] = []
for task in tool_calls:
if task.name == "retrieve_event_or_action_properties":
@@ -154,9 +154,10 @@ class TaxonomyTaskExecutorNode(
class TaxonomyAgentToolkit:
"""Base toolkit for taxonomy agents that handle tool execution."""
- def __init__(self, team: Team, user: User):
+ def __init__(self, team: Team, user: User, event_source: EventSource = EventSource.POSTHOG_AI):
self._team = team
self._user = user
+ self._event_source = event_source
self.MAX_ENTITIES_PER_BATCH = 6
self.MAX_PROPERTIES = 500
@@ -315,7 +316,8 @@ class TaxonomyAgentToolkit:
# Use cache-first execution mode for optimal performance
response = runner.run(
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
- analytics_props={"source": EventSource.POSTHOG_AI},
+ user=self._user,
+ analytics_props={"source": self._event_source},
)
return response, verbose_name
@@ -761,7 +763,8 @@ class TaxonomyAgentToolkit:
):
return ActorsPropertyTaxonomyQueryRunner(query, self._team, user=self._user).run(
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
- analytics_props={"source": EventSource.POSTHOG_AI},
+ user=self._user,
+ analytics_props={"source": self._event_source},
)
@database_sync_to_async(thread_sensitive=False)
diff --git a/ee/hogai/context/context.py b/ee/hogai/context/context.py
index 5e7bceb30e11..eb92be309eca 100644
--- a/ee/hogai/context/context.py
+++ b/ee/hogai/context/context.py
@@ -24,7 +24,7 @@ from posthog.schema import (
)
from posthog.constants import AvailableFeature
-from posthog.event_usage import groups
+from posthog.event_usage import EventSource, groups
from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -141,6 +141,26 @@ class AssistantContextManager(AssistantContextMixin):
def is_subagent(self) -> bool:
return (self._config.get("configurable") or {}).get("is_subagent", False)
+ @property
+ def event_source(self) -> EventSource:
+ """The surface that asked for this run, for analytics attribution.
+
+ Defaults to `posthog_ai` because most runs are the in-product assistant. Programmatic
+ entry points (the MCP `create_and_query_insight` endpoint) resolve it from the request
+ instead, so an agent's work isn't counted as PostHog AI's.
+
+ Coerced rather than type-checked: configs round-trip through checkpoint serialization,
+ which turns the enum back into a plain string, and `isinstance` would silently reset a
+ recovered run to the default.
+ """
+ event_source = (self._config.get("configurable") or {}).get("event_source")
+ if event_source is None:
+ return EventSource.POSTHOG_AI
+ try:
+ return EventSource(event_source)
+ except ValueError:
+ return EventSource.POSTHOG_AI
+
def get_billing_context(self) -> MaxBillingContext | None:
"""
Extracts the billing context from the runnable config.
@@ -507,6 +527,7 @@ class AssistantContextManager(AssistantContextMixin):
return InsightContext(
team=self._team,
user=self._user,
+ event_source=self.event_source,
query=insight.query,
name=insight.name,
description=insight.description,
diff --git a/ee/hogai/context/insight/context.py b/ee/hogai/context/insight/context.py
index 3257f7ac1776..aff556a23b34 100644
--- a/ee/hogai/context/insight/context.py
+++ b/ee/hogai/context/insight/context.py
@@ -1,3 +1,4 @@
+from posthog.event_usage import EventSource
from posthog.hogql_queries.apply_dashboard_filters import (
apply_dashboard_filters_to_dict,
apply_dashboard_variables_to_dict,
@@ -40,9 +41,11 @@ class InsightContext:
dashboard_filters: dict | None = None,
filters_override: dict | None = None,
variables_override: dict | None = None,
+ event_source: EventSource = EventSource.POSTHOG_AI,
):
self.team = team
self.user = user
+ self.event_source = event_source
self.query = query
self.name = name
self.description = description
@@ -93,6 +96,7 @@ class InsightContext:
truncate_results=truncate_results,
user=self.user,
include_prompt_framing=include_prompt_framing,
+ event_source=self.event_source,
)
except Exception as e:
error_message = f"Error executing query: {str(e)}"
diff --git a/ee/hogai/context/insight/query_executor.py b/ee/hogai/context/insight/query_executor.py
index 5e32b6cafcda..3d3f67761378 100644
--- a/ee/hogai/context/insight/query_executor.py
+++ b/ee/hogai/context/insight/query_executor.py
@@ -136,10 +136,17 @@ class AssistantQueryExecutor:
WAIT_TIME_S = 0.5
- def __init__(self, team: Team, utc_now_datetime: datetime, user: "User"):
+ def __init__(
+ self,
+ team: Team,
+ utc_now_datetime: datetime,
+ user: "User",
+ event_source: EventSource = EventSource.POSTHOG_AI,
+ ):
self._team = team
self._utc_now_datetime = utc_now_datetime
self._user = user
+ self._event_source = event_source
async def arun_and_format_query(
self,
@@ -318,6 +325,7 @@ class AssistantQueryExecutor:
parent_tag_kwargs = get_query_tags().model_dump(exclude_none=True)
team = self._team
user = self._user
+ event_source = self._event_source
query_dict = query.model_dump(mode="json")
def process_query_dict_with_tags() -> dict | BaseModel:
@@ -328,7 +336,7 @@ class AssistantQueryExecutor:
execution_mode=execution_mode,
limit_context=LimitContext.POSTHOG_AI,
user=user,
- analytics_props={"source": EventSource.POSTHOG_AI},
+ analytics_props={"source": event_source},
)
# If the query has a blocking execution, execute on a separate thread. Otherwise, use the main thread
@@ -591,6 +599,7 @@ async def execute_and_format_query(
insight_id: Optional[int] = None,
truncate_results: bool = True,
include_prompt_framing: bool = True,
+ event_source: EventSource = EventSource.POSTHOG_AI,
) -> str:
"""
Executes a supported query and formats the results for the AI assistant:
@@ -614,7 +623,7 @@ async def execute_and_format_query(
"""
query = validate_assistant_query(query_model.model_dump(mode="json"))
utc_now_datetime = timezone.now().astimezone(UTC)
- query_runner = AssistantQueryExecutor(team, utc_now_datetime, user=user)
+ query_runner = AssistantQueryExecutor(team, utc_now_datetime, user=user, event_source=event_source)
results, used_fallback = await query_runner.arun_and_format_query(
query, execution_mode, insight_id, truncate_results=truncate_results
diff --git a/ee/hogai/core/runner.py b/ee/hogai/core/runner.py
index 9cd0771e3e09..cdec2658aeab 100644
--- a/ee/hogai/core/runner.py
+++ b/ee/hogai/core/runner.py
@@ -34,7 +34,7 @@ from posthog.schema import (
from posthog import event_usage
from posthog.cloud_utils import is_cloud
-from posthog.event_usage import report_user_action
+from posthog.event_usage import EventSource, report_user_action
from posthog.models import Team, User
from posthog.ph_client import get_client
from posthog.sync import database_sync_to_async
@@ -121,6 +121,7 @@ class BaseAgentRunner(ABC):
_slack_thread_context: Optional["SlackThreadContext"]
_is_agent_billable: bool
_resume_payload: Optional[dict[str, Any]]
+ _event_source: EventSource
def __init__(
self,
@@ -146,10 +147,12 @@ class BaseAgentRunner(ABC):
is_agent_billable: bool = True,
is_impersonated: bool = False,
resume_payload: Optional[dict[str, Any]] = None,
+ event_source: EventSource = EventSource.POSTHOG_AI,
):
self._team = team
self._contextual_tools = contextual_tools or {}
self._user = user
+ self._event_source = event_source
self._session_id = session_id
self._conversation = conversation
self._latest_message = new_message.model_copy(deep=True, update={"id": str(uuid4())}) if new_message else None
@@ -524,6 +527,7 @@ class BaseAgentRunner(ABC):
"is_subagent": not self._use_checkpointer,
"slack_thread_context": self._slack_thread_context,
"is_agent_billable": self._is_agent_billable,
+ "event_source": self._event_source,
# Metadata to be sent to PostHog SDK (error tracking, etc).
"sdk_metadata": {
"tag": "max_ai",
diff --git a/ee/hogai/insights_assistant.py b/ee/hogai/insights_assistant.py
index 7b3fc57519bc..2dc4b15faacc 100644
--- a/ee/hogai/insights_assistant.py
+++ b/ee/hogai/insights_assistant.py
@@ -12,6 +12,7 @@ from posthog.schema import (
VisualizationMessage,
)
+from posthog.event_usage import EventSource
from posthog.models import Team, User
from products.posthog_ai.backend.models.assistant import Conversation
@@ -56,6 +57,7 @@ class InsightsAssistant(BaseAgentRunner):
billing_context: Optional[MaxBillingContext] = None,
initial_state: Optional[AssistantState | PartialAssistantState] = None,
is_agent_billable: bool = True,
+ event_source: EventSource = EventSource.POSTHOG_AI,
):
super().__init__(
team,
@@ -72,6 +74,7 @@ class InsightsAssistant(BaseAgentRunner):
billing_context=billing_context,
initial_state=initial_state,
is_agent_billable=is_agent_billable,
+ event_source=event_source,
stream_processor=ChatAgentStreamProcessor(
team=team,
user=user,
diff --git a/ee/hogai/mcp_tool.py b/ee/hogai/mcp_tool.py
index 56dc6744b3b3..d54876d12b78 100644
--- a/ee/hogai/mcp_tool.py
+++ b/ee/hogai/mcp_tool.py
@@ -4,6 +4,7 @@ from typing import Any, Generic, TypeVar
from pydantic import BaseModel
+from posthog.event_usage import EventSource
from posthog.models import Team, User
ArgsT = TypeVar("ArgsT", bound=BaseModel)
@@ -23,9 +24,10 @@ class MCPTool(ABC, Generic[ArgsT]):
name: str
args_schema: type[ArgsT]
- def __init__(self, team: Team, user: User):
+ def __init__(self, team: Team, user: User, event_source: EventSource = EventSource.MCP):
self._team = team
self._user = user
+ self._event_source = event_source
@abstractmethod
async def execute(self, args: ArgsT) -> str:
@@ -80,11 +82,13 @@ class MCPToolRegistry:
load_all_tools()
return self._tools
- def get(self, name: str, team: Team, user: User) -> MCPTool[Any] | None:
+ def get(
+ self, name: str, team: Team, user: User, event_source: EventSource = EventSource.MCP
+ ) -> MCPTool[Any] | None:
"""Get an MCP tool instance by name, constructed with team/user."""
registration = self._ensure_loaded().get(name)
if registration:
- return registration.tool_cls(team=team, user=user)
+ return registration.tool_cls(team=team, user=user, event_source=event_source)
return None
def get_scopes(self, name: str) -> list[str]:
diff --git a/ee/hogai/tools/execute_sql/mcp_tool.py b/ee/hogai/tools/execute_sql/mcp_tool.py
index 60c35f300249..80c4469773d4 100644
--- a/ee/hogai/tools/execute_sql/mcp_tool.py
+++ b/ee/hogai/tools/execute_sql/mcp_tool.py
@@ -103,6 +103,7 @@ class ExecuteSQLMCPTool(HogQLOutputParserMixin, MCPTool[ExecuteSQLMCPToolArgs]):
name="",
description="",
user=self._user,
+ event_source=self._event_source,
)
results = await insight_context.execute_and_format(
prompt_template="{{{results}}}", truncate_results=args.truncate, include_prompt_framing=False
diff --git a/ee/hogai/tools/read_taxonomy/core.py b/ee/hogai/tools/read_taxonomy/core.py
index 0a441505def2..3005e9921640 100644
--- a/ee/hogai/tools/read_taxonomy/core.py
+++ b/ee/hogai/tools/read_taxonomy/core.py
@@ -2,6 +2,7 @@ from typing import Literal, Union
from pydantic import BaseModel, Field
+from posthog.event_usage import EventSource
from posthog.models import Team, User
from ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkit
@@ -94,7 +95,13 @@ If the user's question involves feature flags, construct the property name using
""".strip()
-def execute_taxonomy_query(query: ReadTaxonomyQuery, toolkit: TaxonomyAgentToolkit, team: Team, user: User) -> str:
+def execute_taxonomy_query(
+ query: ReadTaxonomyQuery,
+ toolkit: TaxonomyAgentToolkit,
+ team: Team,
+ user: User,
+ event_source: EventSource = EventSource.POSTHOG_AI,
+) -> str:
"""
Execute a taxonomy query and return the result.
@@ -102,7 +109,7 @@ def execute_taxonomy_query(query: ReadTaxonomyQuery, toolkit: TaxonomyAgentToolk
"""
match query:
case ReadEvents():
- return format_events_yaml([], team, user, limit=query.limit, offset=query.offset)
+ return format_events_yaml([], team, user, limit=query.limit, offset=query.offset, event_source=event_source)
case ReadEventProperties():
result = toolkit.retrieve_event_or_action_properties(query.event_name)
description = get_event_description(team, query.event_name)
diff --git a/ee/hogai/tools/read_taxonomy/mcp_tool.py b/ee/hogai/tools/read_taxonomy/mcp_tool.py
index 51fe3fde4776..b2a5adb1f26a 100644
--- a/ee/hogai/tools/read_taxonomy/mcp_tool.py
+++ b/ee/hogai/tools/read_taxonomy/mcp_tool.py
@@ -19,13 +19,15 @@ class ReadTaxonomyMCPTool(MCPTool[ReadTaxonomyToolArgs]):
args_schema = ReadTaxonomyToolArgs
async def execute(self, args: ReadTaxonomyToolArgs) -> str:
- toolkit = TaxonomyAgentToolkit(self._team, self._user)
+ toolkit = TaxonomyAgentToolkit(self._team, self._user, event_source=self._event_source)
try:
@database_sync_to_async(thread_sensitive=False)
def _execute_query():
- return execute_taxonomy_query(args.query, toolkit, self._team, self._user)
+ return execute_taxonomy_query(
+ args.query, toolkit, self._team, self._user, event_source=self._event_source
+ )
return await _execute_query()
except ValueError as e:
diff --git a/ee/hogai/tools/read_taxonomy/test/test_tool.py b/ee/hogai/tools/read_taxonomy/test/test_tool.py
index c4d3265833fb..fe88630043e1 100644
--- a/ee/hogai/tools/read_taxonomy/test/test_tool.py
+++ b/ee/hogai/tools/read_taxonomy/test/test_tool.py
@@ -5,6 +5,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
from langchain_core.runnables import RunnableConfig
from parameterized import parameterized
+from posthog.event_usage import EventSource
+
from products.posthog_ai.backend.models.assistant import Conversation
from ee.hogai.tool_errors import MaxToolRetryableError
@@ -110,7 +112,9 @@ class TestReadTaxonomyTool(NonAtomicBaseTest):
result = execute_taxonomy_query(ReadEvents(), mock_toolkit_class.return_value, self.team, self.user)
self.assertIn("events:", result)
- mock_format_events.assert_called_once_with([], self.team, self.user, limit=500, offset=0)
+ mock_format_events.assert_called_once_with(
+ [], self.team, self.user, limit=500, offset=0, event_source=EventSource.POSTHOG_AI
+ )
@patch("ee.hogai.tools.read_taxonomy.core.TaxonomyAgentToolkit")
def test_person_entity_properties_include_dynamic_hint(self, mock_toolkit_class):
diff --git a/ee/hogai/utils/helpers.py b/ee/hogai/utils/helpers.py
index e3d251e2ab7b..7a7252c076c3 100644
--- a/ee/hogai/utils/helpers.py
+++ b/ee/hogai/utils/helpers.py
@@ -204,12 +204,14 @@ def _process_events_data(
user: User,
limit: int | None = None,
offset: int | None = None,
+ event_source: EventSource = EventSource.POSTHOG_AI,
) -> tuple[list[dict], dict[str, str], bool]:
"""Common logic for processing events and building event data."""
query = TeamTaxonomyQuery(limit=limit, offset=offset)
response = TeamTaxonomyQueryRunner(query, team, user=user).run(
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
- analytics_props={"source": EventSource.POSTHOG_AI},
+ user=user,
+ analytics_props={"source": event_source},
)
if not isinstance(response, CachedTeamTaxonomyQueryResponse):
@@ -352,8 +354,11 @@ def format_events_yaml(
user: User,
limit: int | None = None,
offset: int | None = None,
+ event_source: EventSource = EventSource.POSTHOG_AI,
) -> str:
- processed_events, _, has_more = _process_events_data(events_in_context, team, user, limit=limit, offset=offset)
+ processed_events, _, has_more = _process_events_data(
+ events_in_context, team, user, limit=limit, offset=offset, event_source=event_source
+ )
formatted_events = ["events:"]
any_not_seen_recently = False
diff --git a/ee/hogai/utils/test/test_format_events_prompt.py b/ee/hogai/utils/test/test_format_events_prompt.py
index b387cd19ccc3..68b71dcfaa9e 100644
--- a/ee/hogai/utils/test/test_format_events_prompt.py
+++ b/ee/hogai/utils/test/test_format_events_prompt.py
@@ -476,6 +476,7 @@ class TestFormatEventsPrompt(BaseTest):
mock_runner_class.assert_called_once_with(TeamTaxonomyQuery(), self.team, user=self.user)
mock_runner_class.return_value.run.assert_called_once_with(
ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE_AND_BLOCKING_ON_MISS,
+ user=self.user,
analytics_props=ANY,
)
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 91e8414eb5aa..ed3a67222cd2 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -4159,6 +4159,10 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
})
posthog.capture('survey created', {
+ // The web app is the only place this event is emitted from — there is no backend
+ // equivalent — so stamping the surface here is what puts surveys in a `source`
+ // breakdown at all, rather than showing up as unattributed.
+ source: 'web',
name: survey.name,
id: survey.id,
survey_type: survey.type,
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index f884ea479b00..e6be21c00639 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -2091,6 +2091,32 @@
],
"label": "Locale"
},
+ "$mcp_auth_failure_reason": {
+ "description": "Why an MCP request was refused, on $mcp_auth_failed: insufficient_scope (the credential is valid but the API denied the call), inactive_oauth_token, invalid_api_key, or unknown. insufficient_scope also carries $mcp_missing_scope when the API named a scope.",
+ "examples": [
+ "insufficient_scope",
+ "invalid_api_key",
+ "inactive_oauth_token"
+ ],
+ "label": "MCP auth failure reason"
+ },
+ "$mcp_auth_method": {
+ "description": "Which credential the MCP request authenticated with, derived from the bearer token's prefix: oauth, personal_api_key, id_jag, none, or unknown. Stamped on every event by PostHog's own MCP server. Use it to tell an OAuth connector apart from an API-key connection \u2014 for example when a user works around a broken OAuth flow by switching to a personal API key.",
+ "examples": [
+ "oauth",
+ "personal_api_key"
+ ],
+ "label": "MCP auth method"
+ },
+ "$mcp_auth_status": {
+ "description": "HTTP status returned to the client when an MCP request was refused (401 for a rejected credential, 403 for a denied scope). Distinct from $mcp_error_status, which is the upstream status of a failed tool call. Only set on $mcp_auth_failed.",
+ "examples": [
+ 401,
+ 403
+ ],
+ "label": "MCP auth status",
+ "type": "Numeric"
+ },
"$mcp_client_name": {
"description": "The MCP client that initiated the connection. Common values are coding agents (Claude Code, Codex) and chat clients (Claude desktop, Claude on web).",
"examples": [
@@ -2227,6 +2253,14 @@
],
"label": "MCP listed tool names"
},
+ "$mcp_missing_scope": {
+ "description": "The API scope the PostHog API said was missing when it refused an MCP request. Only set on $mcp_auth_failed with reason insufficient_scope, and only when the API named a specific scope.",
+ "examples": [
+ "insight:read",
+ "query:read"
+ ],
+ "label": "MCP missing scope"
+ },
"$mcp_mode": {
"description": "Which tool-registration mode the MCP server ran in for this request. 'cli' is single-exec mode (the v2 wrapper that exposes one dispatcher tool taking a `call <tool> ...` command); 'tools' exposes every tool individually.",
"examples": [
@@ -3735,6 +3769,17 @@
"description": "Snapchat Click ID",
"label": "sccid"
},
+ "source": {
+ "description": "Which PostHog surface the work came from. The surface values are 'web' (the app in a browser), 'posthog_ai' (Max), 'desktop' (the PostHog Desktop app), 'mobile' (the PostHog mobile app), 'slack' (the Slack app), 'mcp' (a third-party agent over MCP), 'cli', and 'api' (a direct API call). On API events, PostHog's own surfaces report themselves, so 'mcp' measures other people's agents. The $mcp_* events are stamped by the MCP server instead, which cannot read the OAuth grant that identifies the Desktop app, so a Desktop request can still show as 'mcp' on those. 'posthog_code' covers the headless coding agents: the cloud agent, the local agent, and signals scouts. 'wizard' is the setup agent and 'terraform' is the Terraform provider. Four values are machines rather than surfaces: 'cache_warming', 'alert', 'export', and 'subscription'. Two unrelated properties share this name, so filter to a specific event before breaking down by it. The app also uses 'source' for which control fired an event, with values like 'menu', 'keyboard-shortcut', and 'card_drag_handle'. Some backend paths use it for something else again: 'static' on $http_log, 'blob_v2', 'blob', 'listing' and 'realtime' on the session replay snapshot events, 'mcpcat' on the legacy MCP events, and 'template' or 'custom' on 'mcp_store server installed'. Two surface values also collide with older control names: on 'switched site mode', 'desktop' means the device-mode control rather than the app, and on the AI report events, 'slack' means the delivery channel.",
+ "examples": [
+ "web",
+ "posthog_ai",
+ "mcp",
+ "desktop",
+ "api"
+ ],
+ "label": "Source"
+ },
"token": {
"description": "Token used for authentication.",
"examples": [
@@ -3988,6 +4033,11 @@
"description_llm": "Identifies an anonymous user. The event shows how many users used an account, so do not use it for active users metrics because a user may skip identification.",
"label": "Identify"
},
+ "$mcp_auth_failed": {
+ "description": "Fires when an MCP request is refused before a session is established, because the credential was rejected or lacked a required scope. Emitted by PostHog's own MCP server rather than the SDK, so it is absent for customer-instrumented servers. Carries `$mcp_auth_failure_reason`, `$mcp_auth_method`, and the client identity, so connectors stuck re-authorizing are visible instead of appearing as an absence of traffic. Not a tool-call failure: it never sets `$mcp_is_error`.",
+ "label": "MCP auth failed",
+ "primary_property": "$mcp_auth_failure_reason"
+ },
"$mcp_custom": {
"description": "A custom MCP analytics event emitted by a server through the SDK's custom-event API. Properties depend on what the caller passed.",
"label": "MCP custom event"
@@ -4222,6 +4272,32 @@
}
},
"mcp_properties": {
+ "$mcp_auth_failure_reason": {
+ "description": "Why an MCP request was refused, on $mcp_auth_failed: insufficient_scope (the credential is valid but the API denied the call), inactive_oauth_token, invalid_api_key, or unknown. insufficient_scope also carries $mcp_missing_scope when the API named a scope.",
+ "examples": [
+ "insufficient_scope",
+ "invalid_api_key",
+ "inactive_oauth_token"
+ ],
+ "label": "MCP auth failure reason"
+ },
+ "$mcp_auth_method": {
+ "description": "Which credential the MCP request authenticated with, derived from the bearer token's prefix: oauth, personal_api_key, id_jag, none, or unknown. Stamped on every event by PostHog's own MCP server. Use it to tell an OAuth connector apart from an API-key connection \u2014 for example when a user works around a broken OAuth flow by switching to a personal API key.",
+ "examples": [
+ "oauth",
+ "personal_api_key"
+ ],
+ "label": "MCP auth method"
+ },
+ "$mcp_auth_status": {
+ "description": "HTTP status returned to the client when an MCP request was refused (401 for a rejected credential, 403 for a denied scope). Distinct from $mcp_error_status, which is the upstream status of a failed tool call. Only set on $mcp_auth_failed.",
+ "examples": [
+ 401,
+ 403
+ ],
+ "label": "MCP auth status",
+ "type": "Numeric"
+ },
"$mcp_client_name": {
"description": "The MCP client that initiated the connection. Common values are coding agents (Claude Code, Codex) and chat clients (Claude desktop, Claude on web).",
"examples": [
@@ -4358,6 +4434,14 @@
],
"label": "MCP listed tool names"
},
+ "$mcp_missing_scope": {
+ "description": "The API scope the PostHog API said was missing when it refused an MCP request. Only set on $mcp_auth_failed with reason insufficient_scope, and only when the API named a specific scope.",
+ "examples": [
+ "insight:read",
+ "query:read"
+ ],
+ "label": "MCP missing scope"
+ },
"$mcp_mode": {
"description": "Which tool-registration mode the MCP server ran in for this request. 'cli' is single-exec mode (the v2 wrapper that exposes one dispatcher tool taking a `call <tool> ...` command); 'tools' exposes every tool individually.",
"examples": [
@@ -6947,6 +7031,32 @@
],
"label": "Locale"
},
+ "$mcp_auth_failure_reason": {
+ "description": "Why an MCP request was refused, on $mcp_auth_failed: insufficient_scope (the credential is valid but the API denied the call), inactive_oauth_token, invalid_api_key, or unknown. insufficient_scope also carries $mcp_missing_scope when the API named a scope.",
+ "examples": [
+ "insufficient_scope",
+ "invalid_api_key",
+ "inactive_oauth_token"
+ ],
+ "label": "MCP auth failure reason"
+ },
+ "$mcp_auth_method": {
+ "description": "Which credential the MCP request authenticated with, derived from the bearer token's prefix: oauth, personal_api_key, id_jag, none, or unknown. Stamped on every event by PostHog's own MCP server. Use it to tell an OAuth connector apart from an API-key connection \u2014 for example when a user works around a broken OAuth flow by switching to a personal API key.",
+ "examples": [
+ "oauth",
+ "personal_api_key"
+ ],
+ "label": "MCP auth method"
+ },
+ "$mcp_auth_status": {
+ "description": "HTTP status returned to the client when an MCP request was refused (401 for a rejected credential, 403 for a denied scope). Distinct from $mcp_error_status, which is the upstream status of a failed tool call. Only set on $mcp_auth_failed.",
+ "examples": [
+ 401,
+ 403
+ ],
+ "label": "MCP auth status",
+ "type": "Numeric"
+ },
"$mcp_client_name": {
"description": "The MCP client that initiated the connection. Common values are coding agents (Claude Code, Codex) and chat clients (Claude desktop, Claude on web).",
"examples": [
@@ -7083,6 +7193,14 @@
],
"label": "MCP listed tool names"
},
+ "$mcp_missing_scope": {
+ "description": "The API scope the PostHog API said was missing when it refused an MCP request. Only set on $mcp_auth_failed with reason insufficient_scope, and only when the API named a specific scope.",
+ "examples": [
+ "insight:read",
+ "query:read"
+ ],
+ "label": "MCP missing scope"
+ },
"$mcp_mode": {
"description": "Which tool-registration mode the MCP server ran in for this request. 'cli' is single-exec mode (the v2 wrapper that exposes one dispatcher tool taking a `call <tool> ...` command); 'tools' exposes every tool individually.",
"examples": [
@@ -8586,6 +8704,17 @@
"description": "Snapchat Click ID Data from the last time this user was seen.",
"label": "Latest sccid"
},
+ "source": {
+ "description": "Which PostHog surface the work came from. The surface values are 'web' (the app in a browser), 'posthog_ai' (Max), 'desktop' (the PostHog Desktop app), 'mobile' (the PostHog mobile app), 'slack' (the Slack app), 'mcp' (a third-party agent over MCP), 'cli', and 'api' (a direct API call). On API events, PostHog's own surfaces report themselves, so 'mcp' measures other people's agents. The $mcp_* events are stamped by the MCP server instead, which cannot read the OAuth grant that identifies the Desktop app, so a Desktop request can still show as 'mcp' on those. 'posthog_code' covers the headless coding agents: the cloud agent, the local agent, and signals scouts. 'wizard' is the setup agent and 'terraform' is the Terraform provider. Four values are machines rather than surfaces: 'cache_warming', 'alert', 'export', and 'subscription'. Two unrelated properties share this name, so filter to a specific event before breaking down by it. The app also uses 'source' for which control fired an event, with values like 'menu', 'keyboard-shortcut', and 'card_drag_handle'. Some backend paths use it for something else again: 'static' on $http_log, 'blob_v2', 'blob', 'listing' and 'realtime' on the session replay snapshot events, 'mcpcat' on the legacy MCP events, and 'template' or 'custom' on 'mcp_store server installed'. Two surface values also collide with older control names: on 'switched site mode', 'desktop' means the device-mode control rather than the app, and on the AI report events, 'slack' means the delivery channel.",
+ "examples": [
+ "web",
+ "posthog_ai",
+ "mcp",
+ "desktop",
+ "api"
+ ],
+ "label": "Source"
+ },
"token": {
"description": "Token used for authentication.",
"examples": [
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index 0ddc0d363537..b545a2096e5b 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -1742,6 +1742,7 @@ class IntegrationViewSet(
"reason_length": len(serializer.validated_data["reason"]),
},
team=self.team,
+ request=request,
)
return Response({"success": True})
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 6e5ad72066fa..2c85ea691697 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -317,6 +317,7 @@ def team_default_release_conditions_view(team: Team, request: request.Request) -
request.user,
"default release conditions updated",
{"team_id": team.id, "enabled": enabled, "group_count": len(default_groups)},
+ request=request,
)
return response.Response({"enabled": config.enabled, "default_groups": config.default_groups})
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 4394c163f936..77522a821a9a 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -7,7 +7,7 @@ from urllib.parse import quote, urlencode
import pytest
from posthog.test.base import APIBaseTest
-from unittest.mock import MagicMock, patch
+from unittest.mock import ANY, MagicMock, patch
from django.core.cache import cache
from django.test import override_settings
@@ -5535,6 +5535,7 @@ class TestIntegrationRequestAccessAPI(APIBaseTest):
"reason_length": len("We need Slack alerts"),
},
team=self.team,
+ request=ANY,
)
@parameterized.expand(
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 3d358e862839..a3923b06fc30 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -781,6 +781,10 @@ def add_fallback_query_tags(tags: QueryTags) -> None:
from posthog.event_usage import EventSource
+ # Stays a bare MCP comparison rather than MCP_TRANSPORT_EVENT_SOURCES: this tag's source is
+ # set by the request middleware, which runs before DRF authentication, so the surfaces that
+ # resolve from the OAuth grant (desktop, Slack) can never reach here — MCP traffic always
+ # arrives as plain `mcp`.
if tags.product is None and tags.source == EventSource.MCP:
tags.product = Product.MCP
diff --git a/posthog/event_usage.py b/posthog/event_usage.py
index 3b78b39beeae..50fc3d5422fe 100644
--- a/posthog/event_usage.py
+++ b/posthog/event_usage.py
@@ -18,8 +18,10 @@ from posthog.constants import POSTHOG_INTERNAL_EMAIL_SUFFIX
from posthog.models import Organization, User
from posthog.models.activity_logging.model_activity import is_impersonated_session
from posthog.models.team import Team
+from posthog.oauth_provenance import get_oauth_client_id, is_first_party_oauth_client, is_interactive_desktop_grant
from posthog.settings import SITE_URL
from posthog.synthetic_user import SyntheticUser
+from posthog.temporal.oauth import POSTHOG_AI_OAUTH_APP_CLIENT_IDS
from posthog.utils import get_instance_realm
if TYPE_CHECKING:
@@ -274,11 +276,22 @@ def report_user_organization_membership_level_changed(
class EventSource(StrEnum):
+ """Which PostHog surface a request came from.
+
+ `mcp` means a third-party agent. A PostHog surface that reaches the backend through the
+ MCP server reports itself instead, so "MCP adoption" measures other people's agents.
+ """
+
WEB = "web"
API = "api"
CLI = "cli"
POSTHOG_AI = "posthog_ai"
+ # Headless coding agents: the cloud agent, the local agent, signals scouts. Distinct from
+ # DESKTOP and MOBILE, which are apps a person is sitting in front of.
POSTHOG_CODE = "posthog_code"
+ DESKTOP = "desktop"
+ MOBILE = "mobile"
+ SLACK = "slack"
TERRAFORM = "terraform"
MCP = "mcp"
WIZARD = "wizard"
@@ -292,8 +305,39 @@ class EventSource(StrEnum):
# the harness, not self-reported by the model). Callers use this to hold agent writes to a
# review-then-apply path; the web app has its own confirm UI, and headless callers (raw API keys,
# Terraform) apply in one call.
+#
+# DESKTOP, MOBILE and SLACK belong here for the same reason as the rest: each is a managed channel
+# an LLM drives. Leaving one out drops the review step for that surface with nothing else to
+# signal that it happened.
AGENT_EVENT_SOURCES = frozenset(
- {EventSource.MCP, EventSource.POSTHOG_CODE, EventSource.WIZARD, EventSource.CLI, EventSource.POSTHOG_AI}
+ {
+ EventSource.MCP,
+ EventSource.POSTHOG_CODE,
+ EventSource.DESKTOP,
+ EventSource.MOBILE,
+ EventSource.SLACK,
+ EventSource.WIZARD,
+ EventSource.CLI,
+ EventSource.POSTHOG_AI,
+ }
+)
+
+# Surfaces that reach the backend through the MCP server. Code asking "did this arrive over MCP"
+# must test membership here rather than comparing against EventSource.MCP, which covers third-party
+# agents only and so leaves out every first-party surface. POSTHOG_CODE, DESKTOP and MOBILE are
+# included even though each also calls REST directly, because the overwhelming majority of their
+# traffic arrives over MCP and the direct calls come from the same clients.
+#
+# Only meaningful after DRF authentication, because desktop and Slack resolve from the OAuth grant.
+# Anything reading a source produced before that, such as the request middleware, sees plain MCP.
+MCP_TRANSPORT_EVENT_SOURCES = frozenset(
+ {
+ EventSource.MCP,
+ EventSource.DESKTOP,
+ EventSource.MOBILE,
+ EventSource.SLACK,
+ EventSource.POSTHOG_CODE,
+ }
)
@@ -327,14 +371,64 @@ AnalyticsProps = TypedDict(
_POSTHOG_CODE_UA_RE = re.compile(r"posthog/(code|[\w.-]+\.hog\.dev)")
+# The Electron app's own user-agent, for the calls it makes straight to the REST API. Matched
+# before _POSTHOG_CODE_UA_RE, which would otherwise swallow it along with the headless agents.
+_DESKTOP_UA_TOKEN = "posthog/desktop.hog.dev"
+
+# The companion mobile app, matched ahead of _POSTHOG_CODE_UA_RE for the same reason. It
+# authenticates against the Desktop OAuth applications, so a mobile request that reached MCP
+# without declaring a consumer would resolve as DESKTOP. Nothing routes mobile through the MCP
+# server today, so the user-agent is the only signal that has to carry this surface.
+_MOBILE_UA_TOKEN = "posthog/mobile.hog.dev"
+
+# The MCP server's catch-all consumer, declared by every first-party caller that is neither Slack
+# nor PostHog AI: the cloud coding agent, signals scouts, signal_report, experiments, image_builder,
+# and the local agent PostHog Desktop hosts. That local agent forwards the user's own consented
+# Desktop token, so the OAuth grant cannot separate it from the app it runs inside. The declaration
+# is the only signal that can, which is why it outranks the grant below. The agents are not
+# separable from each other by header alone, so they share POSTHOG_CODE.
+_POSTHOG_CODE_MCP_CONSUMER = "posthog-code"
+
+# Surfaces a caller can declare in `X-Posthog-Mcp-Consumer` when it wraps the MCP server.
+# Honored only when a first-party OAuth application backs the request: the header is set by the
+# caller, so without that gate a third party could declare itself as one of PostHog's own.
+_FIRST_PARTY_MCP_CONSUMER_TO_SOURCE = {
+ "slack": EventSource.SLACK,
+ "posthog_ai": EventSource.POSTHOG_AI,
+ _POSTHOG_CODE_MCP_CONSUMER: EventSource.POSTHOG_CODE,
+}
+
# The wizard appends `program: <id>` to its user-agent so the backend can tell the
# self-driving onboarding program apart from other wizard programs (they all share the
# `posthog/wizard` UA). Used to attribute self-driving-created sources distinctly.
_WIZARD_SELF_DRIVING_PROGRAM_RE = re.compile(r"program:\s*self-driving")
+def _resolve_mcp_surface(request) -> EventSource:
+ """Which surface wrapped the MCP server, for a request the MCP server proxied.
+
+ Ends at MCP, meaning a third-party agent, unless a first-party OAuth application vouches for
+ the request, which is the only signal here a caller can't set for itself.
+
+ A declared consumer outranks the grant, because the agents PostHog Desktop hosts authenticate
+ with the same interactive token the app itself uses. Only a request that declares nothing is
+ resolved from the grant.
+ """
+ if not is_first_party_oauth_client(request):
+ return EventSource.MCP
+ consumer = request.headers.get("X-Posthog-Mcp-Consumer")
+ if consumer in (None, "") and is_interactive_desktop_grant(request):
+ return EventSource.DESKTOP
+ return _FIRST_PARTY_MCP_CONSUMER_TO_SOURCE.get(consumer, EventSource.MCP)
+
+
def get_event_source(request) -> EventSource:
"""Determine the source of an API request for analytics."""
+ # A token minted against the PostHog AI OAuth app is authoritative — the auth
+ # credential can't be spoofed the way UA tokens and X-PostHog-Client can, so it
+ # wins over every header-based branch below.
+ if get_oauth_client_id(request) in POSTHOG_AI_OAUTH_APP_CLIENT_IDS:
+ return EventSource.POSTHOG_AI
user_agent = request.headers.get("user-agent", "") or ""
if not isinstance(user_agent, str):
user_agent = ""
@@ -345,12 +439,20 @@ def get_event_source(request) -> EventSource:
return EventSource.TERRAFORM
if "posthog/wizard" in user_agent:
return EventSource.WIZARD
+ if _DESKTOP_UA_TOKEN in user_agent:
+ return EventSource.DESKTOP
+ if _MOBILE_UA_TOKEN in user_agent:
+ return EventSource.MOBILE
if _POSTHOG_CODE_UA_RE.search(user_agent):
return EventSource.POSTHOG_CODE
+ # The CLI is the one consumer honored without a first-party OAuth application behind it:
+ # it authenticates with a personal API key, so there is no application to vouch for it.
+ # Mis-declaring as the CLI only mislabels analytics — `cli` is already in
+ # AGENT_EVENT_SOURCES, so it buys no extra write latitude.
if user_agent == "posthog-cli" or request.headers.get("X-Posthog-Mcp-Consumer") == "posthog-cli":
return EventSource.CLI
if "posthog/mcp-server" in user_agent or request.headers.get("X-Posthog-Client") == "mcp":
- return EventSource.MCP
+ return _resolve_mcp_surface(request)
# DRF sets successful_authenticator during view dispatch; before that
# (e.g. in middleware), fall back to checking the Django session cookie
# which is available after Django's AuthenticationMiddleware runs.
diff --git a/posthog/oauth_provenance.py b/posthog/oauth_provenance.py
new file mode 100644
index 000000000000..54420ec11554
--- /dev/null
+++ b/posthog/oauth_provenance.py
@@ -0,0 +1,69 @@
+"""Provenance checks on the OAuth credential a request arrived with.
+
+Several first-party surfaces share one OAuth application, so the client id alone can't
+tell them apart. These helpers read the properties that can: which application minted the
+token, whether it carries the server-side-only `internal_run:read` marker, and whether it
+came from a real consent flow.
+
+`posthog.auth` is imported inside the functions rather than at module level: `posthog.auth`
+pulls in enough of the model layer that importing it here would cycle back through
+`posthog.event_usage`, which is one of this module's callers.
+"""
+
+from posthog.models.oauth import OAuthRefreshToken
+from posthog.temporal.oauth import POSTHOG_DESKTOP_OAUTH_CLIENT_IDS
+
+# Minted server-side only, so its presence proves the token was not obtained by a person
+# through the consent flow. See INTERNAL_SCOPES in posthog/temporal/oauth.py.
+INTERNAL_RUN_SCOPE = "internal_run:read"
+
+
+def get_oauth_access_token(request) -> object | None:
+ """The OAuth access token backing this request, or None if it authenticated some other way."""
+ from posthog.auth import OAuthAccessTokenAuthentication # noqa: PLC0415 — circular via posthog.event_usage
+
+ authenticator = getattr(request, "successful_authenticator", None)
+ if not isinstance(authenticator, OAuthAccessTokenAuthentication):
+ return None
+ return getattr(authenticator, "access_token", None)
+
+
+def get_oauth_client_id(request) -> str | None:
+ application = getattr(get_oauth_access_token(request), "application", None)
+ return getattr(application, "client_id", None)
+
+
+def is_first_party_oauth_client(request) -> bool:
+ """Whether the token was minted against an OAuth application PostHog controls.
+
+ The MCP consumer header is caller-settable, so a third party can declare itself `slack`
+ or `posthog_ai`. Requiring one of our own applications is what makes that header
+ trustworthy enough to attribute a surface from.
+ """
+ return get_oauth_client_id(request) in POSTHOG_DESKTOP_OAUTH_CLIENT_IDS
+
+
+def is_interactive_desktop_grant(request) -> bool:
+ """Whether this request carries a PostHog Desktop token a person consented to.
+
+ The Electron app, the cloud coding agent, and the Slack app all authenticate against the
+ same OAuth application, so three things have to line up: that application, the absence of
+ the server-minted `internal_run:read` marker, and refresh-token lineage proving a consent
+ flow happened. Sandbox tokens fail the second check before the third does any query.
+ """
+ access_token = get_oauth_access_token(request)
+ if access_token is None or not is_first_party_oauth_client(request):
+ return False
+ scopes = set((getattr(access_token, "scope", "") or "").split())
+ if INTERNAL_RUN_SCOPE in scopes:
+ return False
+ return _has_authorization_flow_lineage(access_token)
+
+
+def _has_authorization_flow_lineage(access_token: object) -> bool:
+ if getattr(access_token, "source_refresh_token_id", None) is not None:
+ return True
+ access_token_id = getattr(access_token, "id", None)
+ if access_token_id is None:
+ return False
+ return OAuthRefreshToken.objects.filter(access_token_id=access_token_id).exists()
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index fa87cd9a4926..09262d5331a7 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2976,6 +2976,32 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"label": "Is error (unprefixed)",
"description": "Older unprefixed variant of $mcp_is_error. Emitted on events from the pre-@posthog/mcp code paths; prefer $mcp_is_error for new dashboards.",
},
+ "source": {
+ "label": "Source",
+ "description": (
+ "Which PostHog surface the work came from. The surface values are 'web' (the app in a "
+ "browser), 'posthog_ai' (Max), 'desktop' (the PostHog Desktop app), 'mobile' (the PostHog "
+ "mobile app), 'slack' (the Slack app), 'mcp' (a third-party agent over MCP), 'cli', and "
+ "'api' (a direct API call). On API events, PostHog's own surfaces report themselves, so "
+ "'mcp' measures other people's agents. The $mcp_* events are stamped by the MCP server "
+ "instead, which cannot read the OAuth grant that identifies the Desktop app, so a Desktop "
+ "request can still show as 'mcp' on those. "
+ "'posthog_code' covers the headless coding agents: the cloud agent, the local agent, and "
+ "signals scouts. 'wizard' is the setup agent and 'terraform' is the Terraform provider. "
+ "Four values are machines rather than surfaces: 'cache_warming', 'alert', 'export', and "
+ "'subscription'. "
+ "Two unrelated properties share this name, so filter to a specific event before breaking "
+ "down by it. The app also uses 'source' for which control fired an event, with values "
+ "like 'menu', 'keyboard-shortcut', and 'card_drag_handle'. Some backend paths use it for "
+ "something else again: 'static' on $http_log, 'blob_v2', 'blob', 'listing' and 'realtime' "
+ "on the session replay snapshot events, 'mcpcat' on the legacy MCP events, and 'template' "
+ "or 'custom' on 'mcp_store server installed'. Two "
+ "surface values also collide with older control names: on 'switched site mode', "
+ "'desktop' means the device-mode control rather than the app, and on the AI report "
+ "events, 'slack' means the delivery channel."
+ ),
+ "examples": ["web", "posthog_ai", "mcp", "desktop", "api"],
+ },
"mcp_runtime": {
"label": "MCP runtime",
"description": "Server runtime that handled the MCP request. 'hono' means it was served by the Hono-based MCP server.",
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index abbd863c54e8..2ab347f9f0ac 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -53,6 +53,17 @@ SANDBOX_OAUTH_APP_CLIENT_IDS = frozenset(
}
)
+# The dedicated "PostHog AI" OAuth app. Tokens minted against it are only ever created
+# server-side for PostHog AI sandbox agents, so a request bearing one is authoritatively
+# attributable to PostHog AI regardless of spoofable user-agent or client headers.
+POSTHOG_AI_OAUTH_APP_CLIENT_IDS = frozenset(
+ {
+ POSTHOG_AI_APP_CLIENT_ID_US,
+ POSTHOG_AI_APP_CLIENT_ID_EU,
+ POSTHOG_AI_APP_CLIENT_ID_DEV,
+ }
+)
+
McpScopePreset = Literal["read_only", "full", "signals_scout", "signals_scout_reports"]
SandboxOAuthApplication = Literal["array", "posthog_ai"]
diff --git a/posthog/test/test_event_usage.py b/posthog/test/test_event_usage.py
index baec5c3eb8b8..8f3c4cf396a3 100644
--- a/posthog/test/test_event_usage.py
+++ b/posthog/test/test_event_usage.py
@@ -1,4 +1,5 @@
from types import SimpleNamespace
+from typing import cast
import pytest
from posthog.test.base import BaseTest
@@ -7,6 +8,7 @@ from unittest.mock import patch
from parameterized import parameterized
from rest_framework.test import APIRequestFactory
+from posthog.auth import OAuthAccessTokenAuthentication
from posthog.clickhouse.query_tagging import AccessMethod, tags_context
from posthog.event_usage import (
EventSource,
@@ -17,6 +19,27 @@ from posthog.event_usage import (
report_user_signed_up,
sanitize_header_value,
)
+from posthog.models.oauth import OAuthAccessToken
+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV, POSTHOG_AI_APP_CLIENT_ID_DEV
+
+# The MCP server's catch-all consumer, sent by every sandbox agent and by the agent PostHog
+# Desktop hosts locally.
+_POSTHOG_CODE_CONSUMER = "posthog-code"
+
+
+def _oauth_authenticator(
+ client_id: str, *, scope: str = "insight:read", consented: bool = True
+) -> OAuthAccessTokenAuthentication:
+ authenticator = OAuthAccessTokenAuthentication()
+ authenticator.access_token = cast(
+ OAuthAccessToken,
+ SimpleNamespace(
+ application=SimpleNamespace(client_id=client_id),
+ source_refresh_token_id="refresh-token-id" if consented else None,
+ scope=scope,
+ ),
+ )
+ return authenticator
class TestReportUserAction(BaseTest):
@@ -261,7 +284,8 @@ class TestGetEventSource(BaseTest):
("cli_exact", "posthog-cli", EventSource.CLI),
("wizard", "posthog/wizard 1.0", EventSource.WIZARD),
("posthog_code", "posthog/code 1.2.3", EventSource.POSTHOG_CODE),
- ("hog_dev_subdomain", "posthog/desktop.hog.dev 0.1.0", EventSource.POSTHOG_CODE),
+ ("desktop_app_direct", "posthog/desktop.hog.dev 0.1.0", EventSource.DESKTOP),
+ ("mobile_app_direct", "posthog/mobile.hog.dev; version: 1.4.0", EventSource.MOBILE),
("hog_dev_complex", "posthog/my-app.hog.dev", EventSource.POSTHOG_CODE),
("mcp_server", "posthog/mcp-server 1.0", EventSource.MCP),
("unknown_ua_falls_through_to_api", "some-random-agent/1.0", EventSource.API),
@@ -295,10 +319,81 @@ class TestGetEventSource(BaseTest):
request = factory.get("/fake", HTTP_X_POSTHOG_CLIENT="mcp")
assert get_event_source(request) == EventSource.MCP
+ def test_posthog_ai_oauth_app_beats_the_mcp_header(self):
+ request = SimpleNamespace(
+ META={},
+ headers={"X-Posthog-Client": "mcp"},
+ successful_authenticator=_oauth_authenticator(POSTHOG_AI_APP_CLIENT_ID_DEV),
+ )
+ assert get_event_source(request) == EventSource.POSTHOG_AI
+
+ @parameterized.expand(
+ [
+ # A first-party caller that declares no consumer is resolved from the grant alone, and
+ # only a token a person consented to in the browser is the interactive app.
+ ("consented_grant_is_the_app", "insight:read", True, EventSource.DESKTOP),
+ ("server_minted_token_is_not_the_app", "insight:read internal_run:read", True, EventSource.MCP),
+ ("no_consent_flow_behind_the_token", "insight:read", False, EventSource.MCP),
+ ]
+ )
+ def test_undeclared_first_party_consumer_resolves_from_the_grant(self, _name, scope, consented, expected):
+ request = SimpleNamespace(
+ META={},
+ headers={"X-Posthog-Client": "mcp"},
+ successful_authenticator=_oauth_authenticator(ARRAY_APP_CLIENT_ID_DEV, scope=scope, consented=consented),
+ )
+ assert get_event_source(request) == expected
+
+ def test_authenticator_without_access_token_falls_through_to_mcp(self):
+ request = SimpleNamespace(
+ META={}, headers={"X-Posthog-Client": "mcp"}, successful_authenticator=SimpleNamespace()
+ )
+ assert get_event_source(request) == EventSource.MCP
+
+ @parameterized.expand(
+ [
+ # The agent PostHog Desktop hosts locally authenticates with the same consented token
+ # as the app around it, so the declared consumer is what tells them apart. A grant that
+ # would otherwise read as the interactive app must not override it.
+ ("local_agent_in_desktop", _POSTHOG_CODE_CONSUMER, "insight:read", True, EventSource.POSTHOG_CODE),
+ ("sandbox_agent", _POSTHOG_CODE_CONSUMER, "insight:read internal_run:read", True, EventSource.POSTHOG_CODE),
+ ("slack_app", "slack", "insight:read internal_run:read", True, EventSource.SLACK),
+ ("posthog_ai_agent", "posthog_ai", "insight:read internal_run:read", True, EventSource.POSTHOG_AI),
+ ("unrecognized_consumer", "ops-agent", "insight:read internal_run:read", True, EventSource.MCP),
+ ]
+ )
+ def test_first_party_mcp_consumer_resolves_to_its_surface(self, _name, consumer, scope, consented, expected):
+ request = SimpleNamespace(
+ META={},
+ headers={"X-Posthog-Client": "mcp", "X-Posthog-Mcp-Consumer": consumer},
+ successful_authenticator=_oauth_authenticator(ARRAY_APP_CLIENT_ID_DEV, scope=scope, consented=consented),
+ )
+ assert get_event_source(request) == expected
+
+ def test_third_party_oauth_app_cannot_declare_a_posthog_surface(self):
+ # `X-Posthog-Mcp-Consumer` is set by the caller, so the first-party OAuth application is
+ # what makes it trustworthy. Without one, a self-declared surface must not be honored.
+ request = SimpleNamespace(
+ META={},
+ headers={"X-Posthog-Client": "mcp", "X-Posthog-Mcp-Consumer": "slack"},
+ successful_authenticator=_oauth_authenticator("some-third-party-client-id"),
+ )
+ assert get_event_source(request) == EventSource.MCP
+
+ def test_mcp_server_only_emits_sources_this_enum_knows(self):
+ # The MCP server stamps the same `source` property on its own events, so a value it emits
+ # that is not an EventSource drops out of every breakdown that joins the two. This list is
+ # EVENT_SOURCE in `services/mcp/src/lib/event-source.ts`, which its own test pins; removing
+ # a surface here without removing it there fails this.
+ mcp_server_sources = {"mcp", "cli", "wizard", "slack", "posthog_ai", "posthog_code"}
+ assert mcp_server_sources <= {source.value for source in EventSource}
+
@parameterized.expand(
[
("posthog_cli_consumer_is_cli", "posthog-cli", EventSource.CLI),
- ("other_consumer_stays_mcp", "slack", EventSource.MCP),
+ ("unvouched_slack_stays_mcp", "slack", EventSource.MCP),
+ ("unvouched_posthog_ai_stays_mcp", "posthog_ai", EventSource.MCP),
+ ("unvouched_posthog_code_stays_mcp", "posthog-code", EventSource.MCP),
]
)
def test_mcp_consumer_header_source(self, _name, consumer, expected):
diff --git a/products/ai_observability/backend/api/clustering_job.py b/products/ai_observability/backend/api/clustering_job.py
index 1a0f481314f8..20d0022bc640 100644
--- a/products/ai_observability/backend/api/clustering_job.py
+++ b/products/ai_observability/backend/api/clustering_job.py
@@ -138,6 +138,7 @@ class ClusteringJobViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
"defaults_disabled": disabled_count,
},
team=self.team,
+ request=self.request,
)
@llma_track_latency("llma_clustering_job_update")
@@ -158,6 +159,7 @@ class ClusteringJobViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
"llma clustering job updated",
{"job_id": instance.id, "name": instance.name},
team=self.team,
+ request=self.request,
)
@llma_track_latency("llma_clustering_job_destroy")
@@ -169,5 +171,6 @@ class ClusteringJobViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
"llma clustering job deleted",
{"job_id": instance.id, "name": instance.name},
team=self.team,
+ request=request,
)
return super().destroy(request, *args, **kwargs)
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 75cd90c9a07b..14e0bb778826 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -875,6 +875,7 @@ def _test_hog_over_sessions(
"condition_count": len(conditions),
},
team=team,
+ request=request,
)
if not results:
diff --git a/products/cdp/backend/api/test/test_hog_function_drafts.py b/products/cdp/backend/api/test/test_hog_function_drafts.py
index c69f6e557554..0d6d0535a5a4 100644
--- a/products/cdp/backend/api/test/test_hog_function_drafts.py
+++ b/products/cdp/backend/api/test/test_hog_function_drafts.py
@@ -86,6 +86,28 @@ class TestHogFunctionDrafts(DraftTestCase):
mock_reload.assert_not_called()
assert HogFunction.objects.get(id=function_id).hog == LIVE_HOG
+ @parameterized.expand(
+ [
+ ("desktop_app", "posthog/desktop.hog.dev; version: 1.0"),
+ ("mobile_app", "posthog/mobile.hog.dev; version: 1.0"),
+ ]
+ )
+ def test_first_party_app_edit_also_stages_a_draft(self, _name: str, user_agent: str):
+ # These reach REST under their own user-agent rather than through the MCP header, so the
+ # review gate depends on their membership in AGENT_EVENT_SOURCES. Dropping either would
+ # apply an agent's edit straight to a running function with nothing else to signal it.
+ function_id = self._create()
+
+ with patch(RELOAD_PATH) as mock_reload:
+ response = self.client.patch(
+ self._url(function_id), {"hog": EDITED_HOG}, headers={"user-agent": user_agent}
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["draft"]["hog"] == EDITED_HOG
+ mock_reload.assert_not_called()
+ assert HogFunction.objects.get(id=function_id).hog == LIVE_HOG
+
@parameterized.expand(
[
# An agent can't stage a draft on a function that isn't running, and the web builder
diff --git a/products/customer_analytics/backend/presentation/views/announcements.py b/products/customer_analytics/backend/presentation/views/announcements.py
index 29abd52ebfa9..2dab0561a9eb 100644
--- a/products/customer_analytics/backend/presentation/views/announcements.py
+++ b/products/customer_analytics/backend/presentation/views/announcements.py
@@ -186,6 +186,7 @@ class AnnouncementViewSet(
"customer analytics announcement created",
{"id": str(announcement.id), "channel_count": announcement.total_channels},
team=self.team,
+ request=request,
)
return Response(AnnouncementSerializer(instance=announcement).data, status=status.HTTP_201_CREATED)
diff --git a/products/dashboards/backend/api/dashboard_templates.py b/products/dashboards/backend/api/dashboard_templates.py
index 3d6f705ea68d..53a7d581d123 100644
--- a/products/dashboards/backend/api/dashboard_templates.py
+++ b/products/dashboards/backend/api/dashboard_templates.py
@@ -488,6 +488,7 @@ class DashboardTemplateViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, views
},
team=self.team,
organization=self.organization,
+ request=self.request,
)
def perform_update(self, serializer):
@@ -508,6 +509,7 @@ class DashboardTemplateViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, views
},
team=self.team,
organization=self.organization,
+ request=self.request,
)
@method_decorator(cache_page(60 * 2)) # cache for 2 minutes
@@ -607,6 +609,7 @@ class DashboardTemplateViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, views
},
team=self.team,
organization=self.organization,
+ request=request,
)
serializer = DashboardTemplateSerializer(new_instance, context=self.get_serializer_context())
diff --git a/products/endpoints/backend/presentation/views/api.py b/products/endpoints/backend/presentation/views/api.py
index 2ba41e461f5a..32f7d5ef4865 100644
--- a/products/endpoints/backend/presentation/views/api.py
+++ b/products/endpoints/backend/presentation/views/api.py
@@ -737,6 +737,7 @@ class EndpointViewSet(
"original_reason": result.original_reason,
},
team=self.team,
+ request=request,
)
return Response(
diff --git a/products/experiments/backend/experiment_summary_data_service.py b/products/experiments/backend/experiment_summary_data_service.py
index df1023ff3e51..ae66abc5aab7 100644
--- a/products/experiments/backend/experiment_summary_data_service.py
+++ b/products/experiments/backend/experiment_summary_data_service.py
@@ -208,6 +208,7 @@ class ExperimentSummaryDataService:
)
result = query_runner.run(
execution_mode=execution_mode,
+ user=self._user,
analytics_props={"source": EventSource.POSTHOG_AI},
)
refresh_time = getattr(result, "last_refresh", None)
@@ -257,10 +258,13 @@ class ExperimentSummaryDataService:
query=exposure_query,
team=experiment.team,
limit_context=LimitContext.QUERY_ASYNC,
+ # Runs for the requesting Max user, so warehouse access is enforced against them.
+ user=self._user,
error_event_context="agent",
)
exposure_result = exposure_runner.run(
execution_mode=execution_mode,
+ user=self._user,
analytics_props={"source": EventSource.POSTHOG_AI},
)
diff --git a/products/logs/backend/presentation/views/alerts_api.py b/products/logs/backend/presentation/views/alerts_api.py
index dee3a3403c1b..b229da1c499d 100644
--- a/products/logs/backend/presentation/views/alerts_api.py
+++ b/products/logs/backend/presentation/views/alerts_api.py
@@ -976,6 +976,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
request.user,
"logs alert destination created",
{"alert_id": str(alert.id), "type": data["type"], "event_kinds": list(EVENT_KINDS)},
+ request=request,
)
response = LogsAlertDestinationResponseSerializer({"hog_function_ids": [hf.id for hf in hog_functions]})
return Response(response.data, status=201)
@@ -1004,6 +1005,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
request.user,
"logs alert destination deleted",
{"alert_id": str(alert.id), "count": len(hog_function_ids)},
+ request=request,
)
return Response(status=204)
@@ -1091,7 +1093,7 @@ class LogsAlertViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
],
),
)
- report_user_action(request.user, "logs alert reset", {"alert_id": str(alert.id)})
+ report_user_action(request.user, "logs alert reset", {"alert_id": str(alert.id)}, request=request)
return Response(self.get_serializer(alert).data)
@extend_schema(
diff --git a/products/mcp_store/backend/presentation/gateway_views.py b/products/mcp_store/backend/presentation/gateway_views.py
index 0645d6932f82..0a67173b0da4 100644
--- a/products/mcp_store/backend/presentation/gateway_views.py
+++ b/products/mcp_store/backend/presentation/gateway_views.py
@@ -957,6 +957,7 @@ class MCPGatewayServerViewSet(
"is_team_enabled": server.is_team_enabled,
},
team=self.team,
+ request=self.request,
)
def perform_destroy(self, instance: MCPGatewayServer) -> None:
@@ -977,6 +978,7 @@ class MCPGatewayServerViewSet(
"mcp_gateway server removed",
properties=properties,
team=self.team,
+ request=self.request,
)
def _resolve_scope(self, data: dict) -> tuple[str, User | None, MCPServiceAccount | None]:
@@ -1128,6 +1130,7 @@ class MCPGatewayServerViewSet(
"mcp_gateway server toggled",
properties={"server_url": server.url, "enabled": enabled},
team=self.team,
+ request=request,
)
return Response(MCPGatewayServerSerializer(server, context=self.get_serializer_context()).data)
@@ -1191,6 +1194,7 @@ class MCPGatewayServerViewSet(
"tool_count": len(data["policies"]),
},
team=self.team,
+ request=request,
)
rows = self._resolve_policies_for_scope(server, scope_type, scope_user, scope_account)
@@ -1262,6 +1266,7 @@ class MCPServiceAccountViewSet(
"mcp_gateway agent updated",
properties={"handle": account.handle, "status": account.status},
team=self.team,
+ request=self.request,
)
@validated_request(
@@ -1384,6 +1389,7 @@ class MCPServiceAccountViewSet(
"all_members": bool(data.get("all")),
},
team=self.team,
+ request=request,
)
prefetch_related_objects([account], self._server_access_prefetch())
return Response(MCPServiceAccountSerializer(account, context=self.get_serializer_context()).data)
@@ -1410,6 +1416,7 @@ class MCPOrgRuleViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewsets.Mode
"mcp_gateway rule created",
properties={"rule_name": rule.name, "effect": rule.effect},
team=self.team,
+ request=self.request,
)
def perform_update(self, serializer: serializers.BaseSerializer) -> None:
@@ -1420,6 +1427,7 @@ class MCPOrgRuleViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewsets.Mode
"mcp_gateway rule updated",
properties={"rule_name": rule.name, "enabled": rule.enabled},
team=self.team,
+ request=self.request,
)
def perform_destroy(self, instance: MCPOrgRule) -> None:
@@ -1429,6 +1437,7 @@ class MCPOrgRuleViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewsets.Mode
"mcp_gateway rule deleted",
properties={"rule_name": instance.name},
team=self.team,
+ request=self.request,
)
instance.delete()
@@ -1540,6 +1549,7 @@ class MCPGatewayConfigViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewset
"mcp_gateway custom servers toggled",
properties={"allow_custom_servers": data["allow_custom_servers"]},
team=self.team,
+ request=request,
)
if "allow_member_agent_access" in data:
report_user_action(
@@ -1547,6 +1557,7 @@ class MCPGatewayConfigViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewset
"mcp_gateway member agent access toggled",
properties={"allow_member_agent_access": data["allow_member_agent_access"]},
team=self.team,
+ request=request,
)
return Response(self._serialize_config(config))
@@ -1571,6 +1582,7 @@ class MCPGatewayConfigViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewset
"mcp_gateway all servers toggled",
properties={"enabled": enabled},
team=self.team,
+ request=request,
)
return Response(self._serialize_config(config))
@@ -1596,6 +1608,7 @@ class MCPGatewayConfigViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewset
"mcp_gateway preset applied",
properties={"audience": audience, "preset": preset},
team=self.team,
+ request=request,
)
return Response(self._serialize_config(config))
@@ -1703,5 +1716,6 @@ class MCPGatewayMemberViewSet(GatewayAdminMixin, TeamAndOrgViewSetMixin, viewset
"mcp_gateway member access changed",
properties={"server_name": server.name, "enabled": data["enabled"]},
team=self.team,
+ request=request,
)
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/mcp_store/backend/presentation/views.py b/products/mcp_store/backend/presentation/views.py
index fbcd3a4ac6d2..c73ec393078a 100644
--- a/products/mcp_store/backend/presentation/views.py
+++ b/products/mcp_store/backend/presentation/views.py
@@ -836,6 +836,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"mcp_store install blocked",
properties={"server_url": url, "reason": reason},
team=self.team,
+ request=self.request,
)
raise PermissionDenied("This server is disabled for your team.")
@@ -952,6 +953,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"auth_type": installation.auth_type,
},
team=self.team,
+ request=request,
)
installation.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
@@ -1027,6 +1029,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"is_enabled": data["is_enabled"],
},
team=self.team,
+ request=request,
)
for field, value in data.items():
@@ -1084,6 +1087,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"auth_type": installation.auth_type,
},
team=self.team,
+ request=request,
)
return Response(self.get_serializer(installation).data)
@@ -1132,6 +1136,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"auth_type": installation.auth_type,
},
team=self.team,
+ request=request,
)
return Response(self.get_serializer(installation).data)
@@ -1381,6 +1386,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"source": "template",
},
team=self.team,
+ request=request,
)
result = MCPServerInstallationSerializer(installation, context=self.get_serializer_context())
return Response(result.data, status=status.HTTP_201_CREATED)
@@ -1501,6 +1507,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"install_source": install_source,
},
team=self.team,
+ request=request,
)
return Response({"redirect_url": authorize_url}, status=status.HTTP_200_OK)
@@ -1593,6 +1600,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"source": "custom",
},
team=self.team,
+ request=request,
)
result_serializer = MCPServerInstallationSerializer(installation, context=self.get_serializer_context())
@@ -1911,6 +1919,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"install_source": install_source,
},
team=self.team,
+ request=request,
)
return _oauth_authorize_response(authorize_url, install_source)
@@ -2128,6 +2137,7 @@ class MCPServerInstallationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet
"approval_state": new_state,
},
team=self.team,
+ request=request,
)
return Response(
@@ -2241,6 +2251,7 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):
"install_source": install_source,
},
team=installation.team,
+ request=request,
)
return self._build_oauth_redirect(
install_source,
@@ -2284,6 +2295,7 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):
"install_source": install_source,
},
team=installation.team,
+ request=request,
)
return self._build_oauth_redirect(
install_source,
@@ -2316,6 +2328,7 @@ class MCPOAuthRedirectViewSet(viewsets.ViewSet):
"source": "template" if template else "custom",
},
team=installation.team,
+ request=request,
)
return self._build_oauth_redirect(
diff --git a/products/posthog_ai/backend/api/mcp_tools.py b/products/posthog_ai/backend/api/mcp_tools.py
index a52291fc7e50..33920012c24e 100644
--- a/products/posthog_ai/backend/api/mcp_tools.py
+++ b/products/posthog_ai/backend/api/mcp_tools.py
@@ -22,6 +22,7 @@ from posthog.api.documentation import _FallbackSerializer
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.clickhouse.query_tagging import Feature, tags_context
+from posthog.event_usage import get_event_source
from posthog.models.user import User
from posthog.renderers import SafeJSONRenderer
@@ -125,7 +126,9 @@ class MCPToolsViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
Scopes are resolved dynamically per tool via dangerously_get_required_scopes.
"""
- tool = mcp_tool_registry.get(tool_name, team=self.team, user=cast(User, request.user))
+ tool = mcp_tool_registry.get(
+ tool_name, team=self.team, user=cast(User, request.user), event_source=get_event_source(request)
+ )
if tool is None:
return Response(
{"success": False, "content": f"Tool '{tool_name}' not found"},
diff --git a/products/posthog_ai/backend/api/test_mcp_tools.py b/products/posthog_ai/backend/api/test_mcp_tools.py
index 047b43210c0b..5cce7be3ed3c 100644
--- a/products/posthog_ai/backend/api/test_mcp_tools.py
+++ b/products/posthog_ai/backend/api/test_mcp_tools.py
@@ -1,8 +1,13 @@
+from datetime import UTC, datetime
+
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
from rest_framework import status
+from posthog.schema import CachedTeamTaxonomyQueryResponse
+
+from posthog.event_usage import EventSource
from posthog.models import Organization, Team
@@ -67,6 +72,31 @@ class TestMCPToolsAPI(APIBaseTest):
self.assertIn("test_event", data["content"])
mock_execute.assert_called_once()
+ @patch("ee.hogai.utils.helpers.TeamTaxonomyQueryRunner")
+ def test_invoke_read_taxonomy_attributes_query_executed_to_user_and_mcp_source(self, mock_runner_cls):
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ mock_runner_cls.return_value.run.return_value = CachedTeamTaxonomyQueryResponse(
+ cache_key="cache_key",
+ is_cached=True,
+ last_refresh=now,
+ next_allowed_client_refresh=now,
+ results=[],
+ timezone="UTC",
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/mcp_tools/read_taxonomy/",
+ {"args": {"query": {"kind": "events"}}},
+ format="json",
+ headers={"X-PostHog-Client": "mcp"},
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertTrue(response.json()["success"])
+ run_kwargs = mock_runner_cls.return_value.run.call_args.kwargs
+ self.assertEqual(run_kwargs["user"], self.user)
+ self.assertEqual(run_kwargs["analytics_props"], {"source": EventSource.MCP})
+
@patch("ee.hogai.tools.execute_sql.mcp_tool.ExecuteSQLMCPTool.execute", new_callable=AsyncMock)
def test_invoke_tool_error_returns_error_response(self, mock_execute):
from ee.hogai.tool_errors import MaxToolRetryableError
diff --git a/products/pulse/backend/api/brief.py b/products/pulse/backend/api/brief.py
index a6049d235832..3ea0454df48e 100644
--- a/products/pulse/backend/api/brief.py
+++ b/products/pulse/backend/api/brief.py
@@ -292,6 +292,7 @@ class BriefConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"pulse config created",
{"config_id": str(instance.id)},
team=self.team,
+ request=self.request,
)
def perform_destroy(self, instance: BriefConfig) -> None:
@@ -302,6 +303,7 @@ class BriefConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"pulse config deleted",
{"config_id": str(instance.id)},
team=self.team,
+ request=self.request,
)
@@ -425,6 +427,7 @@ class ProductBriefViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet)
"pulse brief generation contended",
{"config_id": str(config.id) if config else None},
team=self.team,
+ request=request,
)
try:
brief.delete()
@@ -455,5 +458,6 @@ class ProductBriefViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet)
"pulse brief generated",
{"config_id": str(config.id) if config else None, "period": period, "trigger": "on_demand"},
team=self.team,
+ request=request,
)
return Response(ProductBriefSerializer(brief).data, status=status.HTTP_201_CREATED)
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index b51b4d406a4c..da61a46d5ab2 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -2299,6 +2299,7 @@ class SignalReportViewSet(
},
team=self.team,
organization=self.organization,
+ request=request,
)
return self._refund_response(refund)
diff --git a/products/tasks/backend/facade/client_provenance.py b/products/tasks/backend/facade/client_provenance.py
index 0fb69160b293..c39d48c2a812 100644
--- a/products/tasks/backend/facade/client_provenance.py
+++ b/products/tasks/backend/facade/client_provenance.py
@@ -1,31 +1,11 @@
from rest_framework.request import Request
-from posthog.auth import OAuthAccessTokenAuthentication
-from posthog.models.oauth import OAuthRefreshToken
-from posthog.temporal.oauth import POSTHOG_DESKTOP_OAUTH_CLIENT_IDS
+from posthog.oauth_provenance import is_interactive_desktop_grant
from products.tasks.backend.models import TaskClientProvenance
def get_task_client_provenance(request: Request) -> TaskClientProvenance | None:
- authenticator = getattr(request, "successful_authenticator", None)
- if not isinstance(authenticator, OAuthAccessTokenAuthentication):
- return None
-
- access_token = getattr(authenticator, "access_token", None)
- application = getattr(access_token, "application", None)
- scopes = set((getattr(access_token, "scope", "") or "").split())
- if application is None or "internal_run:read" in scopes or not _has_authorization_flow_lineage(access_token):
- return None
- if application.client_id in POSTHOG_DESKTOP_OAUTH_CLIENT_IDS:
+ if is_interactive_desktop_grant(request):
return TaskClientProvenance.POSTHOG_DESKTOP
return None
-
-
-def _has_authorization_flow_lineage(access_token: object) -> bool:
- if getattr(access_token, "source_refresh_token_id", None) is not None:
- return True
- access_token_id = getattr(access_token, "id", None)
- if access_token_id is None:
- return False
- return OAuthRefreshToken.objects.filter(access_token_id=access_token_id).exists()
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index fa98fa660860..4499c1e26ea2 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -2114,13 +2114,18 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
# It avoids a second live credential round-trip — and the confusing failure mode where the
# first check passes but a transient blip fails the second, leaving nothing created.
- # The setup wizard and PostHog Desktop drive creation through the MCP tools, which inject
- # `created_via=mcp` before the request reaches us — the agent can't set the field itself.
- # Upgrade that machine-injected value when the transport identifies one of them, so their
- # runs are distinguishable from other MCP clients. Explicit `web`/`api` values are left alone.
+ # The setup wizard and PostHog's agent surfaces drive creation through the MCP tools, which
+ # inject `created_via=mcp` before the request reaches us — the agent can't set the field
+ # itself. Upgrade that machine-injected value when the transport identifies one of them, so
+ # their runs are distinguishable from other MCP clients. Explicit `web`/`api` values are
+ # left alone. The PostHog apps and the headless agents all map to `self_driving`: the
+ # distinction between them is an analytics one, and splitting it here would need a new
+ # stored value.
if created_via == ExternalDataSource.CreatedVia.MCP:
transport_created_via = {
EventSource.WIZARD: ExternalDataSource.CreatedVia.WIZARD,
+ EventSource.DESKTOP: ExternalDataSource.CreatedVia.SELF_DRIVING,
+ EventSource.MOBILE: ExternalDataSource.CreatedVia.SELF_DRIVING,
EventSource.POSTHOG_CODE: ExternalDataSource.CreatedVia.SELF_DRIVING,
}
created_via = transport_created_via.get(get_event_source(request), created_via)
diff --git a/products/web_analytics/backend/max_tools.py b/products/web_analytics/backend/max_tools.py
index f0f7f298e55a..bb161b17cbe3 100644
--- a/products/web_analytics/backend/max_tools.py
+++ b/products/web_analytics/backend/max_tools.py
@@ -138,7 +138,7 @@ class WebAnalyticsFilterOptionsToolkit(TaxonomyAgentToolkit):
query=PropertyValuesQuery(property_type=PropertyType.EVENT, property_key=property_name),
user=self._user,
)
- response = runner.run(ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ response = runner.run(ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE, user=self._user)
return [item.name for item in getattr(response, "results", []) or []]
diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.ts
index 55e85370ceca..67672bd24ee8 100644
--- a/services/mcp/src/hono/analytics.ts
+++ b/services/mcp/src/hono/analytics.ts
@@ -5,6 +5,8 @@ import type { MCPAnalyticsIntentSource } from '@posthog/mcp-analytics'
import type { McpAuthFailure } from '@/lib/auth-errors'
import { classifyAuthMethod } from '@/lib/auth-method'
import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION, PRODUCT_DATA_CATALOG_FLAG } from '@/lib/constants'
+import { resolveEventSource } from '@/lib/event-source'
+import { gatewayServerSlug, isGatewayToolName, THIRD_PARTY_TOOL_CATEGORY } from '@/lib/gateway-tools'
import { getPostHogClient } from '@/lib/posthog'
import {
buildMCPAnalyticsGroups,
@@ -14,7 +16,6 @@ import {
} from '@/lib/posthog/analytics'
import type { RequestProperties } from '@/lib/request-properties'
import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'
-import { gatewayServerSlug, isGatewayToolName, THIRD_PARTY_TOOL_CATEGORY } from '@/lib/gateway-tools'
import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolCategory, getToolDescription } from '@/tools/toolDefinitions'
import { buildMCPSessionAnalyticsProperties, getEffectiveMCPClientIdentity } from './mcp-context'
@@ -39,6 +40,15 @@ function buildBaseProperties(
const properties: Record<string, unknown> = {
$ai_product: 'mcp',
+ // The same property `posthog/event_usage.py` stamps on product events, so an MCP call
+ // and the API work it causes land in one breakdown. Distinct from `$mcp_source`, which
+ // names the emitting SDK rather than the surface.
+ source: resolveEventSource({
+ mcpConsumer: clientIdentity.mcpConsumer,
+ clientUserAgent: requestContext.clientUserAgent,
+ apiKeyScopes: state.apiKeyScopes,
+ oauthClientId: state.oauthClientId,
+ }),
$mcp_source: MCP_ANALYTICS_SOURCE,
$mcp_server_name: MCP_SERVER_NAME,
$mcp_server_version: MCP_SERVER_VERSION,
@@ -380,6 +390,12 @@ export function trackAuthFailure(props: RequestProperties, failure: McpAuthFailu
event: '$mcp_auth_failed',
properties: {
$ai_product: 'mcp',
+ // Resolved without scopes — the request never authenticated, so nothing can
+ // vouch for a declared consumer and anything unproven lands as `mcp`.
+ source: resolveEventSource({
+ mcpConsumer: props.mcpConsumer,
+ clientUserAgent: props.clientUserAgent,
+ }),
$mcp_source: MCP_ANALYTICS_SOURCE,
$mcp_server_name: MCP_SERVER_NAME,
$mcp_server_version: MCP_SERVER_VERSION,
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index aa4328550f09..5f7e2b636e72 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -12,12 +12,12 @@ import {
import type { RequestProperties } from '@/lib/request-properties'
import { filterStaffOnlyTools } from '@/lib/staff-only-tools'
import type { McpMode } from '@/lib/utils'
-import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'
import { TASKS_CONTEXT_TOOL_NAMES } from '@/tools/tasksContext'
+import { getRequiredFeatureFlags, getScopeGatedTools, type ScopeGatedTool } from '@/tools/toolDefinitions'
import type { Context, Tool, Env, ZodObjectAny } from '@/tools/types'
-import type { RedisLike } from './cache/RedisCache'
import { McpSessionRedisStore } from './cache/McpSessionRedisStore'
+import type { RedisLike } from './cache/RedisCache'
import {
buildMCPRequestContext,
getEffectiveMCPClientContext,
@@ -35,6 +35,7 @@ export interface ResolvedState {
useSingleExec: boolean
toolFeatureFlags: EvaluatedFlags | undefined
apiKeyScopes: string[]
+ oauthClientId: string | undefined
clientProfile: MCPClientProfile
requestContext: MCPRequestContext
sessionContext: MCPSessionContext | null
@@ -167,6 +168,7 @@ export class RequestStateResolver {
const toolFeatureFlags = Object.fromEntries(flagKeysForState.map((k) => [k, mergedFlags[k]]))
const oauthClientName = (await reqCtx.tokenCache.get('clientName')) || undefined
+ const oauthClientId = (await reqCtx.tokenCache.get('oauthClientId')) || undefined
const clientProfile = new MCPClientProfile({
clientName: clientContext.mcpClientName,
@@ -236,6 +238,7 @@ export class RequestStateResolver {
useSingleExec,
toolFeatureFlags,
apiKeyScopes,
+ oauthClientId,
clientProfile,
requestContext,
sessionContext,
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index c7e2b54a0729..a551e4e1eded 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -1,4 +1,5 @@
import type { ApiClient, GroupType } from '@/api/client'
+import type { Schemas } from '@/api/generated'
import { hasScope } from '@/lib/api'
import type { ScopedCache } from '@/lib/cache/ScopedCache'
import {
@@ -11,7 +12,6 @@ import {
import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'
import { getPostHogClient } from '@/lib/posthog'
import { sanitizeHeaderValue } from '@/lib/utils'
-import type { Schemas } from '@/api/generated'
import type { ApiUser } from '@/schema/api'
import type { CachedOrg, CachedProject, CachedUser, State } from '@/tools/types'
@@ -73,7 +73,14 @@ export class StateManager {
throw new Error(ErrorCode.INACTIVE_OAUTH_TOKEN)
}
- const { scope, scoped_teams, scoped_organizations, client_name } = introspectionResult.data
+ const { scope, scoped_teams, scoped_organizations, client_name, client_id } = introspectionResult.data
+
+ // Which OAuth application minted this token. Introspection is server-derived, so unlike
+ // the consumer header the caller cannot set it, which is what makes it usable as the
+ // first-party gate in `resolveEventSource`. Django gates on the same id set.
+ if (client_id) {
+ await this._cache.set('oauthClientId', client_id)
+ }
const sanitizedClientName = sanitizeHeaderValue(client_name)
if (sanitizedClientName) {
diff --git a/services/mcp/src/lib/event-source.ts b/services/mcp/src/lib/event-source.ts
new file mode 100644
index 000000000000..06bc81b24154
--- /dev/null
+++ b/services/mcp/src/lib/event-source.ts
@@ -0,0 +1,111 @@
+// Which PostHog surface a request came from, stamped as `source` so the MCP server's own
+// events sit in the same breakdown as the product events they cause.
+//
+// The vocabulary is Django's: `EventSource` in `posthog/event_usage.py` owns it, and this is a
+// subset. `tests/event-source.test.ts` pins the values below, and the API holds the same list in
+// `test_mcp_server_only_emits_sources_this_enum_knows`, so a surface added on one side alone fails
+// on the other.
+
+import { POSTHOG_CODE_CONSUMER } from './client-detection'
+
+export const EVENT_SOURCE = {
+ MCP: 'mcp',
+ CLI: 'cli',
+ WIZARD: 'wizard',
+ SLACK: 'slack',
+ POSTHOG_AI: 'posthog_ai',
+ POSTHOG_CODE: 'posthog_code',
+} as const
+
+export type EventSource = (typeof EVENT_SOURCE)[keyof typeof EVENT_SOURCE]
+
+const CLI_CONSUMER = 'posthog-cli'
+const WIZARD_USER_AGENT_FRAGMENT = 'posthog/wizard'
+
+// Minted server-side only and rejected by every user-facing scope validator, so a token
+// carrying it is provably one of PostHog's own agents rather than a third party naming
+// itself one. See INTERNAL_SCOPES in `posthog/temporal/oauth.py`.
+const INTERNAL_RUN_SCOPE = 'internal_run:read'
+
+// The OAuth applications PostHog controls, mirroring POSTHOG_DESKTOP_OAUTH_CLIENT_IDS and
+// POSTHOG_AI_OAUTH_APP_CLIENT_IDS in `posthog/temporal/oauth.py`, which owns them. A client id
+// reaches this server through token introspection rather than a header, so unlike
+// `x-posthog-mcp-consumer` the caller cannot set it for itself.
+const POSTHOG_AI_OAUTH_CLIENT_IDS = new Set([
+ 'N6UgOECSl98ag1xajxPphGApQXYEVvJIwzCXotKu',
+ '0Lizwa3mFSlBuEEQ8V8FMJlskUXpDuSmoEdhzxyi',
+ 'DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1',
+])
+
+const FIRST_PARTY_OAUTH_CLIENT_IDS = new Set([
+ 'HCWoE0aRFMYxIxFNTTwkOORn5LBjOt2GVDzwSw5W',
+ 'AIvijgMS0dxKEmr5z6odvRd8Pkh5vts3nPTzgzU9',
+ 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ',
+ 'a5TY7w9IjFYfes6dkPgZe6envclWw3bm2UD8ZTlm',
+ '1A7vO138Fh5sYmJislicN4F5HnttI6urmFttxPDU',
+])
+
+/**
+ * Whether one of PostHog's own OAuth applications vouches for this request.
+ *
+ * The client id is what Django gates on, so it is the signal that makes the two sides agree.
+ * `internal_run:read` stays as a second route because it is minted server-side only, which
+ * makes it proof of a first-party token on its own, and it still resolves the surface when
+ * introspection has not populated the client id for this request.
+ */
+function isFirstPartyCaller(input: EventSourceInput): boolean {
+ if (input.oauthClientId && FIRST_PARTY_OAUTH_CLIENT_IDS.has(input.oauthClientId)) {
+ return true
+ }
+ return input.apiKeyScopes?.includes(INTERNAL_RUN_SCOPE) ?? false
+}
+
+// What a first-party caller declares in `x-posthog-mcp-consumer` when it wraps this server.
+// A Map rather than an object literal because the key is caller-supplied: indexing an object
+// with `constructor` or `toString` returns an inherited function, which is truthy and so
+// survives a `??` fallback.
+const FIRST_PARTY_CONSUMER_TO_SOURCE = new Map<string, EventSource>([
+ ['slack', EVENT_SOURCE.SLACK],
+ ['posthog_ai', EVENT_SOURCE.POSTHOG_AI],
+ [POSTHOG_CODE_CONSUMER, EVENT_SOURCE.POSTHOG_CODE],
+])
+
+export interface EventSourceInput {
+ mcpConsumer?: string | undefined
+ clientUserAgent?: string | undefined
+ apiKeyScopes?: readonly string[] | undefined
+ oauthClientId?: string | undefined
+}
+
+/**
+ * Resolve the surface behind an MCP request.
+ *
+ * Mirrors `get_event_source` in `posthog/event_usage.py`, with one remaining gap. Django can
+ * tell the interactive desktop app apart from the agents that share its OAuth application by
+ * reading refresh-token lineage out of the database, which this server cannot do. A first-party
+ * request that declares no consumer therefore resolves to `desktop` on the API events and `mcp`
+ * on the `$mcp_*` events from the same call. Nothing routes the app through this server today,
+ * so the gap is not reachable in practice; the `source` taxonomy entry records it.
+ *
+ * Ends at `mcp`, meaning a third-party agent, whenever nothing vouches for the declared consumer.
+ */
+export function resolveEventSource(input: EventSourceInput): EventSource {
+ // A token minted against the PostHog AI application is authoritative, which is the same
+ // early return `get_event_source` makes before it looks at any header.
+ if (input.oauthClientId && POSTHOG_AI_OAUTH_CLIENT_IDS.has(input.oauthClientId)) {
+ return EVENT_SOURCE.POSTHOG_AI
+ }
+ // Matches Django: the outer caller's user-agent wins over anything the MCP layer says.
+ if (input.clientUserAgent?.includes(WIZARD_USER_AGENT_FRAGMENT)) {
+ return EVENT_SOURCE.WIZARD
+ }
+ // The CLI authenticates with a personal API key, so there is no first-party grant to
+ // vouch for it. Django honors it ungated for the same reason.
+ if (input.mcpConsumer === CLI_CONSUMER) {
+ return EVENT_SOURCE.CLI
+ }
+ if (!input.mcpConsumer || !isFirstPartyCaller(input)) {
+ return EVENT_SOURCE.MCP
+ }
+ return FIRST_PARTY_CONSUMER_TO_SOURCE.get(input.mcpConsumer) ?? EVENT_SOURCE.MCP
+}
diff --git a/services/mcp/src/schema/api.ts b/services/mcp/src/schema/api.ts
index df48e990075d..81408bb39a41 100644
--- a/services/mcp/src/schema/api.ts
+++ b/services/mcp/src/schema/api.ts
@@ -54,6 +54,7 @@ export type ApiOAuthIntrospection =
scoped_teams: number[]
scoped_organizations: string[]
client_name?: string
+ client_id?: string
}
| {
active: false
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
index a10722ced42b..94891cb5c6b1 100644
--- a/services/mcp/src/tools/types.ts
+++ b/services/mcp/src/tools/types.ts
@@ -26,6 +26,7 @@ export type State = {
region: CloudRegion | undefined
apiKey: ApiRedactedPersonalApiKey | undefined
clientName: string | undefined
+ oauthClientId: string | undefined
mcpClientName: string | undefined
mcpClientVersion: string | undefined
mcpProtocolVersion: string | undefined
diff --git a/services/mcp/tests/event-source.test.ts b/services/mcp/tests/event-source.test.ts
new file mode 100644
index 000000000000..7285d34f2d53
--- /dev/null
+++ b/services/mcp/tests/event-source.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest'
+
+import { EVENT_SOURCE, resolveEventSource } from '@/lib/event-source'
+
+// Every surface this server is allowed to stamp. `test_mcp_server_only_emits_sources_this_enum_knows`
+// in `posthog/test/test_event_usage.py` holds the same list against Django's EventSource, so adding
+// one here without adding it there fails on that side.
+const SURFACES_THE_API_KNOWS = ['mcp', 'cli', 'wizard', 'slack', 'posthog_ai', 'posthog_code']
+
+const SANDBOX_SCOPES = ['insight:read', 'internal_run:read']
+const CONSENTED_SCOPES = ['insight:read']
+
+// Mirrors ARRAY_APP_CLIENT_ID_DEV and POSTHOG_AI_APP_CLIENT_ID_DEV in `posthog/temporal/oauth.py`.
+const ARRAY_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ'
+const POSTHOG_AI_CLIENT_ID = 'DD2ZLG6a2YEUtpPANSzSiIBPuUryYmbndLnKKUy1'
+
+describe('resolveEventSource', () => {
+ it.each([
+ ['a third-party agent has nothing to vouch for it', { mcpConsumer: 'cursor' }, EVENT_SOURCE.MCP],
+ [
+ 'a self-declared first-party consumer without a server-minted token stays third-party',
+ { mcpConsumer: 'slack', apiKeyScopes: ['insight:read'] },
+ EVENT_SOURCE.MCP,
+ ],
+ ['the Slack app', { mcpConsumer: 'slack', apiKeyScopes: SANDBOX_SCOPES }, EVENT_SOURCE.SLACK],
+ ['PostHog AI', { mcpConsumer: 'posthog_ai', apiKeyScopes: SANDBOX_SCOPES }, EVENT_SOURCE.POSTHOG_AI],
+ [
+ 'a sandbox coding agent',
+ { mcpConsumer: 'posthog-code', apiKeyScopes: SANDBOX_SCOPES },
+ EVENT_SOURCE.POSTHOG_CODE,
+ ],
+ [
+ 'an unrecognized consumer on a server-minted token',
+ { mcpConsumer: 'ops-agent', apiKeyScopes: SANDBOX_SCOPES },
+ EVENT_SOURCE.MCP,
+ ],
+ ['the CLI, which has no first-party grant to gate on', { mcpConsumer: 'posthog-cli' }, EVENT_SOURCE.CLI],
+ [
+ 'the wizard, whose user-agent outranks the MCP layer',
+ { mcpConsumer: 'posthog-code', clientUserAgent: 'posthog/wizard 1.0' },
+ EVENT_SOURCE.WIZARD,
+ ],
+ ['no consumer at all', {}, EVENT_SOURCE.MCP],
+ [
+ // The agent PostHog Desktop hosts authenticates with the user's consented token, so it
+ // carries no `internal_run:read`. Only the OAuth application vouches for it, and Django
+ // resolves the same request to posthog_code.
+ 'the local agent inside PostHog Desktop',
+ { mcpConsumer: 'posthog-code', apiKeyScopes: CONSENTED_SCOPES, oauthClientId: ARRAY_CLIENT_ID },
+ EVENT_SOURCE.POSTHOG_CODE,
+ ],
+ [
+ 'a PostHog AI token, whichever consumer it declares',
+ { mcpConsumer: 'cursor', oauthClientId: POSTHOG_AI_CLIENT_ID },
+ EVENT_SOURCE.POSTHOG_AI,
+ ],
+ [
+ 'a third-party application declaring a first-party consumer',
+ { mcpConsumer: 'slack', apiKeyScopes: CONSENTED_SCOPES, oauthClientId: 'some-third-party-client-id' },
+ EVENT_SOURCE.MCP,
+ ],
+ [
+ // A consumer naming an inherited Object member must not resolve to one.
+ 'a consumer borrowed from the prototype chain',
+ { mcpConsumer: 'constructor', apiKeyScopes: SANDBOX_SCOPES },
+ EVENT_SOURCE.MCP,
+ ],
+ ])('resolves %s', (_name, input, expected) => {
+ expect(resolveEventSource(input)).toBe(expected)
+ })
+
+ it('emits only surfaces the PostHog API also knows', () => {
+ // A source the API's EventSource does not carry drops out of every breakdown that joins
+ // the MCP events with the product events they cause.
+ expect(Object.values(EVENT_SOURCE).sort()).toEqual([...SURFACES_THE_API_KNOWS].sort())
+ })
+})
diff --git a/services/mcp/tests/hono/analytics.test.ts b/services/mcp/tests/hono/analytics.test.ts
index 9df25dbdd9f0..3dedf6c510a7 100644
--- a/services/mcp/tests/hono/analytics.test.ts
+++ b/services/mcp/tests/hono/analytics.test.ts
@@ -32,6 +32,7 @@ function makeState(overrides: Partial<ResolvedState> = {}): ResolvedState {
useSingleExec: true,
toolFeatureFlags: undefined,
apiKeyScopes: [],
+ oauthClientId: undefined,
clientProfile: {} as any,
requestContext: {
authMethod: 'personal_api_key',
@@ -111,6 +112,23 @@ describe('Hono MCP analytics contexts', () => {
})
})
+ it('stamps the surface as `source` so MCP events join product events', async () => {
+ // Without it, $mcp_* events carry no `source` at all and sit outside the breakdown
+ // that measures MCP adoption. The resolution matrix itself is covered in
+ // tests/event-source.test.ts — this only proves the property reaches the event.
+ await trackToolCall(
+ 'user-get',
+ 12,
+ false,
+ makeState({
+ apiKeyScopes: ['insight:read', 'internal_run:read'],
+ requestContext: { ...makeState().requestContext, mcpConsumer: 'slack' },
+ })
+ )
+
+ expect(mockCaptureToolCall.mock.calls[0]![0].properties.source).toBe('slack')
+ })
+
it('omits session properties when there is no MCP session context', async () => {
await trackToolCall('user-get', 12, false, makeState({ sessionContext: null }))
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index 22b0ef42c6a6..ca318abd0e4e 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -49,6 +49,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
useSingleExec: false,
toolFeatureFlags: undefined,
apiKeyScopes: [],
+ oauthClientId: undefined,
clientProfile: {
capabilities: { supportsInstructions: true },
isCliModeEnabled: vi.fn(() => false),
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index 15c4576a24ee..058ef2e5a559 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -81,6 +81,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
useSingleExec: false,
toolFeatureFlags: undefined,
apiKeyScopes: [],
+ oauthClientId: undefined,
clientProfile: {
capabilities: { supportsInstructions: true },
isCliModeEnabled: vi.fn(() => false),
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
index 0a3fa5b5f7a6..2189c0accf25 100644
--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -52,6 +52,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
useSingleExec: false,
toolFeatureFlags: undefined,
apiKeyScopes: [],
+ oauthClientId: undefined,
clientProfile: {
capabilities: { supportsInstructions: true },
isCliModeEnabled: vi.fn(() => false),
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index 524c601e1e73..fe1c78e58777 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -47,6 +47,7 @@ function makeState(tools: { name: string }[], overrides: Partial<ResolvedState>
useSingleExec: false,
toolFeatureFlags: undefined,
apiKeyScopes: [],
+ oauthClientId: undefined,
clientProfile: {
capabilities: { supportsInstructions: true },
isCliModeEnabled: vi.fn(() => false),