Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(activity-log): show agent intent and task on audited changes (#100741)

posthog[bot]f956d22c9d4a
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.md
index b8926b81dfac..afbd37d493e4 100644
--- a/docs/internal/activity-logging.md
+++ b/docs/internal/activity-logging.md
@@ -121,6 +121,16 @@ The row is a system row.
To attribute it to a job, pass a `Trigger(job_type=..., job_id=..., payload=...)` in `Detail`.
A receiver can also read one from `get_current_trigger()` when the job wrapped its write in `ActivityTriggerContext(...)`; the receiver has to read and pass it, the context alone stores nothing.
+### Agent writes
+
+`OAuthAccessTokenAuthentication` records two things for an agent running in a sandbox: the task the token is bound to, and the agent's stated reason from the `x-posthog-intent` header.
+When a row would otherwise have no trigger, `log_activity` fills it with `Trigger(job_type="agent", job_id=<task id>, payload={"intent": ...})`.
+A product that passes its own trigger keeps it, so this only fills the gap.
+
+The task id is what makes the row an agent write, and it is not self-reported: the sandbox provisioning binds it to the token it mints.
+The intent is the agent's own claim and nothing verifies it, so it is read only from a request whose token carries that binding, and every surface that shows it says where it came from.
+Without that rule, any caller could put the header on a write of its own and have the audit trail present the write as automation.
+
A model with a fail-closed manager (`TeamScopedRootMixin`, `ProductTeamModel`) raises `TeamScopeError` on any query without team context.
The mixin's before-update read is by primary key without a team filter (`unscoped()`), so a `save()` outside a request works.
Your own reads in the same path still need `with team_scope(team_id):` or `Model.objects.for_team(team_id)`.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c0ae72087e13..3399885260cf 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -112,6 +112,14 @@ snapshots:
hash: v1.k794b7964.6aab6f60f5f5106fd66cf02ad1f62be1e3c7bf08e13b75761f75b1fdff364568.YblDy_cCbcSdCbly1El4Qw3GRwtAFGM11gHIH-dHk9o
components-activitylog--without-audit-logs-feaure--light:
hash: v1.k794b7964.1eed88732da4c326634cb530f95a9abd01a0c58ee567835a43165e77d675b6eb.rB6MYt2DBwRCcUcRIYjwQ629nrgOWhD3uoF8J02EuXU
+ components-agentattribution--intent-and-task--dark:
+ hash: v1.k794b7964.0d80c815b27006d88f038af4b2d689f510f8bdf583d7fc830eb68942821b56e4.vFLLhu562dwroQu8TA_dLSIrYC3SgtRpKdZTB8ufS84
+ components-agentattribution--intent-and-task--light:
+ hash: v1.k794b7964.24895d9480ddd6f87009e5b1b25baf6e886cac9cd9880903e339bff843033fd8.KzV5k8F-3EZNmgX3eF2rV0oiWATstdKagopl-HYlEfQ
+ components-agentattribution--task-only--dark:
+ hash: v1.k794b7964.5b5f3178c99673ba0bf03dddb8a88cf889e51cf1d89039743d51c3bb056172cc.nuzeiVXJiHurkyu1JOKm6DOspFpAqjrJKgmUZzfj0d0
+ components-agentattribution--task-only--light:
+ hash: v1.k794b7964.7998d17fc86c2c7943b3e69cf5e661dc4af268064ffa0d1f63ce7d867c26d306.NS_bmOi6RrA5Trtg55bFg4znU7uOCkALbnJkMMgk4r0
components-agentpromptbutton--default--dark:
hash: v1.k794b7964.589f9b44c782286a8f62d7390a1c152611b358df714447e892afcdbb3681296b.DLA5NWyjGVTWKj7Sry71BrbQvkGJEKeNdD-MR-4pqHA
components-agentpromptbutton--default--light:
diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.tsx
index 88433e8ef73d..b3d90426a900 100644
--- a/frontend/src/lib/components/ActivityLog/ActivityLog.tsx
+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.tsx
@@ -14,6 +14,7 @@ import {
ActivityLogLogicProps,
activityLogLogic,
} from 'lib/components/ActivityLog/activityLogLogic'
+import { AgentAttribution } from 'lib/components/ActivityLog/AgentAttribution'
import { ActivityChange, HumanizedActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
import { TZLabel } from 'lib/components/TZLabel'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -204,6 +205,7 @@ export const ActivityLogRow = ({
{logItem.extendedDescription && (
<div className="ActivityLogRow__description__extended">{logItem.extendedDescription}</div>
)}
+ <AgentAttribution logItem={logItem} />
<div className="text-secondary flex items-center gap-1.5">
<TZLabel time={logItem.created_at} />
{logItem.client && (
diff --git a/frontend/src/lib/components/ActivityLog/AgentAttribution.stories.tsx b/frontend/src/lib/components/ActivityLog/AgentAttribution.stories.tsx
new file mode 100644
index 000000000000..6295695ccd13
--- /dev/null
+++ b/frontend/src/lib/components/ActivityLog/AgentAttribution.stories.tsx
@@ -0,0 +1,49 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { dayjs } from 'lib/dayjs'
+
+import { ActivityScope } from '~/types'
+
+import { AgentAttribution } from './AgentAttribution'
+import { ActivityLogDetail, HumanizedActivityLogItem } from './humanizeActivity'
+
+const AGENT_TASK_ID = '019f4c2a-0000-7000-8000-0000000000aa'
+
+function logItem(detail: Partial<ActivityLogDetail>): HumanizedActivityLogItem {
+ return {
+ description: 'changed the tile query on Weekly signups',
+ created_at: dayjs('2026-09-14T12:00:00Z'),
+ unprocessed: {
+ activity: 'updated',
+ created_at: '2026-09-14T12:00:00Z',
+ scope: ActivityScope.DASHBOARD,
+ client: 'mcp',
+ detail: { merge: null, trigger: null, changes: null, name: 'Weekly signups', ...detail },
+ },
+ }
+}
+
+type Story = StoryObj<typeof AgentAttribution>
+const meta: Meta<typeof AgentAttribution> = {
+ title: 'Components/AgentAttribution',
+ component: AgentAttribution,
+}
+export default meta
+
+export const IntentAndTask: Story = {
+ args: {
+ logItem: logItem({
+ trigger: {
+ job_type: 'agent',
+ job_id: AGENT_TASK_ID,
+ payload: { intent: 'Repairing a tile that hit the query row limit, as the report asked' },
+ },
+ }),
+ },
+}
+
+export const TaskOnly: Story = {
+ args: {
+ logItem: logItem({ trigger: { job_type: 'agent', job_id: AGENT_TASK_ID, payload: {} } }),
+ },
+}
diff --git a/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx b/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx
new file mode 100644
index 000000000000..ce79624db14a
--- /dev/null
+++ b/frontend/src/lib/components/ActivityLog/AgentAttribution.tsx
@@ -0,0 +1,35 @@
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { Link } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+import { HumanizedActivityLogItem } from './humanizeActivity'
+import { parseAgentAttribution } from './parseAgentAttribution'
+
+export const AGENT_INTENT_TOOLTIP = 'Self-reported by the agent in the x-posthog-intent request header'
+
+export function AgentAttribution({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element | null {
+ const attribution = parseAgentAttribution(logItem)
+ if (!attribution) {
+ return null
+ }
+
+ return (
+ <div className="text-secondary text-xs flex flex-col gap-0.5" data-attr="activity-log-agent-attribution">
+ {attribution.intent && (
+ <div>
+ <Tooltip title={AGENT_INTENT_TOOLTIP}>
+ <span className="underline decoration-dotted">Agent intent</span>
+ </Tooltip>{' '}
+ <span className="text-default">{attribution.intent}</span>
+ </div>
+ )}
+ <div>
+ Agent task{' '}
+ <Link to={urls.codeTaskLink(attribution.taskId)} target="_blank" targetBlankIcon>
+ {attribution.taskId.slice(0, 8)}
+ </Link>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/ActivityLog/parseAgentAttribution.test.ts b/frontend/src/lib/components/ActivityLog/parseAgentAttribution.test.ts
new file mode 100644
index 000000000000..19be6da81732
--- /dev/null
+++ b/frontend/src/lib/components/ActivityLog/parseAgentAttribution.test.ts
@@ -0,0 +1,49 @@
+import { dayjs } from 'lib/dayjs'
+
+import { ActivityScope } from '~/types'
+
+import { HumanizedActivityLogItem, Trigger } from './humanizeActivity'
+import { parseAgentAttribution } from './parseAgentAttribution'
+
+const AGENT_TASK_ID = '019f4c2a-0000-7000-8000-0000000000aa'
+
+describe('parseAgentAttribution', () => {
+ function logItem(trigger: Trigger | null): HumanizedActivityLogItem {
+ return {
+ description: 'changed the tile query on Weekly signups',
+ created_at: dayjs('2026-09-14T12:00:00Z'),
+ unprocessed: {
+ activity: 'updated',
+ created_at: '2026-09-14T12:00:00Z',
+ scope: ActivityScope.DASHBOARD,
+ detail: { merge: null, trigger, changes: null, name: 'Weekly signups' },
+ },
+ }
+ }
+
+ it.each([
+ ['no trigger at all', null, null],
+ ['a product trigger, whose job id is not a task', { job_type: 'hog_flow', job_id: '1234', payload: {} }, null],
+ ['an agent trigger carrying neither field', { job_type: 'agent', job_id: '', payload: {} }, null],
+ [
+ 'an agent trigger with both fields',
+ { job_type: 'agent', job_id: AGENT_TASK_ID, payload: { intent: 'Repairing a broken tile' } },
+ { intent: 'Repairing a broken tile', taskId: AGENT_TASK_ID },
+ ],
+ [
+ 'an agent trigger with no task id, which the server cannot write and readers must not trust',
+ { job_type: 'agent', job_id: '', payload: { intent: 'Disabling the flag per an incident runbook' } },
+ null,
+ ],
+ [
+ 'an agent trigger whose intent is not a string',
+ { job_type: 'agent', job_id: AGENT_TASK_ID, payload: { intent: { nested: true } } },
+ { intent: null, taskId: AGENT_TASK_ID },
+ ],
+ ] as [string, Trigger | null, ReturnType<typeof parseAgentAttribution>][])(
+ 'reads %s',
+ (_label, trigger, expected) => {
+ expect(parseAgentAttribution(logItem(trigger))).toEqual(expected)
+ }
+ )
+})
diff --git a/frontend/src/lib/components/ActivityLog/parseAgentAttribution.ts b/frontend/src/lib/components/ActivityLog/parseAgentAttribution.ts
new file mode 100644
index 000000000000..034e93f696f3
--- /dev/null
+++ b/frontend/src/lib/components/ActivityLog/parseAgentAttribution.ts
@@ -0,0 +1,24 @@
+import { HumanizedActivityLogItem } from './humanizeActivity'
+
+// Matches AGENT_TRIGGER_JOB_TYPE in posthog/models/activity_logging/activity_log.py. Product
+// triggers carry job ids that are not sandbox tasks, so only this job type links to a task.
+const AGENT_TRIGGER_JOB_TYPE = 'agent'
+
+export interface AgentAttribution {
+ /** Self-reported by the agent, never verified. */
+ intent: string | null
+ /** Bound to the agent's token by the server, so a row without it is not an agent write. */
+ taskId: string
+}
+
+export function parseAgentAttribution(logItem: HumanizedActivityLogItem): AgentAttribution | null {
+ const trigger = logItem.unprocessed?.detail?.trigger
+ if (trigger?.job_type !== AGENT_TRIGGER_JOB_TYPE || !trigger.job_id) {
+ return null
+ }
+
+ return {
+ intent: typeof trigger.payload?.intent === 'string' ? trigger.payload.intent : null,
+ taskId: trigger.job_id,
+ }
+}
diff --git a/frontend/src/scenes/audit-logs/AuditLogTable.tsx b/frontend/src/scenes/audit-logs/AuditLogTable.tsx
index a0f6b9b94ada..5f5ed6f23280 100644
--- a/frontend/src/scenes/audit-logs/AuditLogTable.tsx
+++ b/frontend/src/scenes/audit-logs/AuditLogTable.tsx
@@ -2,12 +2,16 @@ import { useState } from 'react'
import { LemonTag, LemonTabs, Tooltip } from '@posthog/lemon-ui'
+import { AGENT_INTENT_TOOLTIP } from 'lib/components/ActivityLog/AgentAttribution'
import { HumanizedActivityLogItem, humanizeActivity, humanizeScope } from 'lib/components/ActivityLog/humanizeActivity'
+import { parseAgentAttribution } from 'lib/components/ActivityLog/parseAgentAttribution'
import MonacoDiffEditor from 'lib/components/MonacoDiffEditor'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { Link } from 'lib/lemon-ui/Link'
import { PaginationManual } from 'lib/lemon-ui/PaginationControl'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
+import { urls } from 'scenes/urls'
export interface AuditLogTableProps {
logItems: HumanizedActivityLogItem[]
@@ -164,6 +168,7 @@ export function AuditLogTable({ logItems, pagination, teamsById }: AuditLogTable
function ExpandedRowContent({ logItem }: { logItem: HumanizedActivityLogItem }): JSX.Element {
const unprocessed = logItem.unprocessed
+ const agent = parseAgentAttribution(logItem)
if (!unprocessed) {
return <div className="p-4 text-muted">No additional details available</div>
@@ -195,6 +200,28 @@ function ExpandedRowContent({ logItem }: { logItem: HumanizedActivityLogItem }):
<div className="text-[13px] text-default">{unprocessed.item_id}</div>
</div>
)}
+ {agent?.intent && (
+ <div>
+ <Tooltip title={AGENT_INTENT_TOOLTIP}>
+ <div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1 w-fit">
+ Agent intent
+ </div>
+ </Tooltip>
+ <div className="text-[13px] text-default">{agent.intent}</div>
+ </div>
+ )}
+ {agent && (
+ <div>
+ <div className="text-[11px] font-medium text-muted-alt uppercase tracking-wider mb-1">
+ Agent task
+ </div>
+ <div className="text-[13px]">
+ <Link to={urls.codeTaskLink(agent.taskId)} target="_blank" targetBlankIcon>
+ {agent.taskId}
+ </Link>
+ </div>
+ </div>
+ )}
</div>
</div>
diff --git a/posthog/auth.py b/posthog/auth.py
index 7d4aa9d7c545..cc6dbe59f72f 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -29,12 +29,17 @@ from zxcvbn import zxcvbn
from posthog.clickhouse.query_tagging import AccessMethod, tag_authentication
from posthog.constants import AvailableFeature
+from posthog.exceptions_capture import capture_exception
from posthog.helpers.two_factor_session import enforce_two_factor
from posthog.helpers.verified_domain_enforcement import enforce_verified_domain
from posthog.ingress.verify.schemes import hmac_sha256_signature, signatures_match
from posthog.internal_api_secret import usable_internal_api_secrets
from posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt, get_oidc_verification_keys
-from posthog.models.activity_logging.utils import activity_storage
+from posthog.models.activity_logging.utils import (
+ ACTIVITY_LOG_INTENT_HEADER,
+ ACTIVITY_LOG_INTENT_MAX_LENGTH,
+ activity_storage,
+)
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthApplicationAuthBrand
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.personal_api_key import (
@@ -894,6 +899,23 @@ class SharingPasswordProtectedAuthentication(authentication.BaseAuthentication):
return None
+def _record_agent_attribution(request: Union[HttpRequest, Request], access_token: OAuthAccessToken) -> None:
+ """Record the sandbox task bound to the token, and the intent the agent claims.
+
+ Any caller can send the intent header, so it is read only behind the token binding.
+ Attribution is extra detail on an audit row, so an error here must not fail the request.
+ """
+ try:
+ if access_token.sandbox_task_id is None:
+ return
+ activity_storage.set_agent_task_id(str(access_token.sandbox_task_id))
+ intent = request.headers.get(ACTIVITY_LOG_INTENT_HEADER, "").strip()[:ACTIVITY_LOG_INTENT_MAX_LENGTH]
+ if intent:
+ activity_storage.set_agent_intent(intent)
+ except Exception as e:
+ capture_exception(e)
+
+
class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):
"""
OAuth 2.0 Bearer token authentication using access tokens
@@ -915,35 +937,46 @@ class OAuthAccessTokenAuthentication(authentication.BaseAuthentication):
if not access_token:
raise AuthenticationFailed(detail="Invalid access token.")
- self._enforce_toolbar_access(access_token)
-
- self.access_token = access_token
-
- tag_authentication(
- user_id=access_token.user.pk,
- team_id=access_token.user.current_team_id,
- access_method=AccessMethod.OAUTH,
- )
-
- # ActivityLoggingMiddleware only captures session-authenticated users (it runs
- # before DRF auth), so signal-driven activity logging would otherwise record
- # bearer-token requests as system actions. Only write when the middleware owns
- # cleanup: outside a request cycle (e.g. authenticate() called directly) the
- # thread-local would leak.
- if activity_storage.is_request_scoped():
- activity_storage.set_user(access_token.user)
- # Tokens minted during staff impersonation must keep the impersonation
- # marker in the audit trail.
- if access_token.impersonated_by_id is not None:
- activity_storage.set_was_impersonated(True)
-
- return access_token.user, None
+ return self._authenticate_access_token(request, access_token)
except AuthenticationFailed:
raise
except Exception:
raise AuthenticationFailed(detail="Invalid access token.")
+ def _authenticate_access_token(
+ self, request: Union[HttpRequest, Request], access_token: OAuthAccessToken
+ ) -> tuple[Any, None]:
+ self._enforce_toolbar_access(access_token)
+
+ self.access_token = access_token
+
+ # The delegated query rejects missing users, but the nullable relation needs a type guard.
+ user = access_token.user
+ if user is None:
+ raise AuthenticationFailed(detail="User associated with access token not found.")
+
+ tag_authentication(
+ user_id=user.pk,
+ team_id=user.current_team_id,
+ access_method=AccessMethod.OAUTH,
+ )
+
+ # ActivityLoggingMiddleware only captures session-authenticated users (it runs
+ # before DRF auth), so signal-driven activity logging would otherwise record
+ # bearer-token requests as system actions. Only write when the middleware owns
+ # cleanup: outside a request cycle (e.g. authenticate() called directly) the
+ # thread-local would leak.
+ if activity_storage.is_request_scoped():
+ activity_storage.set_user(user)
+ # Tokens minted during staff impersonation must keep the impersonation
+ # marker in the audit trail.
+ if access_token.impersonated_by_id is not None:
+ activity_storage.set_was_impersonated(True)
+ _record_agent_attribution(request, access_token)
+
+ return user, None
+
def _extract_token(self, request: Union[HttpRequest, Request]) -> Optional[str]:
if "authorization" in request.headers:
authorization_match = re.match(rf"^{self.keyword}\s+(\S.+)$", request.headers["authorization"])
@@ -1071,18 +1104,7 @@ class DelegatedOAuthAccessTokenAuthentication(OAuthAccessTokenAuthentication):
except (KeyError, OAuthAccessToken.DoesNotExist) as error:
raise AuthenticationFailed(detail="Source OAuth access token is no longer valid.") from error
- self._enforce_toolbar_access(access_token)
- self.access_token = access_token
- tag_authentication(
- user_id=access_token.user.pk,
- team_id=access_token.user.current_team_id,
- access_method=AccessMethod.OAUTH,
- )
- if activity_storage.is_request_scoped():
- activity_storage.set_user(access_token.user)
- if access_token.impersonated_by_id is not None:
- activity_storage.set_was_impersonated(True)
- return access_token.user, None
+ return self._authenticate_access_token(request, access_token)
class WidgetAuthentication(authentication.BaseAuthentication):
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 2ca674240218..65a784e29d2a 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -1179,6 +1179,37 @@ def _handle_activity_log_transaction(create_fn, error_context: dict, *, using: s
return None
+# The frontend matches on this job type to render the job id as a link to a sandbox task.
+# Product triggers (`hog_flow`, `canvas_action`) carry job ids that point elsewhere.
+AGENT_TRIGGER_JOB_TYPE = "agent"
+
+
+def agent_trigger() -> Optional[Trigger]:
+ """The agent attribution for this request, or None when no token-bound task reached it.
+
+ The task id is required because it is the only server-set part. The intent is the agent's claim.
+ """
+ task_id = activity_storage.get_agent_task_id()
+ if not task_id:
+ return None
+ intent = activity_storage.get_agent_intent()
+ return Trigger(
+ job_type=AGENT_TRIGGER_JOB_TYPE,
+ job_id=task_id,
+ payload={"intent": intent} if intent else {},
+ )
+
+
+def _with_agent_trigger(detail: Detail) -> Detail:
+ """The row is written inside the user's save, so an error here must not fail that save."""
+ try:
+ trigger = agent_trigger()
+ return dataclasses.replace(detail, trigger=trigger) if trigger is not None else detail
+ except Exception as e:
+ capture_exception(e)
+ return detail
+
+
def log_activity(
*,
organization_id: Optional[UUID],
@@ -1201,6 +1232,9 @@ def log_activity(
client = activity_storage.get_client()
if ip_address is None:
ip_address = activity_storage.get_ip_address()
+ if detail.trigger is None:
+ # A product that sets its own trigger already says what drove the write.
+ detail = _with_agent_trigger(detail)
if was_impersonated and user is None:
logger.warn(
"activity_log.failed_to_write_to_activity_log",
diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.py
index 941c478659b3..c1456f10798a 100644
--- a/posthog/models/activity_logging/utils.py
+++ b/posthog/models/activity_logging/utils.py
@@ -16,6 +16,10 @@ logger = structlog.get_logger(__name__)
ACTIVITY_LOG_CLIENT_HEADER = "x-posthog-client"
ACTIVITY_LOG_CLIENT_MAX_LENGTH = 32
+# The MCP server forwards the same intent it sends to analytics as `$mcp_intent`. It is the
+# caller's own claim, so it is read only from a request whose token is bound to a sandbox task.
+ACTIVITY_LOG_INTENT_HEADER = "x-posthog-intent"
+ACTIVITY_LOG_INTENT_MAX_LENGTH = 500
@frozen
@@ -77,6 +81,26 @@ class ActivityLoggingStorage:
if hasattr(self._local, "client"):
delattr(self._local, "client")
+ def set_agent_intent(self, intent: Optional[str]) -> None:
+ self._local.agent_intent = intent
+
+ def get_agent_intent(self) -> Optional[str]:
+ return getattr(self._local, "agent_intent", None)
+
+ def clear_agent_intent(self) -> None:
+ if hasattr(self._local, "agent_intent"):
+ delattr(self._local, "agent_intent")
+
+ def set_agent_task_id(self, task_id: Optional[str]) -> None:
+ self._local.agent_task_id = task_id
+
+ def get_agent_task_id(self) -> Optional[str]:
+ return getattr(self._local, "agent_task_id", None)
+
+ def clear_agent_task_id(self) -> None:
+ if hasattr(self._local, "agent_task_id"):
+ delattr(self._local, "agent_task_id")
+
def set_ip_address(self, ip_address: Optional[str]) -> None:
self._local.ip_address = ip_address
@@ -102,6 +126,8 @@ class ActivityLoggingStorage:
self.clear_user()
self.clear_was_impersonated()
self.clear_client()
+ self.clear_agent_intent()
+ self.clear_agent_task_id()
self.clear_ip_address()
self.clear_trigger()
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.py
index 1aa949fb79a7..4a236eba0c2d 100644
--- a/posthog/test/activity_logging/test_activity_logging.py
+++ b/posthog/test/activity_logging/test_activity_logging.py
@@ -1,17 +1,24 @@
+from datetime import timedelta
+from uuid import UUID
+
import pytest
-from posthog.test.base import BaseTest
+from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import patch
from django.db.utils import IntegrityError
+from django.utils import timezone
from parameterized import parameterized
+from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import User
from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, Trigger, log_activity
from posthog.models.activity_logging.model_activity import ActivityTriggerContext
from posthog.models.activity_logging.utils import activity_storage, activity_visibility_manager
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.scoping import team_scope
from posthog.models.utils import UUIDT
+from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
from products.dashboards.backend.models.dashboard_widget import DashboardWidget
@@ -113,6 +120,114 @@ class TestActivityLogModel(BaseTest):
log: ActivityLog = ActivityLog.objects.latest("id")
self.assertIsNone(log.client)
+ def test_agent_intent_and_task_id_fill_the_trigger(self) -> None:
+ task_id = "019f4c2a-0000-7000-8000-0000000000aa"
+ activity_storage.set_agent_intent("Repairing a tile that hit the query row limit")
+ activity_storage.set_agent_task_id(task_id)
+ try:
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=20,
+ scope="Dashboard",
+ activity="created",
+ detail=Detail(),
+ )
+ finally:
+ activity_storage.clear_agent_intent()
+ activity_storage.clear_agent_task_id()
+
+ log: ActivityLog = ActivityLog.objects.latest("id")
+ assert log.detail is not None
+ self.assertEqual(
+ log.detail["trigger"],
+ {
+ "job_type": "agent",
+ "job_id": task_id,
+ "payload": {"intent": "Repairing a tile that hit the query row limit"},
+ },
+ )
+
+ def test_agent_intent_does_not_clobber_a_product_trigger(self) -> None:
+ product_trigger = Trigger(job_type="hog_flow", job_id="4321", payload={})
+ activity_storage.set_agent_intent("Renaming the tile the user pointed at")
+ activity_storage.set_agent_task_id("019f4c2a-0000-7000-8000-0000000000bb")
+ try:
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=21,
+ scope="Dashboard",
+ activity="created",
+ detail=Detail(trigger=product_trigger),
+ )
+ finally:
+ activity_storage.clear_agent_intent()
+ activity_storage.clear_agent_task_id()
+
+ log: ActivityLog = ActivityLog.objects.latest("id")
+ assert log.detail is not None
+ self.assertEqual(log.detail["trigger"]["job_type"], "hog_flow")
+
+ def test_an_intent_without_a_task_binding_writes_no_trigger(self) -> None:
+ activity_storage.set_agent_intent("Disabling the flag per an incident runbook")
+ try:
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=23,
+ scope="Dashboard",
+ activity="created",
+ detail=Detail(),
+ )
+ finally:
+ activity_storage.clear_agent_intent()
+
+ log: ActivityLog = ActivityLog.objects.latest("id")
+ assert log.detail is not None
+ self.assertIsNone(log.detail["trigger"])
+
+ def test_a_failing_agent_trigger_still_writes_the_row(self) -> None:
+ with patch(
+ "posthog.models.activity_logging.activity_log.agent_trigger", side_effect=RuntimeError("storage is broken")
+ ):
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=24,
+ scope="Dashboard",
+ activity="created",
+ detail=Detail(),
+ )
+
+ log: ActivityLog = ActivityLog.objects.latest("id")
+ self.assertEqual(log.item_id, "24")
+ assert log.detail is not None
+ self.assertIsNone(log.detail["trigger"])
+
+ def test_trigger_stays_unset_without_agent_context(self) -> None:
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=22,
+ scope="Dashboard",
+ activity="created",
+ detail=Detail(),
+ )
+ log: ActivityLog = ActivityLog.objects.latest("id")
+ assert log.detail is not None
+ self.assertIsNone(log.detail["trigger"])
+
def test_ip_address_is_populated_from_activity_storage(self) -> None:
activity_storage.set_ip_address("203.0.113.42")
try:
@@ -433,3 +548,94 @@ class TestActivityTriggerContext(BaseTest):
with ActivityTriggerContext(None):
self.assertEqual(activity_storage.get_trigger(), outer)
self.assertEqual(activity_storage.get_trigger(), outer)
+
+
+class TestAgentAttributionOnApiWrites(APIBaseTest):
+ """The intent header, the OAuth token binding and the audit row only meet on a real request."""
+
+ def _authenticate_as_sandbox_agent(self, task_id: UUID | None, delegated: bool = False) -> None:
+ application = OAuthApplication.objects.create(
+ name="Sandbox",
+ client_id=ARRAY_APP_CLIENT_ID_DEV,
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token="pha_sandbox_agent",
+ scope="dashboard:read dashboard:write",
+ expires=timezone.now() + timedelta(hours=1),
+ scoped_teams=[self.team.id],
+ sandbox_task_id=task_id,
+ )
+ self.client.logout()
+ token_value = token.token
+ if delegated:
+ token_value = encode_jwt(
+ {"id": self.user.id, "oauth_access_token_id": str(token.id)},
+ timedelta(minutes=15),
+ PosthogJwtAudience.DELEGATED_USER,
+ )
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token_value}")
+
+ @parameterized.expand(
+ [
+ (
+ "records the intent of a token bound to a sandbox task",
+ UUID("019f4c2a-0000-7000-8000-0000000000aa"),
+ False,
+ {
+ "job_type": "agent",
+ "job_id": "019f4c2a-0000-7000-8000-0000000000aa",
+ "payload": {"intent": "Repairing a tile that hit the query row limit"},
+ },
+ ),
+ (
+ "records the intent of a delegated token bound to a sandbox task",
+ UUID("019f4c2a-0000-7000-8000-0000000000aa"),
+ True,
+ {
+ "job_type": "agent",
+ "job_id": "019f4c2a-0000-7000-8000-0000000000aa",
+ "payload": {"intent": "Repairing a tile that hit the query row limit"},
+ },
+ ),
+ ("ignores the header on a token with no task", None, False, None),
+ ]
+ )
+ def test_agent_write(
+ self, _name: str, task_id: UUID | None, delegated: bool, expected_trigger: dict | None
+ ) -> None:
+ self._authenticate_as_sandbox_agent(task_id, delegated)
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/",
+ {"name": "Weekly signups"},
+ HTTP_X_POSTHOG_INTENT="Repairing a tile that hit the query row limit",
+ )
+ self.assertEqual(response.status_code, 201, response.content)
+
+ log = ActivityLog.objects.filter(scope="Dashboard").latest("id")
+ assert log.detail is not None
+ self.assertEqual(log.detail["trigger"], expected_trigger)
+
+ def test_a_failing_attribution_loses_the_intent_and_nothing_else(self) -> None:
+ task_id = UUID("019f4c2a-0000-7000-8000-0000000000aa")
+ self._authenticate_as_sandbox_agent(task_id)
+
+ with patch("posthog.auth.activity_storage.set_agent_intent", side_effect=RuntimeError("storage is broken")):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/dashboards/",
+ {"name": "Weekly signups"},
+ HTTP_X_POSTHOG_INTENT="Repairing a tile that hit the query row limit",
+ )
+
+ self.assertEqual(response.status_code, 201, response.content)
+ log = ActivityLog.objects.filter(scope="Dashboard").latest("id")
+ assert log.detail is not None
+ self.assertEqual(log.detail["trigger"], {"job_type": "agent", "job_id": str(task_id), "payload": {}})
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index 1a8561685976..09f59cd16c53 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -163,6 +163,19 @@ export interface ApiConfig {
* the agent's task; the API validates it against the token's team.
*/
taskId?: string | undefined
+ /** One tool call's stated intent, forwarded as `x-posthog-intent`. Set it through `withIntent`. */
+ intent?: string | undefined
+}
+
+// Matches ACTIVITY_LOG_INTENT_MAX_LENGTH in posthog/models/activity_logging/utils.py.
+const MAX_INTENT_HEADER_LENGTH = 500
+
+// The intent rides along on every API call, so a bad value must cost the header, never the call.
+function intentHeaderValue(intent: unknown): string | undefined {
+ if (typeof intent !== 'string') {
+ return undefined
+ }
+ return sanitizeHeaderValue(intent)?.slice(0, MAX_INTENT_HEADER_LENGTH)
}
type Endpoint = Record<string, any>
@@ -180,6 +193,20 @@ export class ApiClient {
this.publicBaseUrl = config.publicBaseUrl || config.baseUrl
}
+ /**
+ * A copy of this client that carries one tool call's intent.
+ *
+ * The calls in a JSON-RPC batch run concurrently over one cached client, so writing the
+ * intent onto that client would let a later call overwrite an earlier call's intent.
+ * The copy keeps the prototype, so a `ForwardingApiClient` copy still forwards.
+ */
+ withIntent(intent: string): this {
+ const scoped = Object.create(Object.getPrototypeOf(this) as object) as this
+ Object.assign(scoped, this)
+ scoped.config = { ...this.config, intent }
+ return scoped
+ }
+
getProjectBaseUrl(projectId: string): string {
if (projectId === '@current') {
return this.publicBaseUrl
@@ -224,6 +251,8 @@ export class ApiClient {
'x-posthog-mcp-conversation-id': this.config.mcpConversationId,
// Forward the sandbox task id so API writes are attributed to the agent's task.
'X-PostHog-Task-Id': this.config.taskId,
+ // Forward the agent's stated intent so the activity log records why, not just who.
+ 'x-posthog-intent': intentHeaderValue(this.config.intent),
}),
'X-PostHog-Client': 'mcp',
}
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 5793b15ca42b..49f07fb930ef 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -104,6 +104,19 @@ function shouldSuppressStructuredContent(args: {
return args.isCliModeEnabled && !isRenderUiHostInSingleExec
}
+// The state is shared by every call in a JSON-RPC batch, so the client is copied, not written to.
+// The intent is extra detail on an audit row: if the copy fails, the call runs without it.
+function stateCarryingIntent(state: ResolvedState, intent: string | undefined): ResolvedState {
+ if (!intent) {
+ return state
+ }
+ try {
+ return { ...state, context: { ...state.context, api: state.context.api.withIntent(intent) } }
+ } catch {
+ return state
+ }
+}
+
export class ToolExecutor {
private readonly catalog: ToolCatalog
private readonly instructionsBuilder: InstructionsBuilder
@@ -187,10 +200,11 @@ export class ToolExecutor {
? (rawRequestMeta as Record<string, unknown>)
: undefined
const { analyticsMeta, args } = this.extractAnalyticsMetadata(toolName, rawArgs, originalTool, requestMeta)
+ const callState = stateCarryingIntent(state, analyticsMeta.intent)
const callParams = { ...params, arguments: args }
if (toolName === 'exec') {
- return this.callExecTool(callParams, state, analyticsMeta)
+ return this.callExecTool(callParams, callState, analyticsMeta)
}
if (toolName === 'render-ui') {
@@ -199,7 +213,7 @@ export class ToolExecutor {
toolCallsTotal.inc({ tool: toolName, status: 'error' })
return { content: [{ type: 'text', text: `Tool ${toolName} not found` }], isError: true }
}
- return this.callRenderUiTool(callParams, state, analyticsMeta)
+ return this.callRenderUiTool(callParams, callState, analyticsMeta)
}
if (!state.allTools.some((t) => t.name === toolName)) {
@@ -222,7 +236,7 @@ export class ToolExecutor {
_meta: tool._meta,
},
callParams,
- state,
+ callState,
analyticsMeta
)
}
diff --git a/services/mcp/src/lib/connection-forwarding.ts b/services/mcp/src/lib/connection-forwarding.ts
index b86d9ba8c8f5..19399c610c8f 100644
--- a/services/mcp/src/lib/connection-forwarding.ts
+++ b/services/mcp/src/lib/connection-forwarding.ts
@@ -90,7 +90,8 @@ export class ForwardingApiClient extends ApiClient {
let forwarded: ForwardResponse
try {
- forwarded = await this.local.request<ForwardResponse>({
+ const local = this.config.intent ? this.local.withIntent(this.config.intent) : this.local
+ forwarded = await local.request<ForwardResponse>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(this.options.localProjectId)}/posthog_connections/${encodeURIComponent(this.options.connectionId)}/forward/`,
body,
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index da43bbe1a76e..6267d8878dae 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -30,62 +30,12 @@ vi.mock('@/lib/posthog', async () => {
})
import { InstructionsBuilder } from '@/hono/instructions'
-import type { ResolvedState } from '@/hono/request-state-resolver'
import { ToolCatalog } from '@/hono/tool-catalog'
import { ToolExecutor } from '@/hono/tool-executor'
import { getPostHogClient } from '@/lib/posthog'
import { MAX_CAPTURED_DESCRIPTION_LENGTH } from '@/tools/toolDefinitions'
-function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {
- return {
- reqCtx: {
- cache: { get: vi.fn(), set: vi.fn() },
- safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
- trackEvent: vi.fn(),
- getSessionUuid: vi.fn().mockResolvedValue(undefined),
- getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
- } as any,
- context: {
- api: {},
- cache: {},
- env: {},
- stateManager: {},
- sessionManager: {},
- getDistinctId: vi.fn(),
- trackEvent: vi.fn(),
- } as any,
- useSingleExec: false,
- toolFeatureFlags: undefined,
- apiKeyScopes: [],
- oauthClientId: undefined,
- clientProfile: {
- capabilities: { supportsInstructions: true },
- isCliModeEnabled: vi.fn(() => false),
- isClaudeUiHost: vi.fn(() => false),
- isInlineExecUiHost: vi.fn(() => false),
- isClaudeChatHost: vi.fn(() => false),
- } as any,
- requestContext: {
- authMethod: 'personal_api_key',
- sessionId: 'sess-1',
- mcpClientName: 'test',
- mcpClientVersion: '1.0',
- mcpProtocolVersion: '2025-03-26',
- transport: 'streamable-http',
- },
- sessionContext: null,
- allTools: tools as any,
- scopeGatedTools: [],
- flagGatedTools: [],
- gatewayToolsEnabled: false,
- distinctId: 'test-distinct-id',
- renderUiEnabled: false,
- metadata: undefined,
- metadataCompact: undefined,
- groupTypes: undefined,
- ...overrides,
- }
-}
+import { makeToolExecutorState, mockApi } from '../shared/test-utils'
describe('ToolExecutor analytics capture', () => {
let catalog: ToolCatalog
@@ -102,7 +52,7 @@ describe('ToolExecutor analytics capture', () => {
})
it('injects the analytics arguments into advertised tools', async () => {
- const state = makeState([], { useSingleExec: true })
+ const state = makeToolExecutorState([], { useSingleExec: true })
const result = await executor.handleToolsList(state)
@@ -185,7 +135,7 @@ describe('ToolExecutor analytics capture', () => {
const filteredTools = catalog
.getFilteredTools({ scopes: ['*'] })
.filter((tool) => tool.name === 'execute-sql' || tool.name === 'organization-get')
- const state = makeState(filteredTools, { useSingleExec: true })
+ const state = makeToolExecutorState(filteredTools, { useSingleExec: true })
await executor.handleToolsList(state)
const result = (await executor.handleToolCall(
@@ -209,6 +159,38 @@ describe('ToolExecutor analytics capture', () => {
}
)
+ it.each([
+ ['states an intent', { command: 'tools', context: 'auditing the dashboard tiles' }],
+ ['states none', { command: 'tools' }],
+ ] as const)(
+ 'leaves the shared API client alone, so a concurrent call cannot pick up this intent — the agent %s',
+ async (_label, args) => {
+ vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})
+ const state = makeToolExecutorState([], { useSingleExec: true })
+
+ await executor.handleToolCall({ name: 'exec', arguments: args }, state)
+
+ expect(state.context.api.config.intent).toBeUndefined()
+ }
+ )
+
+ it('runs the call without an intent when the API client cannot carry one', async () => {
+ vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})
+ const state = makeToolExecutorState([], { useSingleExec: true })
+ state.context.api = mockApi({
+ withIntent: () => {
+ throw new Error('cannot copy this client')
+ },
+ }) as any
+
+ const result = (await executor.handleToolCall(
+ { name: 'exec', arguments: { command: 'tools', context: 'auditing the dashboard tiles' } },
+ state
+ )) as { isError?: boolean }
+
+ expect(result.isError).toBeFalsy()
+ })
+
it.each(['not_captured', 'capture_error'] as const)(
'records %s when analytics preparation cannot capture a supplied model',
async (reason) => {
@@ -223,7 +205,7 @@ describe('ToolExecutor analytics capture', () => {
const result = (await executor.handleToolCall(
{ name: 'exec', arguments: { command: 'tools', llm_model: 'example-model' } },
- makeState([], { useSingleExec: true })
+ makeToolExecutorState([], { useSingleExec: true })
)) as { isError?: boolean }
expect(result.isError).toBeFalsy()
@@ -241,7 +223,7 @@ describe('ToolExecutor analytics capture', () => {
// test. (projects-get hits the API, which the harness can't fulfill, so we
// assert on the captured analytics, not the tool's own result.)
it('strips analytics arguments before a native tool validates and forwards their values', async () => {
- const state = makeState([{ name: 'projects-get' }])
+ const state = makeToolExecutorState([{ name: 'projects-get' }])
await executor.handleToolsList(state)
const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})
@@ -278,13 +260,13 @@ describe('ToolExecutor analytics capture', () => {
{
label: 'native path',
call: { name: 'execute-sql', arguments: { query: 'SELECT 1' } },
- state: () => makeState([{ name: 'execute-sql' }]),
+ state: () => makeToolExecutorState([{ name: 'execute-sql' }]),
},
{
label: 'exec path',
call: { name: 'exec', arguments: { command: 'call execute-sql {"query": "SELECT 1"}' } },
state: () =>
- makeState(
+ makeToolExecutorState(
catalog.getFilteredTools({ scopes: ['*'] }).filter((tool) => tool.name === 'execute-sql'),
{ useSingleExec: false }
),
@@ -314,7 +296,7 @@ describe('ToolExecutor analytics capture', () => {
const result = (await executor.handleToolCall(
{ name: 'projects-get', arguments: {} },
- makeState([{ name: 'projects-get' }])
+ makeToolExecutorState([{ name: 'projects-get' }])
)) as any
expect(result.content).toBeTruthy()
diff --git a/services/mcp/tests/hono/tool-executor-metrics.test.ts b/services/mcp/tests/hono/tool-executor-metrics.test.ts
index 43a73a977286..25182afb37f9 100644
--- a/services/mcp/tests/hono/tool-executor-metrics.test.ts
+++ b/services/mcp/tests/hono/tool-executor-metrics.test.ts
@@ -51,7 +51,7 @@ import {
wrapError,
} from '@/lib/errors'
-import { toolFromPreBuilt } from '../shared/test-utils'
+import { makeToolExecutorState, mockApi, toolFromPreBuilt } from '../shared/test-utils'
const mockTrackToolCall = vi.mocked(trackToolCall)
@@ -61,58 +61,6 @@ function trackToolCallExtras(tool: string): Record<string, unknown> | undefined
return call?.[4]
}
-function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {
- return {
- reqCtx: {
- cache: { get: vi.fn(), set: vi.fn() },
- safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
- trackEvent: vi.fn(),
- trackContextSwitchEvent: vi.fn(),
- getSessionUuid: vi.fn().mockResolvedValue(undefined),
- getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
- } as any,
- context: {
- api: {},
- cache: {},
- env: {},
- stateManager: {},
- sessionManager: {},
- getDistinctId: vi.fn(),
- trackEvent: vi.fn(),
- } as any,
- useSingleExec: false,
- toolFeatureFlags: undefined,
- apiKeyScopes: [],
- oauthClientId: undefined,
- clientProfile: {
- capabilities: { supportsInstructions: true },
- isCliModeEnabled: vi.fn(() => false),
- isClaudeUiHost: vi.fn(() => false),
- isInlineExecUiHost: vi.fn(() => false),
- isClaudeChatHost: vi.fn(() => false),
- } as any,
- requestContext: {
- authMethod: 'personal_api_key',
- sessionId: 'sess-1',
- mcpClientName: 'test',
- mcpClientVersion: '1.0',
- mcpProtocolVersion: '2025-03-26',
- transport: 'streamable-http',
- },
- sessionContext: null,
- allTools: tools as any,
- scopeGatedTools: [],
- flagGatedTools: [],
- gatewayToolsEnabled: false,
- distinctId: 'test-distinct-id',
- renderUiEnabled: false,
- metadata: undefined,
- metadataCompact: undefined,
- groupTypes: undefined,
- ...overrides,
- }
-}
-
type FakeToolBase = { schema: z.ZodObject<Record<string, never>>; handler: ReturnType<typeof vi.fn>; _meta: undefined }
function makeFakeTool(
@@ -156,7 +104,10 @@ describe('ToolExecutor metrics', () => {
it('records success counter and duration timer', async () => {
vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('my-tool') as any)
- await executor.handleToolCall({ name: 'my-tool', arguments: {} }, makeState([{ name: 'my-tool' }]))
+ await executor.handleToolCall(
+ { name: 'my-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'my-tool' }])
+ )
expect(mockToolDurationStartTimer).toHaveBeenCalledWith({ tool: 'my-tool' })
expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'my-tool', status: 'success' })
@@ -170,7 +121,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'fail-tool', status: 'error' })
expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'fail-tool', error_type: 'internal' })
@@ -184,7 +138,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
expect(trackToolCallExtras('fail-tool')).toMatchObject({ $mcp_error_type: 'internal' })
})
@@ -204,7 +161,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
const extras = trackToolCallExtras('fail-tool')
expect(extras).toMatchObject({ $mcp_error_type: 'internal' })
@@ -230,7 +190,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
const extras = trackToolCallExtras('fail-tool')
expect(extras).toMatchObject({
@@ -278,7 +241,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
expect(trackToolCallExtras('fail-tool')).toMatchObject({ $mcp_error_message: expected })
})
@@ -301,7 +267,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
const extras = trackToolCallExtras('fail-tool')
expect(extras).toMatchObject({
@@ -325,7 +294,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
expect(trackToolCallExtras('fail-tool')).toMatchObject({
$mcp_error_message: 'HTTP 502 Bad Gateway on GET /api/environments/2/insights/',
@@ -341,7 +313,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
const message = trackToolCallExtras('fail-tool')?.$mcp_error_message as string
expect(message.startsWith('line2xxx')).toBe(true)
@@ -360,7 +335,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'execute-sql', arguments: {} }, makeState([{ name: 'execute-sql' }]))
+ await executor.handleToolCall(
+ { name: 'execute-sql', arguments: {} },
+ makeToolExecutorState([{ name: 'execute-sql' }])
+ )
expect(trackToolCallExtras('execute-sql')).toMatchObject({
$mcp_error_type: 'rate_limited',
@@ -382,7 +360,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'execute-sql', arguments: {} }, makeState([{ name: 'execute-sql' }]))
+ await executor.handleToolCall(
+ { name: 'execute-sql', arguments: {} },
+ makeToolExecutorState([{ name: 'execute-sql' }])
+ )
expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'execute-sql', error_type: 'rate_limited' })
})
@@ -402,7 +383,10 @@ describe('ToolExecutor metrics', () => {
}) as any
)
- await executor.handleToolCall({ name: 'execute-sql', arguments: {} }, makeState([{ name: 'execute-sql' }]))
+ await executor.handleToolCall(
+ { name: 'execute-sql', arguments: {} },
+ makeToolExecutorState([{ name: 'execute-sql' }])
+ )
expect(mockToolErrorsInc).toHaveBeenCalledWith({ tool: 'execute-sql', error_type: 'rate_limited' })
})
@@ -416,7 +400,10 @@ describe('ToolExecutor metrics', () => {
base: { schema: z.object({ required_field: z.string() }), handler: vi.fn(), _meta: undefined },
} as any)
- await executor.handleToolCall({ name: 'strict-tool', arguments: {} }, makeState([{ name: 'strict-tool' }]))
+ await executor.handleToolCall(
+ { name: 'strict-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'strict-tool' }])
+ )
expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'strict-tool', status: 'validation_error' })
expect(mockToolDurationStartTimer).not.toHaveBeenCalled()
@@ -437,7 +424,7 @@ describe('ToolExecutor metrics', () => {
await executor.handleToolCall(
{ name: 'strict-tool', arguments: { requiredField: 'sent under the wrong name' } },
- makeState([{ name: 'strict-tool' }])
+ makeToolExecutorState([{ name: 'strict-tool' }])
)
// Exactly one event: the rejection returns before the handler runs, so
@@ -459,7 +446,7 @@ describe('ToolExecutor metrics', () => {
})
it('records error for unknown tool', async () => {
- await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeState([]))
+ await executor.handleToolCall({ name: 'nonexistent', arguments: {} }, makeToolExecutorState([]))
expect(mockToolCallsInc).toHaveBeenCalledWith({ tool: 'nonexistent', status: 'error' })
})
@@ -473,7 +460,7 @@ describe('ToolExecutor metrics', () => {
const tools = catalog
.getPreBuiltEntries()
.map((entry) => toolFromPreBuilt(catalog.getToolByName(entry.name)!, entry))
- return makeState(tools as any, { useSingleExec: true })
+ return makeToolExecutorState(tools as any, { useSingleExec: true })
}
it('emits no exec-labelled counter or timer on success', async () => {
@@ -617,7 +604,7 @@ describe('ToolExecutor metrics', () => {
/** A context whose skill fetch resolves, so the success path runs. */
function contextThatServes(): any {
return {
- api: { request: vi.fn().mockResolvedValue({ name: 'conductor', body: 'skill body' }) },
+ api: mockApi({ request: vi.fn().mockResolvedValue({ name: 'conductor', body: 'skill body' }) }),
cache: {},
env: {},
stateManager: { getProjectId: vi.fn().mockResolvedValue('2') },
@@ -631,7 +618,7 @@ describe('ToolExecutor metrics', () => {
function contextThatRejects(): any {
return {
...contextThatServes(),
- api: {
+ api: mockApi({
request: vi.fn().mockRejectedValue(
new PostHogApiError({
status: 404,
@@ -641,7 +628,7 @@ describe('ToolExecutor metrics', () => {
method: 'GET',
})
),
- },
+ }),
}
}
@@ -650,7 +637,7 @@ describe('ToolExecutor metrics', () => {
function contextThatMisses(): any {
return {
...contextThatServes(),
- api: {
+ api: mockApi({
request: vi.fn().mockRejectedValue(
new PostHogApiError({
status: 404,
@@ -660,7 +647,7 @@ describe('ToolExecutor metrics', () => {
method: 'GET',
})
),
- },
+ }),
}
}
@@ -755,7 +742,7 @@ describe('ToolExecutor metrics', () => {
await executor.handleToolCall(
{ name: 'skill-get', arguments: { skill_name: 'conductor' } },
- makeState(tools as any, { context: contextThatServes() })
+ makeToolExecutorState(tools as any, { context: contextThatServes() })
)
expect(trackToolCallExtras('skill-get')).toMatchObject({ $mcp_skill_name: 'conductor' })
diff --git a/services/mcp/tests/hono/tool-executor-tokens.test.ts b/services/mcp/tests/hono/tool-executor-tokens.test.ts
index 43364781a7c8..600e6e1d6e09 100644
--- a/services/mcp/tests/hono/tool-executor-tokens.test.ts
+++ b/services/mcp/tests/hono/tool-executor-tokens.test.ts
@@ -25,64 +25,11 @@ vi.mock('@/resources', () => ({
import { z } from 'zod'
import { InstructionsBuilder } from '@/hono/instructions'
-import type { ResolvedState } from '@/hono/request-state-resolver'
import { ToolCatalog } from '@/hono/tool-catalog'
import { ToolExecutor } from '@/hono/tool-executor'
import { estimateTokens } from '@/lib/estimate-tokens'
-import { toolFromPreBuilt } from '../shared/test-utils'
-
-function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {
- return {
- reqCtx: {
- cache: { get: vi.fn(), set: vi.fn() },
- safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
- trackEvent: vi.fn(),
- trackContextSwitchEvent: vi.fn(),
- getSessionUuid: vi.fn().mockResolvedValue(undefined),
- getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
- } as any,
- context: {
- api: {},
- cache: {},
- env: {},
- stateManager: {},
- sessionManager: {},
- getDistinctId: vi.fn(),
- trackEvent: vi.fn(),
- } as any,
- useSingleExec: false,
- toolFeatureFlags: undefined,
- apiKeyScopes: [],
- oauthClientId: undefined,
- clientProfile: {
- capabilities: { supportsInstructions: true },
- isCliModeEnabled: vi.fn(() => false),
- isClaudeUiHost: vi.fn(() => false),
- isInlineExecUiHost: vi.fn(() => false),
- isClaudeChatHost: vi.fn(() => false),
- } as any,
- requestContext: {
- authMethod: 'personal_api_key',
- sessionId: 'sess-1',
- mcpClientName: 'test',
- mcpClientVersion: '1.0',
- mcpProtocolVersion: '2025-03-26',
- transport: 'streamable-http',
- },
- sessionContext: null,
- allTools: tools as any,
- scopeGatedTools: [],
- flagGatedTools: [],
- gatewayToolsEnabled: false,
- distinctId: 'test-distinct-id',
- renderUiEnabled: false,
- metadata: undefined,
- metadataCompact: undefined,
- groupTypes: undefined,
- ...overrides,
- }
-}
+import { makeToolExecutorState, toolFromPreBuilt } from '../shared/test-utils'
type FakeToolBase = {
schema: z.ZodObject<Record<string, never>>
@@ -139,7 +86,7 @@ describe('ToolExecutor token estimates', () => {
await executor.handleToolCall(
{ name: 'execute-sql', arguments: { query: 'SELECT 1' } },
- makeState([{ name: 'execute-sql' }])
+ makeToolExecutorState([{ name: 'execute-sql' }])
)
expect(mockTrackExecuteSqlGeneration).toHaveBeenCalledTimes(1)
@@ -152,7 +99,10 @@ describe('ToolExecutor token estimates', () => {
it('does not emit a generation for other tools', async () => {
vi.spyOn(catalog, 'getToolByName').mockReturnValue(makeFakeTool('my-tool') as any)
- await executor.handleToolCall({ name: 'my-tool', arguments: {} }, makeState([{ name: 'my-tool' }]))
+ await executor.handleToolCall(
+ { name: 'my-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'my-tool' }])
+ )
expect(mockTrackExecuteSqlGeneration).not.toHaveBeenCalled()
})
@@ -170,7 +120,7 @@ describe('ToolExecutor token estimates', () => {
const response = (await executor.handleToolCall(
{ name: 'my-tool', arguments: {} },
- makeState([{ name: 'my-tool' }])
+ makeToolExecutorState([{ name: 'my-tool' }])
)) as any
const [toolName, , isError, , extra] = mockTrackToolCall.mock.calls[0]!
@@ -196,7 +146,7 @@ describe('ToolExecutor token estimates', () => {
const response = (await executor.handleToolCall(
{ name: 'ui-tool', arguments: {} },
- makeState([{ name: 'ui-tool' }])
+ makeToolExecutorState([{ name: 'ui-tool' }])
)) as any
// structuredContent rides along for UI tools but must not be double-billed.
@@ -212,7 +162,10 @@ describe('ToolExecutor token estimates', () => {
}) as any
)
- await executor.handleToolCall({ name: 'fail-tool', arguments: {} }, makeState([{ name: 'fail-tool' }]))
+ await executor.handleToolCall(
+ { name: 'fail-tool', arguments: {} },
+ makeToolExecutorState([{ name: 'fail-tool' }])
+ )
const [toolName, , isError, , extra] = mockTrackToolCall.mock.calls[0]!
expect(toolName).toBe('fail-tool')
@@ -232,7 +185,7 @@ describe('ToolExecutor token estimates', () => {
const response = (await executor.handleToolCall(
{ name: 'exec', arguments: { command: 'tools' } },
- makeState(tools, { useSingleExec: true })
+ makeToolExecutorState(tools, { useSingleExec: true })
)) as any
const execCall = mockTrackToolCall.mock.calls.find((call) => call[0] === 'exec')!
@@ -250,7 +203,7 @@ describe('ToolExecutor token estimates', () => {
.map((entry) => toolFromPreBuilt(catalog.getToolByName(entry.name)!, entry))
const target = tools.find((t) => t.name === 'docs-search')! as any
target.handler = vi.fn(async () => 'inner-ok')
- const state = makeState(tools as any, { useSingleExec: true })
+ const state = makeToolExecutorState(tools as any, { useSingleExec: true })
await executor.handleToolCall(
{ name: 'exec', arguments: { command: 'call docs-search {"query":"hi"}' } },
diff --git a/services/mcp/tests/hono/tool-executor.test.ts b/services/mcp/tests/hono/tool-executor.test.ts
index d1300de6f908..1d5ae72fe324 100644
--- a/services/mcp/tests/hono/tool-executor.test.ts
+++ b/services/mcp/tests/hono/tool-executor.test.ts
@@ -24,6 +24,8 @@ import { makeSkillFile, SkillCatalog } from '@/skills/skill-catalog'
import { getToolDefinition } from '@/tools/toolDefinitions'
import { POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY } from '@/tools/types'
+import { makeToolExecutorState, mockApi } from '../shared/test-utils'
+
// A tool with a renderable (dispatchable) UI app — used to exercise the render-ui path.
const uiAppTool = {
name: 'survey-get',
@@ -31,57 +33,6 @@ const uiAppTool = {
_meta: { ui: { resourceUri: URI_MAP['survey'] } },
}
-function makeState(tools: { name: string }[], overrides: Partial<ResolvedState> = {}): ResolvedState {
- return {
- reqCtx: {
- cache: { get: vi.fn(), set: vi.fn() },
- safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
- trackEvent: vi.fn(),
- getSessionUuid: vi.fn().mockResolvedValue(undefined),
- getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
- } as any,
- context: {
- api: {},
- cache: {},
- env: {},
- stateManager: {},
- sessionManager: {},
- getDistinctId: vi.fn(),
- trackEvent: vi.fn(),
- } as any,
- useSingleExec: false,
- toolFeatureFlags: undefined,
- apiKeyScopes: [],
- oauthClientId: undefined,
- clientProfile: {
- capabilities: { supportsInstructions: true },
- isCliModeEnabled: vi.fn(() => false),
- isClaudeUiHost: vi.fn(() => false),
- isInlineExecUiHost: vi.fn(() => false),
- isClaudeChatHost: vi.fn(() => false),
- } as any,
- requestContext: {
- authMethod: 'personal_api_key',
- sessionId: 'sess-1',
- mcpClientName: 'test',
- mcpClientVersion: '1.0',
- mcpProtocolVersion: '2025-03-26',
- transport: 'streamable-http',
- },
- sessionContext: null,
- allTools: tools as any,
- scopeGatedTools: [],
- flagGatedTools: [],
- gatewayToolsEnabled: false,
- distinctId: 'test-distinct-id',
- renderUiEnabled: false,
- metadata: undefined,
- metadataCompact: undefined,
- groupTypes: undefined,
- ...overrides,
- }
-}
-
describe('ToolExecutor', () => {
let catalog: ToolCatalog
let executor: ToolExecutor
@@ -94,7 +45,7 @@ describe('ToolExecutor', () => {
describe('handleToolCall', () => {
it('returns error when tool name is missing', async () => {
- const result = (await executor.handleToolCall({}, makeState([]))) as any
+ const result = (await executor.handleToolCall({}, makeToolExecutorState([]))) as any
expect(result.isError).toBe(true)
expect(result.content[0].text).toContain('Missing tool name')
})
@@ -102,7 +53,7 @@ describe('ToolExecutor', () => {
it('returns error when tool does not exist', async () => {
const result = (await executor.handleToolCall(
{ name: 'nonexistent-tool', arguments: {} },
- makeState([])
+ makeToolExecutorState([])
)) as any
expect(result.isError).toBe(true)
expect(result.content[0].text).toContain('nonexistent-tool')
@@ -113,7 +64,10 @@ describe('ToolExecutor', () => {
const entries = catalog.getPreBuiltEntries()
const tool = entries[0]!
- const result = (await executor.handleToolCall({ name: tool.name, arguments: {} }, makeState([]))) as any
+ const result = (await executor.handleToolCall(
+ { name: tool.name, arguments: {} },
+ makeToolExecutorState([])
+ )) as any
expect(result.isError).toBe(true)
expect(result.content[0].text).toContain('not found')
})
@@ -126,7 +80,7 @@ describe('ToolExecutor', () => {
const result = (await executor.handleToolCall(
{ name: knownTool.name, arguments: { __invalid_field_xyz: 'bad' } },
- makeState([{ name: knownTool.name }])
+ makeToolExecutorState([{ name: knownTool.name }])
)) as any
expect(result).not.toBeNull()
@@ -141,7 +95,7 @@ describe('ToolExecutor', () => {
const result = (await executor.handleToolCall(
{ name: 'user-get', arguments: {} },
- makeState([{ name: 'user-get' }])
+ makeToolExecutorState([{ name: 'user-get' }])
)) as any
expect(result).not.toBeNull()
@@ -155,7 +109,7 @@ describe('ToolExecutor', () => {
const result = (await executor.handleToolCall(
{ name: 'exec', arguments: { command: 'tools' } },
- makeState(filteredTools, { useSingleExec: false })
+ makeToolExecutorState(filteredTools, { useSingleExec: false })
)) as any
expect(result.isError).toBeFalsy()
@@ -167,7 +121,7 @@ describe('ToolExecutor', () => {
function skillMissContext(skillName: string, body: string): ResolvedState['context'] {
return {
- api: {
+ api: mockApi({
request: vi.fn().mockRejectedValue(
new PostHogApiError({
status: 404,
@@ -177,7 +131,7 @@ describe('ToolExecutor', () => {
method: 'GET',
})
),
- },
+ }),
cache: {},
env: {},
stateManager: { getProjectId: vi.fn().mockResolvedValue('1') },
@@ -205,7 +159,7 @@ describe('ToolExecutor', () => {
'No file "refs/guide.md" in the skill "real-skill".',
],
])('answers a %s miss with the plain message in tools mode', async (name, args, body, expected) => {
- const state = makeState([{ name }], { context: skillMissContext(args.skill_name, body) })
+ const state = makeToolExecutorState([{ name }], { context: skillMissContext(args.skill_name, body) })
const result = (await executor.handleToolCall({ name, arguments: args }, state)) as any
@@ -245,7 +199,7 @@ describe('ToolExecutor', () => {
const tools = useExec
? catalog.getFilteredTools({ scopes: ['*'] }).filter((tool) => tool.name === 'skill-get')
: [{ name: 'skill-get' }]
- const state = makeState(tools as any, {
+ const state = makeToolExecutorState(tools as any, {
useSingleExec: useExec,
toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: skillsEnabled },
context: skillMissContext(skillName, `{"detail":"Skill with name '${skillName}' not found."}`),
@@ -268,19 +222,19 @@ describe('ToolExecutor', () => {
const allEntries = catalog.getPreBuiltEntries()
const subset = allEntries.slice(0, 3)
- const result = await executor.handleToolsList(makeState(subset.map((e) => ({ name: e.name }))))
+ const result = await executor.handleToolsList(makeToolExecutorState(subset.map((e) => ({ name: e.name }))))
expect(result.tools).toHaveLength(3)
expect(result.tools.map((t) => t.name)).toEqual(subset.map((e) => e.name))
})
it('returns empty list when allTools is empty', async () => {
- const result = await executor.handleToolsList(makeState([]))
+ const result = await executor.handleToolsList(makeToolExecutorState([]))
expect(result.tools).toEqual([])
})
it('returns single exec tool entry when useSingleExec is true', async () => {
- const state = makeState(
+ const state = makeToolExecutorState(
catalog
.getPreBuiltEntries()
.slice(0, 5)
@@ -358,7 +312,7 @@ describe('ToolExecutor', () => {
const skillExecutor = new ToolExecutor(catalog, new InstructionsBuilder(''), {
getCatalog: () => skills,
} as any)
- const state = makeState([], {
+ const state = makeToolExecutorState([], {
useSingleExec: true,
toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: skillsEnabled },
clientProfile: {
@@ -444,12 +398,12 @@ describe('ToolExecutor', () => {
}
return { count: 1, results: [{ name: 'team-retention' }] }
})
- const state = makeState([], {
+ const state = makeToolExecutorState([], {
useSingleExec: true,
toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },
apiKeyScopes: ['llm_skill:read'],
context: {
- api: { request: apiRequest },
+ api: mockApi({ request: apiRequest }),
stateManager: { getProjectId: vi.fn().mockResolvedValue(12) },
} as any,
})
@@ -479,7 +433,7 @@ describe('ToolExecutor', () => {
})
it('tells the agent project skills need the read scope instead of failing silently', async () => {
- const state = makeState([], {
+ const state = makeToolExecutorState([], {
useSingleExec: true,
toolFeatureFlags: { [MCP_EXEC_SKILLS_FEATURE_FLAG]: true },
apiKeyScopes: ['insight:read'],
@@ -528,7 +482,7 @@ describe('ToolExecutor', () => {
.map((e) => ({ name: e.name }))
const metadataMarker = 'CURRENT PROJECT: Acme (timezone America/New_York)'
- const state = makeState(tools, {
+ const state = makeToolExecutorState(tools, {
useSingleExec: true,
metadata: metadataMarker,
clientProfile: {
@@ -556,7 +510,7 @@ describe('ToolExecutor', () => {
)
it('serves multiple optional guidance topics through exec learn for Claude web/desktop', async () => {
- const state = makeState(
+ const state = makeToolExecutorState(
catalog
.getPreBuiltEntries()
.slice(0, 5)
@@ -587,7 +541,7 @@ describe('ToolExecutor', () => {
})
it('lists render-ui alongside exec when render-ui is enabled and a UI-app tool is available', async () => {
- const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
+ const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
const result = await executor.handleToolsList(state)
expect(result.tools.map((t) => t.name)).toEqual(['exec', 'render-ui'])
@@ -605,7 +559,7 @@ describe('ToolExecutor', () => {
})
it('omits render-ui when render-ui is disabled, even with a UI-app tool available', async () => {
- const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: false })
+ const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: false })
const result = await executor.handleToolsList(state)
expect(result.tools.map((t) => t.name)).toEqual(['exec'])
@@ -614,7 +568,7 @@ describe('ToolExecutor', () => {
describe('render-ui', () => {
it('dispatches to the render-ui payload when render-ui is enabled', async () => {
- const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
+ const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: true })
const result = (await executor.handleToolCall(
{ name: 'render-ui', arguments: { tool_name: 'survey-get', tool_input: { surveyId: 'abc' } } },
@@ -627,7 +581,7 @@ describe('ToolExecutor', () => {
})
it('rejects a render-ui call when render-ui is disabled', async () => {
- const state = makeState([uiAppTool], { useSingleExec: true, renderUiEnabled: false })
+ const state = makeToolExecutorState([uiAppTool], { useSingleExec: true, renderUiEnabled: false })
const result = (await executor.handleToolCall(
{ name: 'render-ui', arguments: { tool_name: 'survey-get', tool_input: { surveyId: 'abc' } } },
@@ -696,7 +650,7 @@ describe('ToolExecutor', () => {
},
} as any)
- const state = makeState([uiAppTool], { useSingleExec, renderUiEnabled })
+ const state = makeToolExecutorState([uiAppTool], { useSingleExec, renderUiEnabled })
vi.mocked(state.clientProfile.isCliModeEnabled).mockReturnValue(true)
if (posthogAi) {
state.clientProfile = { ...state.clientProfile, consumer: 'posthog_ai' } as typeof state.clientProfile
@@ -747,7 +701,7 @@ describe('ToolExecutor', () => {
const result = (await executor.handleToolCall(
{ name: metricRunTool.name, arguments: {} },
- makeState([metricRunTool], { useSingleExec: false })
+ makeToolExecutorState([metricRunTool], { useSingleExec: false })
)) as any
expect(result.content[0].text.includes('NONCANONICAL')).toBe(marked)
diff --git a/services/mcp/tests/shared/test-utils.ts b/services/mcp/tests/shared/test-utils.ts
index 9800d643abd5..ca99693eaf2b 100644
--- a/services/mcp/tests/shared/test-utils.ts
+++ b/services/mcp/tests/shared/test-utils.ts
@@ -1,6 +1,8 @@
import type { Tool as McpTool } from '@modelcontextprotocol/sdk/types.js'
+import { vi } from 'vitest'
import { ApiClient } from '@/api/client'
+import type { ResolvedState } from '@/hono/request-state-resolver'
import type { PreBuiltTool } from '@/hono/tool-catalog'
import { MemoryCache } from '@/lib/cache/MemoryCache'
import { SessionManager } from '@/lib/SessionManager'
@@ -644,3 +646,64 @@ export function toolFromPreBuilt(preBuilt: PreBuiltTool, entry: McpTool): Tool<Z
scopes: [],
}
}
+
+// `ToolExecutor` copies the client through `withIntent` before it runs a tool, so the mock needs
+// the real method or every call fails before it reaches the code under test.
+export function mockApi(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return { config: {}, withIntent: ApiClient.prototype.withIntent, ...overrides }
+}
+
+export function makeToolExecutorState(
+ tools: { name: string }[],
+ overrides: Partial<ResolvedState> = {}
+): ResolvedState {
+ return {
+ reqCtx: {
+ cache: { get: vi.fn(), set: vi.fn() },
+ safelyGetAnalyticsContext: vi.fn().mockResolvedValue(undefined),
+ trackEvent: vi.fn(),
+ trackContextSwitchEvent: vi.fn(),
+ getSessionUuid: vi.fn().mockResolvedValue(undefined),
+ getEffectiveSessionUuid: vi.fn().mockResolvedValue(undefined),
+ } as any,
+ context: {
+ api: mockApi(),
+ cache: {},
+ env: {},
+ stateManager: {},
+ sessionManager: {},
+ getDistinctId: vi.fn(),
+ trackEvent: vi.fn(),
+ } as any,
+ useSingleExec: false,
+ toolFeatureFlags: undefined,
+ apiKeyScopes: [],
+ oauthClientId: undefined,
+ clientProfile: {
+ capabilities: { supportsInstructions: true },
+ isCliModeEnabled: vi.fn(() => false),
+ isClaudeUiHost: vi.fn(() => false),
+ isInlineExecUiHost: vi.fn(() => false),
+ isClaudeChatHost: vi.fn(() => false),
+ } as any,
+ requestContext: {
+ authMethod: 'personal_api_key',
+ sessionId: 'sess-1',
+ mcpClientName: 'test',
+ mcpClientVersion: '1.0',
+ mcpProtocolVersion: '2025-03-26',
+ transport: 'streamable-http',
+ },
+ sessionContext: null,
+ allTools: tools as any,
+ scopeGatedTools: [],
+ flagGatedTools: [],
+ gatewayToolsEnabled: false,
+ distinctId: 'test-distinct-id',
+ renderUiEnabled: false,
+ metadata: undefined,
+ metadataCompact: undefined,
+ groupTypes: undefined,
+ ...overrides,
+ }
+}
diff --git a/services/mcp/tests/unit/api-client.test.ts b/services/mcp/tests/unit/api-client.test.ts
index d973b9be6d8f..89e1705558fc 100644
--- a/services/mcp/tests/unit/api-client.test.ts
+++ b/services/mcp/tests/unit/api-client.test.ts
@@ -200,6 +200,43 @@ describe('ApiClient', () => {
vi.unstubAllGlobals()
})
+ it.each([
+ [
+ 'forwards a stated intent',
+ 'Repairing a tile that hit the query row limit',
+ 'Repairing a tile that hit the query row limit',
+ ],
+ ['caps an overlong intent', 'i'.repeat(900), 'i'.repeat(500)],
+ ['strips characters a header cannot carry', 'Fixing the 📈 tile\nfor the user', 'Fixing the tilefor the user'],
+ ['omits an intent that is not a string', 42 as unknown as string, undefined],
+ ['omits the header when the agent stated none', undefined, undefined],
+ ] as const)('%s', async (_label, intent, expected) => {
+ const mockFetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({}), { status: 200 }))
+ vi.stubGlobal('fetch', mockFetch)
+ const client = new ApiClient({ apiToken: 'test-token-123', baseUrl: 'https://example.com', intent })
+
+ await client.request({ method: 'GET', path: '/api/projects/1/dashboards/' })
+
+ const [, options] = mockFetch.mock.calls[0]!
+ expect(options.headers['x-posthog-intent']).toBe(expected)
+ vi.unstubAllGlobals()
+ })
+
+ it('sends an intent only from the copy that carries it, so concurrent calls cannot cross', async () => {
+ // A fresh Response per call: a body can only be read once.
+ const mockFetch = vi.fn().mockImplementation(async () => new Response(JSON.stringify({}), { status: 200 }))
+ vi.stubGlobal('fetch', mockFetch)
+ const shared = new ApiClient({ apiToken: 'test-token-123', baseUrl: 'https://example.com' })
+
+ await shared.withIntent('auditing the dashboard tiles').request({ method: 'GET', path: '/api/projects/1/' })
+ await shared.request({ method: 'GET', path: '/api/projects/1/' })
+
+ expect(mockFetch.mock.calls[0]![1].headers['x-posthog-intent']).toBe('auditing the dashboard tiles')
+ expect(mockFetch.mock.calls[1]![1].headers).not.toHaveProperty('x-posthog-intent')
+ expect(shared.config.intent).toBeUndefined()
+ vi.unstubAllGlobals()
+ })
+
it.each([
[
'both ids set',
diff --git a/services/mcp/tests/unit/connection-forwarding.test.ts b/services/mcp/tests/unit/connection-forwarding.test.ts
index ae7ccf683f03..423145ee20d2 100644
--- a/services/mcp/tests/unit/connection-forwarding.test.ts
+++ b/services/mcp/tests/unit/connection-forwarding.test.ts
@@ -117,6 +117,27 @@ describe('posthog connection forwarding', () => {
})
})
+ it('forwards the tool intent with a forwarded request', async () => {
+ const fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ status: 200, data: {} })))
+ vi.stubGlobal('fetch', fetch)
+ const forwarding = new ForwardingApiClient(
+ new ApiClient({ apiToken: 'local-token', baseUrl: 'https://us.posthog.com' }),
+ {
+ connectionId: '99',
+ localProjectId: '7',
+ target: TARGET,
+ }
+ )
+
+ await forwarding.withIntent('updating the connected project').request({
+ method: 'POST',
+ path: '/api/projects/4242/insights/',
+ body: { name: 'Updated insight' },
+ })
+
+ expect(fetch.mock.calls[0]![1].headers['x-posthog-intent']).toBe('updating the connected project')
+ })
+
it('surfaces a status the target returned as a thrown API error', async () => {
// The forward endpoint answers 200 whatever the target said. Without re-raising it here,
// a tool reads the error envelope as a successful result and reports made-up data.