:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): tag tool-call telemetry with the caller's scope preset (#91361)
posthog[bot]a4206631b834
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex a18f490c2fa4..d64895a5e913 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -2939,6 +2939,11 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"description": "The PostHog cloud region the MCP server routed the request to.","examples": ["us", "eu"],},+ "$mcp_scope_preset": {+ "label": "MCP scope preset",+ "description": "Which kind of caller minted the token behind an MCP request, worked out from its scope set. 'scout' is a Signals scout run, 'research' is a read-only report-research run, 'implementation' is a write-capable implementation run, 'sandbox' is any other server-minted run (a task started from the desktop app or the pipeline before the scratchpad scopes tell research and implementation apart), and 'user' is a person's own token. Stamped on every event by PostHog's own MCP server. Use it to split scratchpad and notes usage by caller, for example to measure scout scratchpad adoption apart from ordinary users.",+ "examples": ["scout", "research", "implementation", "sandbox", "user"],+ },"$mcp_oauth_client_name": {"label": "MCP OAuth client name","description": "The OAuth client name captured during the MCP handshake, when the connection used OAuth instead of a personal API key.",diff --git a/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md b/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.mdindex 00a7d3967f06..5fe69fc2535f 100644--- a/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md+++ b/products/mcp_analytics/skills/debugging-mcp-analytics/references/event-vocabulary.md@@ -64,6 +64,8 @@ server, so never rely on them in customer-facing queries or docs without checkin`$mcp_session_id` (transport-level), `$mcp_region`, `$mcp_mode`, `$mcp_consumer`,`$mcp_version`, `$mcp_client_user_agent` (no longer dogfood-only — the SDKs emit it too sinceTS 0.11.0 / Python 7.42.0), `$mcp_transport`, `$mcp_auth_method`,+`$mcp_scope_preset` (which kind of caller minted the token, worked out from its scope set:+`scout`, `research`, `implementation`, `sandbox` for any other server-minted run, or `user` for a person's own token; `research` and `implementation` need the scratchpad scopes and do not occur yet),`$mcp_organization_id`, `$mcp_project_id`, `$mcp_project_uuid`, `$mcp_project_name`,`$ai_product` (`mcp`), and the non-`$`-prefixed `mcp_runtime` (`hono`) and`mcp_vendor_client` — the last of which is the **top-priority harness signal**, so itdiff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.mdindex 1c628268e507..cab35c121d00 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-mcp.md@@ -68,7 +68,7 @@ And two tools cover what SQL can't express at all: `posthog:mcp-analytics-intent| `$mcp_resource_name` | SDK | Name of the MCP resource/prompt/tool the event refers to (resource-read and prompt-get events). || `$mcp_source` | SDK | Constant identifier for the analytics SDK that emitted the event (e.g. `posthog_mcp_analytics`). Lets you separate SDK-emitted events from other/legacy MCP paths. |-**Server-stamped extras (PostHog's own server only, not the SDK):** `$mcp_session_id` (transport-level session handle — see "Three identifiers" below), `$mcp_region` (cloud region that handled the request, e.g. `us`/`eu`), `$mcp_mode` (`cli` for single-exec, `tools` for one-tool-per-name), `$mcp_consumer` (upstream surface, e.g. `posthog-code`/`slack`), and the non-`$`-prefixed `mcp_vendor_client` (vendor/client identity from the `x-anthropic-client` header, e.g. `ClaudeCode`/`ClaudeAI` — used to resolve the harness in the bucketing SQL below) and `mcp_runtime` (server runtime, e.g. `hono`), plus `$mcp_auth_method` (which credential the request authenticated with, from the bearer token's prefix: `oauth`, `personal_api_key`, `id_jag`, `none`, `unknown`).+**Server-stamped extras (PostHog's own server only, not the SDK):** `$mcp_session_id` (transport-level session handle — see "Three identifiers" below), `$mcp_region` (cloud region that handled the request, e.g. `us`/`eu`), `$mcp_mode` (`cli` for single-exec, `tools` for one-tool-per-name), `$mcp_consumer` (upstream surface, e.g. `posthog-code`/`slack`), and the non-`$`-prefixed `mcp_vendor_client` (vendor/client identity from the `x-anthropic-client` header, e.g. `ClaudeCode`/`ClaudeAI` — used to resolve the harness in the bucketing SQL below) and `mcp_runtime` (server runtime, e.g. `hono`), plus `$mcp_auth_method` (which credential the request authenticated with, from the bearer token's prefix: `oauth`, `personal_api_key`, `id_jag`, `none`, `unknown`), plus `$mcp_scope_preset` (which kind of caller minted the token, worked out from its scope set: `scout`, `research`, `implementation`, `sandbox` for any other server-minted run, or `user` for a person's own token; `research` and `implementation` need the scratchpad scopes and do not occur yet).**Refused requests are a separate event.** A request the PostHog API rejects dies before any session, organization, or project is resolved, so it emits none of the events above — it emits `$mcp_auth_failed` instead, with `$mcp_auth_failure_reason` (`insufficient_scope`, `inactive_oauth_token`, `invalid_api_key`, `unknown`), `$mcp_missing_scope` when the API named a scope, and `$mcp_auth_status` (401/403). Only PostHog's own server emits it, so it is absent for customer-instrumented servers.diff --git a/services/mcp/src/cli/context.ts b/services/mcp/src/cli/context.tsindex c529d385a261..7f29cc48e87d 100644--- a/services/mcp/src/cli/context.ts+++ b/services/mcp/src/cli/context.ts@@ -5,6 +5,7 @@ import { MemoryCache } from '@/lib/cache/MemoryCache'import { getPostHogClient } from '@/lib/posthog'import { buildMCPAnalyticsGroups, buildMCPContextProperties } from '@/lib/posthog/analytics'import type { AnalyticsEvent } from '@/lib/posthog/analytics'+import { resolveScopePreset } from '@/lib/scope-preset'import { SessionManager } from '@/lib/SessionManager'import { StateManager } from '@/lib/StateManager'import { sanitizeHeaderValue } from '@/lib/utils'@@ -71,9 +72,10 @@ export async function buildCliContext(config: CliConfig): Promise<Context> {trackEvent: (event: AnalyticsEvent, properties: Record<string, unknown> = {}) => {const capture = (async (): Promise<void> => {try {- const [distinctId, analyticsContext] = await Promise.all([+ const [distinctId, analyticsContext, apiKey] = await Promise.all([stateManager.getDistinctId().catch(() => undefined),stateManager.getAnalyticsContext().catch(() => undefined),+ stateManager.getApiKey().catch(() => undefined),])const groups = analyticsContext ? buildMCPAnalyticsGroups(analyticsContext) : {}@@ -87,6 +89,7 @@ export async function buildCliContext(config: CliConfig): Promise<Context> {$mcp_client_name: 'posthog-cli',$mcp_consumer: 'posthog-cli',$mcp_mode: 'cli',+ $mcp_scope_preset: resolveScopePreset(apiKey?.scopes),$mcp_version: config.version,...(cliInvocationId ? { cli_invocation_id: cliInvocationId } : {}),...(analyticsContext ? buildMCPContextProperties(analyticsContext) : {}),diff --git a/services/mcp/src/hono/analytics.ts b/services/mcp/src/hono/analytics.tsindex 3fd3ae437e93..717e1acc878e 100644--- a/services/mcp/src/hono/analytics.ts+++ b/services/mcp/src/hono/analytics.ts@@ -15,6 +15,7 @@ import {type MCPAnalyticsContext,} from '@/lib/posthog/analytics'import type { RequestProperties } from '@/lib/request-properties'+import { resolveScopePreset } from '@/lib/scope-preset'import { EXECUTE_SQL_TOOL_NAME } from '@/tools/posthogAiTools/executeSql'import { MAX_CAPTURED_DESCRIPTION_LENGTH, getToolCategory, getToolDescription } from '@/tools/toolDefinitions'@@ -64,6 +65,9 @@ function buildBaseProperties($mcp_mode: requestContext.mode,$mcp_region: requestContext.region,$mcp_auth_method: requestContext.authMethod,+ // Which kind of caller minted this token — scout, research run, implementation run, or+ // ordinary user — so scratchpad and notes calls split by caller in one breakdown.+ $mcp_scope_preset: resolveScopePreset(state.apiKeyScopes),...(analyticsContext? {$mcp_organization_id: analyticsContext.organizationId,diff --git a/services/mcp/src/lib/scope-preset.ts b/services/mcp/src/lib/scope-preset.tsnew file mode 100644index 000000000000..781985a33e67--- /dev/null+++ b/services/mcp/src/lib/scope-preset.ts@@ -0,0 +1,84 @@+// Which kind of caller a token belongs to, stamped as `$mcp_scope_preset` on every `$mcp_*`+// event so scratchpad and notes usage can be split by scout vs report research vs+// implementation run vs any other server-minted sandbox run vs ordinary user.+//+// Derived from the token's scope set, not read from the token. The sandbox token is minted in+// `posthog/temporal/oauth.py::create_oauth_access_token_for_user` from a preset name, but that+// name is not carried on the token today, so this recovers it from the scopes the server+// already has. If the token later carries the preset name verbatim, report that instead and+// delete this derivation — it must not stay a second source of truth.++// Minted server-side only for a Signals scout run (`SCOUT_INTERNAL_SCOPES` in+// `posthog/temporal/oauth.py`). Its presence proves the caller is a scout.+const SCOUT_INTERNAL_WRITE_SCOPE = 'signal_scout_internal:write'++// Minted server-side only for the report-research and implementation pipeline runs that share+// the fleet scratchpad. Added by the scope-split work; absent today, so pipeline callers fall+// through to `user` until that lands.+const SCRATCHPAD_INTERNAL_WRITE_SCOPE = 'signal_scratchpad_internal:write'++// Every server-minted token carries `task:write` (INTERNAL_SCOPES), so it cannot tell a+// read-only research run apart from a write-capable implementation run. Excluded here.+const ALWAYS_PRESENT_WRITE_SCOPES = new Set(['task:write'])++// Provenance marker on every server-minted token (INTERNAL_SCOPES). `internal_run` is not a+// user-grantable scope object, so a token carrying it came from a sandbox run, never from a+// person's own key or consent grant. It says "sandbox", not which kind: until the scratchpad+// scope lands, the report-research and implementation runs land here rather than in `user`.+const SERVER_MINTED_MARKER_SCOPE = 'internal_run:read'++// Scope objects minted server-side only (mirrors SERVER_MINT_ONLY_SCOPE_OBJECTS in `api.ts`+// plus the scratchpad object). A `:write` on one of these is internal provenance, not the+// user-facing write access that separates an implementation run from a research run.+const INTERNAL_WRITE_SCOPE_OBJECTS = new Set([+ 'internal_run',+ 'loop_context_internal',+ 'mcp_builtin_agent',+ 'signal_scout_internal',+ 'signal_scout_report',+ 'signal_scratchpad_internal',+])++export const MCP_SCOPE_PRESET = {+ SCOUT: 'scout',+ RESEARCH: 'research',+ IMPLEMENTATION: 'implementation',+ SANDBOX: 'sandbox',+ USER: 'user',+} as const++export type McpScopePreset = (typeof MCP_SCOPE_PRESET)[keyof typeof MCP_SCOPE_PRESET]++// True when the token holds a user-facing write scope — the signal that separates an+// implementation run (writes) from a research run (read-only base).+function hasUserFacingWriteScope(scopes: readonly string[]): boolean {+ return scopes.some((scope) => {+ if (!scope.endsWith(':write') || ALWAYS_PRESENT_WRITE_SCOPES.has(scope)) {+ return false+ }+ const object = scope.split(':', 1)[0]+ return object !== undefined && !INTERNAL_WRITE_SCOPE_OBJECTS.has(object)+ })+}++/**+ * Resolve the caller kind behind a token from its scope set.+ *+ * A scout is settled first: its own internal write scope is proof on its own. A pipeline run+ * carries the scratchpad write scope without the scout one, and splits into a read-only+ * research run and a write-capable implementation run. Any other token that carries the+ * server-minted marker is a sandbox run of unknown kind. Everything else is an ordinary user.+ */+export function resolveScopePreset(scopes: readonly string[] | undefined): McpScopePreset {+ const scopeSet = scopes ?? []+ if (scopeSet.includes(SCOUT_INTERNAL_WRITE_SCOPE)) {+ return MCP_SCOPE_PRESET.SCOUT+ }+ if (scopeSet.includes(SCRATCHPAD_INTERNAL_WRITE_SCOPE)) {+ return hasUserFacingWriteScope(scopeSet) ? MCP_SCOPE_PRESET.IMPLEMENTATION : MCP_SCOPE_PRESET.RESEARCH+ }+ if (scopeSet.includes(SERVER_MINTED_MARKER_SCOPE)) {+ return MCP_SCOPE_PRESET.SANDBOX+ }+ return MCP_SCOPE_PRESET.USER+}diff --git a/services/mcp/tests/scope-preset.test.ts b/services/mcp/tests/scope-preset.test.tsnew file mode 100644index 000000000000..8496ee264cc0--- /dev/null+++ b/services/mcp/tests/scope-preset.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest'++import { MCP_SCOPE_PRESET, resolveScopePreset } from '@/lib/scope-preset'++// Every server-minted token carries `task:write` and `internal_run:read` (INTERNAL_SCOPES in+// `posthog/temporal/oauth.py`), so each sandbox set below includes them.+const INTERNAL_SCOPES = ['task:write', 'internal_run:read']++// A scout token, as `resolve_scopes` mints for `signals_scout`: reads plus the scout-internal+// write scope and the narrow user-facing writes.+const SCOUT_SCOPES = [...INTERNAL_SCOPES, 'insight:read', 'signal_scout_internal:write', 'notebook:write']++// The two pipeline sets carry `signal_scratchpad_internal:write`, which no preset mints yet.+// They describe the `signals_research` / `signals_implementation` presets the scope-split work+// adds, so these cases pin the classifier's contract ahead of it.+const RESEARCH_SCOPES = [...INTERNAL_SCOPES, 'insight:read', 'dashboard:read', 'signal_scratchpad_internal:write']+const IMPLEMENTATION_SCOPES = [+ ...INTERNAL_SCOPES,+ 'insight:read',+ 'insight:write',+ 'dashboard:write',+ 'signal_scratchpad_internal:write',+]++// What `read_only` and `full` mint today for every other sandbox run, the report-research and+// implementation runs included: server-minted, no caller-specific scope.+const READ_ONLY_SANDBOX_SCOPES = [...INTERNAL_SCOPES, 'insight:read', 'dashboard:read']+const FULL_SANDBOX_SCOPES = [...INTERNAL_SCOPES, 'insight:read', 'insight:write', 'dashboard:write']++// A person's own token (personal API key or OAuth consent) never carries `internal_run:read`.+const READ_ONLY_USER_SCOPES = ['insight:read', 'dashboard:read']+const FULL_USER_SCOPES = ['insight:read', 'insight:write', 'dashboard:write', 'task:write']++describe('resolveScopePreset', () => {+ it.each([+ ['a scout token', SCOUT_SCOPES, MCP_SCOPE_PRESET.SCOUT],+ ['a research token', RESEARCH_SCOPES, MCP_SCOPE_PRESET.RESEARCH],+ ['an implementation token', IMPLEMENTATION_SCOPES, MCP_SCOPE_PRESET.IMPLEMENTATION],+ ["a read-only sandbox token (today's research run)", READ_ONLY_SANDBOX_SCOPES, MCP_SCOPE_PRESET.SANDBOX],+ ["a full sandbox token (today's implementation run)", FULL_SANDBOX_SCOPES, MCP_SCOPE_PRESET.SANDBOX],+ ['a read-only user token', READ_ONLY_USER_SCOPES, MCP_SCOPE_PRESET.USER],+ ['a full user token', FULL_USER_SCOPES, MCP_SCOPE_PRESET.USER],+ ['no scopes at all', [], MCP_SCOPE_PRESET.USER],+ ['undefined scopes', undefined, MCP_SCOPE_PRESET.USER],+ ])('classifies %s', (_label, scopes, expected) => {+ expect(resolveScopePreset(scopes)).toBe(expected)+ })++ it('reads as a scout even when the scratchpad write scope is also present', () => {+ expect(resolveScopePreset(['signal_scout_internal:write', 'signal_scratchpad_internal:write'])).toBe(+ MCP_SCOPE_PRESET.SCOUT+ )+ })+})diff --git a/services/mcp/tests/unit/cli-context.test.ts b/services/mcp/tests/unit/cli-context.test.tsindex c2a680d101b6..24512bb4e8eb 100644--- a/services/mcp/tests/unit/cli-context.test.ts+++ b/services/mcp/tests/unit/cli-context.test.ts@@ -6,6 +6,7 @@ import { AnalyticsEvent } from '@/lib/posthog/analytics'const mocks = vi.hoisted(() => ({capture: vi.fn(),getAnalyticsContext: vi.fn(),+ getApiKey: vi.fn(),getDistinctId: vi.fn(),}))@@ -19,6 +20,7 @@ vi.mock('@/lib/StateManager', () => ({StateManager: class {getDistinctId = mocks.getDistinctIdgetAnalyticsContext = mocks.getAnalyticsContext+ getApiKey = mocks.getApiKey},}))@@ -29,8 +31,10 @@ describe('CLI context', () => {mocks.capture.mockClear()mocks.getDistinctId.mockReset()mocks.getAnalyticsContext.mockReset()+ mocks.getApiKey.mockReset()mocks.getDistinctId.mockRejectedValue(new Error('offline'))mocks.getAnalyticsContext.mockRejectedValue(new Error('offline'))+ mocks.getApiKey.mockRejectedValue(new Error('offline'))})it('uses an opaque analytics distinct ID when identity resolution fails', async () => {@@ -56,6 +60,7 @@ describe('CLI context', () => {expect(mocks.capture).toHaveBeenCalledWith(expect.objectContaining({distinctId: 'posthog-cli:anonymous',+ properties: expect.objectContaining({ $mcp_scope_preset: 'user' }),}))})