: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): forward the OAuth client name on outbound PostHog API calls (#74178)
Sinan Kucukkoseler723ab65754f7
diff --git a/products/notebooks/backend/analytics.py b/products/notebooks/backend/analytics.pyindex d4827c72ee2b..bb2f76804a78 100644--- a/products/notebooks/backend/analytics.py+++ b/products/notebooks/backend/analytics.py@@ -50,7 +50,6 @@ def capture_notebook_created(created_by_id: int | None = None,request: "Request | None" = None,mcp_consumer: str | None = None,- mcp_oauth_client: str | None = None,api_key_type: str | None = None,conversation_id: str | None = None,topic: str | None = None,@@ -66,7 +65,6 @@ def capture_notebook_created("creation_source": creation_source,**_optional_props(mcp_consumer=mcp_consumer,- mcp_oauth_client=mcp_oauth_client,api_key_type=api_key_type,conversation_id=conversation_id,topic=topic,@@ -97,7 +95,6 @@ def capture_notebook_read(is_creator: bool,user_access_level: str | None = None,mcp_consumer: str | None = None,- mcp_oauth_client: str | None = None,api_key_type: str | None = None,) -> None:"""Emit `notebook read` for a programmatic (non-browser) notebook retrieve. Browser opens are@@ -110,7 +107,6 @@ def capture_notebook_read(**_optional_props(user_access_level=user_access_level,mcp_consumer=mcp_consumer,- mcp_oauth_client=mcp_oauth_client,api_key_type=api_key_type,),}diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex 15127773f453..41eb02e64cae 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -111,17 +111,17 @@ def classify_request_source(request: Request) -> tuple[str, dict[str, str | None"""Classify a notebook request as a browser action (``ui``) vs a programmatic client (``mcp``/API).Session-cookie requests are the browser; anything else (personal API key, OAuth app) is a- programmatic client. The PostHog MCP server forwards the client identity so PostHog Desktop can be- told apart from a customer's own MCP client: ``mcp_consumer`` is ``posthog-code``/``posthog-cli``- for first-party PostHog Desktop, and ``mcp_oauth_client`` is the OAuth app name (e.g. Claude) for- third-party clients. Shared by the create and read events."""+ programmatic client. ``mcp_consumer`` is the wrapping app the PostHog MCP server forwards+ (``posthog-code``/``posthog-cli`` for first-party PostHog Desktop), which tells it apart from a+ customer's own MCP client. The third-party OAuth app name (e.g. Claude) rides along on every+ request-bound event as ``mcp_oauth_client_name`` via ``get_request_analytics_properties``, so it+ isn't repeated here. Shared by the create and read events."""authenticator = getattr(request, "successful_authenticator", None)if authenticator is None or isinstance(authenticator, SessionAuthentication):return NotebookCreationSource.UI, {}return NotebookCreationSource.MCP, {"api_key_type": type(authenticator).__name__,"mcp_consumer": request.META.get("HTTP_X_POSTHOG_MCP_CONSUMER"),- "mcp_oauth_client": request.META.get("HTTP_X_POSTHOG_MCP_OAUTH_CLIENT_NAME"),}@@ -268,7 +268,6 @@ class NotebookSerializer(NotebookMinimalSerializer):visibility=notebook.visibility,node_count=notebook_node_count(notebook.content),mcp_consumer=source_props.get("mcp_consumer"),- mcp_oauth_client=source_props.get("mcp_oauth_client"),api_key_type=source_props.get("api_key_type"),)@@ -748,7 +747,6 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDis_creator=instance.created_by_id == getattr(request.user, "id", None),user_access_level=serializer.data.get("user_access_level"),mcp_consumer=source_props.get("mcp_consumer"),- mcp_oauth_client=source_props.get("mcp_oauth_client"),api_key_type=source_props.get("api_key_type"),)diff --git a/products/notebooks/backend/test/test_analytics.py b/products/notebooks/backend/test/test_analytics.pyindex 1415d24c3c09..06d8071a988c 100644--- a/products/notebooks/backend/test/test_analytics.py+++ b/products/notebooks/backend/test/test_analytics.py@@ -24,17 +24,15 @@ class _FakeKeyAuth:class _FakeRequest:- def __init__(self, authenticator, mcp_consumer=None, mcp_oauth_client=None):+ def __init__(self, authenticator, mcp_consumer=None):self.successful_authenticator = authenticatorself.META = {}if mcp_consumer is not None:self.META["HTTP_X_POSTHOG_MCP_CONSUMER"] = mcp_consumer- if mcp_oauth_client is not None:- self.META["HTTP_X_POSTHOG_MCP_OAUTH_CLIENT_NAME"] = mcp_oauth_client-def _fake_request(authenticator, mcp_consumer=None, mcp_oauth_client=None) -> Request:- return cast(Request, _FakeRequest(authenticator, mcp_consumer, mcp_oauth_client))+def _fake_request(authenticator, mcp_consumer=None) -> Request:+ return cast(Request, _FakeRequest(authenticator, mcp_consumer))class TestNotebookAnalytics(BaseTest):@@ -56,16 +54,11 @@ class TestNotebookAnalytics(BaseTest):self.assertEqual(extra, {})def test_classify_request_source_api_key_captures_mcp_client_identity(self):- # The MCP server forwards mcp_consumer (posthog-code -> PostHog Desktop) and mcp_oauth_client- # (the OAuth app, e.g. Claude), which is how Q4 (PostHog Desktop) is split from Q5.- source, extra = classify_request_source(- _fake_request(_FakeKeyAuth(), mcp_consumer="posthog-code", mcp_oauth_client="Claude")- )+ # The MCP server forwards mcp_consumer (posthog-code -> PostHog Desktop), which is how+ # PostHog Desktop is split from a customer's own MCP client.+ source, extra = classify_request_source(_fake_request(_FakeKeyAuth(), mcp_consumer="posthog-code"))self.assertEqual(source, NotebookCreationSource.MCP)- self.assertEqual(- extra,- {"api_key_type": "_FakeKeyAuth", "mcp_consumer": "posthog-code", "mcp_oauth_client": "Claude"},- )+ self.assertEqual(extra, {"api_key_type": "_FakeKeyAuth", "mcp_consumer": "posthog-code"})def test_classify_request_source_no_authenticator_defaults_to_ui(self):source, extra = classify_request_source(_fake_request(None))@@ -111,7 +104,7 @@ class TestNotebookAnalytics(BaseTest):args, _ = mock_report.call_argsself.assertEqual(args[0], self.user)self.assertEqual(args[1], NOTEBOOK_READ_EVENT)- # mcp_consumer flows through; mcp_oauth_client is unset and so dropped.+ # mcp_consumer flows through; the None-valued optional props are dropped.self.assertEqual(args[2],{diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.tsindex b21dd4a05914..804cff1899ba 100644--- a/services/mcp/src/hono/request-context.ts+++ b/services/mcp/src/hono/request-context.ts@@ -79,6 +79,13 @@ export class RequestContext {return this.tokenCache}+ private async readCachedOAuthClientName(): Promise<string | undefined> {+ if (!this.props.userHash) {+ return undefined+ }+ return (await this.tokenCache.get('clientName')) || undefined+ }+private async api(): Promise<ApiClient> {if (!this.apiInstance) {const customApiBaseUrl = getCustomApiBaseUrl()@@ -101,6 +108,11 @@ export class RequestContext {mcpClientVersion: this.props.mcpClientVersion,mcpProtocolVersion: this.props.mcpProtocolVersion,mcpConsumer: this.props.mcpConsumer,+ // Cached from a previous request's token introspection. On a cold cache this is+ // still unset here, so `StateManager` also stamps it onto the live client's config+ // the moment introspection resolves it — otherwise a token's first request would+ // reach the API unattributed.+ oauthClientName: await this.readCachedOAuthClientName(),taskId: this.props.taskId,})}diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.tsindex 6c51a80cbac8..2fc09cfc6c27 100644--- a/services/mcp/src/lib/StateManager.ts+++ b/services/mcp/src/lib/StateManager.ts@@ -76,6 +76,10 @@ export class StateManager {const sanitizedClientName = sanitizeHeaderValue(client_name)if (sanitizedClientName) {await this._cache.set('clientName', sanitizedClientName)+ // Introspection is the first point the OAuth app name is known, and the client was+ // already built for this request — stamp it on so the rest of the request forwards+ // `x-posthog-mcp-oauth-client-name` instead of waiting for the next cache hit.+ this._api.config.oauthClientName = sanitizedClientName}return {diff --git a/services/mcp/tests/hono/request-context.test.ts b/services/mcp/tests/hono/request-context.test.tsindex c8afd3831062..bb3dd8e7c8d9 100644--- a/services/mcp/tests/hono/request-context.test.ts+++ b/services/mcp/tests/hono/request-context.test.ts@@ -104,6 +104,22 @@ describe('RequestContext', () => {expect(config.baseUrl).toBe('https://us.posthog.com')expect(config.publicBaseUrl).toBe('https://us.posthog.com')})++ it.each([+ { label: 'cached OAuth client name', cached: 'Claude', expected: 'Claude' },+ { label: 'no cached OAuth client name', cached: undefined, expected: undefined },+ ])('passes $label through as oauthClientName', async ({ cached, expected }) => {+ const redis = fakeRedis()+ if (cached) {+ await redis.set('mcp:token:test-user:clientName', JSON.stringify(cached))+ }+ mockMe.mockResolvedValue({ success: true, data: { distinct_id: 'user-1' } })++ const ctx = new RequestContext(redis, env, makeProps())+ await ctx.getDistinctId()++ expect(mockApiClientCtor.mock.calls[0]![0].oauthClientName).toBe(expected)+ })})describe('getDistinctId', () => {diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.tsindex c8deecafea99..828f87a8ead2 100644--- a/services/mcp/tests/unit/StateManager.test.ts+++ b/services/mcp/tests/unit/StateManager.test.ts@@ -81,6 +81,36 @@ describe('StateManager', () => {})})+ describe('getApiKey', () => {+ function oauthApi(clientName: string | null): ApiClient {+ return {+ config: { apiToken: 'phx_test' },+ apiKeys: () => ({+ current: async () => ({ success: false, error: { message: 'not a personal key' } }),+ }),+ oauth: () => ({+ introspect: async () => ({+ success: true,+ data: { active: true, scope: 'insight:read', client_name: clientName },+ }),+ }),+ } as unknown as ApiClient+ }++ it.each([+ { label: 'an OAuth app name', clientName: 'Claude', expected: 'Claude' },+ { label: 'no OAuth app name', clientName: null, expected: undefined },+ ])('stamps $label onto the live client so the same request forwards it', async ({ clientName, expected }) => {+ const api = oauthApi(clientName)+ stateManager = new StateManager(cache, api)++ await stateManager.getApiKey()++ expect(api.config.oauthClientName).toBe(expected)+ expect(await cache.get('clientName')).toBe(expected)+ })+ })+describe('setDefaultOrganizationAndProject', () => {it('should handle team-scoped API key with single team', async () => {const teamScopedApiKey = {