: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
fix(mcp): skip org fetch on init when key lacks organization:read (#58814)
Joshua Snyder47d4a035adbc
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.tsindex 9e5aaebdeb1e..72f274513d9f 100644--- a/services/mcp/src/lib/StateManager.ts+++ b/services/mcp/src/lib/StateManager.ts@@ -1,4 +1,5 @@import type { ApiClient, GroupType } from '@/api/client'+import { hasScope } from '@/lib/api'import { getPostHogClient } from '@/lib/analytics'import { ErrorCode, MissingOrganizationContextError, MissingProjectContextError, wrapError } from '@/lib/errors'import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'@@ -277,6 +278,14 @@ export class StateManager {if (!orgId) {return undefined}+ // `/api/organizations/{id}/` requires `organization:read`. Project-scoped+ // personal API keys do not carry that scope, so the fetch would 403 on+ // every session init and dogpile error tracking. Mirror the `group:read`+ // gate in `mcp.ts` and skip the fetch when the scope is absent.+ const apiKey = await this.getApiKey()+ if (!hasScope(apiKey.scopes, 'organization:read')) {+ return undefined+ }return this.getOrFetchCached({name: 'org',cacheKey: `cachedOrg:${orgId}` as const,diff --git a/services/mcp/src/lib/instructions.ts b/services/mcp/src/lib/instructions.tsindex 5fec56fdf834..760e55f1e08e 100644--- a/services/mcp/src/lib/instructions.ts+++ b/services/mcp/src/lib/instructions.ts@@ -20,11 +20,15 @@ export function buildActiveEnvironmentContextPrompt(if (org || project) {const projectName = project?.name ?? 'Unknown'const projectId = project?.id ?? 'unknown'- const orgName = org?.name ?? 'Unknown'- const orgId = org?.id ?? 'unknown'- lines.push(- `You are currently in project "${projectName}" (id: ${projectId}) within organization "${orgName}" (id: ${orgId}).`- )+ if (org) {+ const orgName = org.name ?? 'Unknown'+ const orgId = org.id ?? 'unknown'+ lines.push(+ `You are currently in project "${projectName}" (id: ${projectId}) within organization "${orgName}" (id: ${orgId}).`+ )+ } else {+ lines.push(`You are currently in project "${projectName}" (id: ${projectId}).`)+ }}if (project) {lines.push(`Project timezone: ${project.timezone ?? 'UTC'}.`)diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.tsindex 667ab57752ab..afb477c61201 100644--- a/services/mcp/tests/unit/StateManager.test.ts+++ b/services/mcp/tests/unit/StateManager.test.ts@@ -335,6 +335,53 @@ describe('StateManager', () => {expect(result).toBeUndefined()})++ it('skips the org fetch when the API key lacks organization:read', async () => {+ // Pre-#58726 behaviour: every MCP session init with a project-scoped+ // personal API key would 403 on `/api/organizations/{id}/` and+ // dogpile error tracking. The scope guard short-circuits before the+ // HTTP call so no exception is captured and the org is treated as+ // best-effort missing.+ await cache.set('orgId', 'org-1')+ vi.spyOn(stateManager, 'getApiKey').mockResolvedValue({+ scopes: ['project:read', 'insight:read'],+ scoped_organizations: [],+ scoped_teams: [456],+ })+ const orgGet = vi.fn()+ ;(stateManager as any)._api = {+ organizations: () => ({ get: orgGet }),+ }++ const result = await stateManager.getCachedOrFetchOrg()++ expect(result).toBeUndefined()+ expect(orgGet).not.toHaveBeenCalled()+ })++ it.each([['organization:read'], ['organization:write'], ['*']])(+ 'fetches the org when the API key carries %s',+ async (scope) => {+ await cache.set('orgId', 'org-1')+ vi.spyOn(stateManager, 'getApiKey').mockResolvedValue({+ scopes: [scope],+ scoped_organizations: [],+ scoped_teams: [],+ })+ const orgGet = vi.fn().mockResolvedValue({+ success: true,+ data: { id: 'org-1', name: 'Org 1' },+ })+ ;(stateManager as any)._api = {+ organizations: () => ({ get: orgGet }),+ }++ const result = await stateManager.getCachedOrFetchOrg()++ expect(orgGet).toHaveBeenCalledWith({ orgId: 'org-1' })+ expect(result).toMatchObject({ id: 'org-1', name: 'Org 1' })+ }+ )})describe('getProjectId', () => {diff --git a/services/mcp/tests/unit/instructions.test.ts b/services/mcp/tests/unit/instructions.test.tsindex 0b5757739f2f..85165b135a56 100644--- a/services/mcp/tests/unit/instructions.test.ts+++ b/services/mcp/tests/unit/instructions.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'import type { GroupType } from '@/api/client'import {+ buildActiveEnvironmentContextPrompt,buildDefinedGroupsBlock,buildQueryToolsBlock,buildQueryToolsCompact,@@ -10,6 +11,7 @@ import {QueryToolCatalog,type QueryToolInfo,} from '@/lib/instructions'+import type { CachedOrg, CachedProject, CachedUser } from '@/tools/types'describe('buildDefinedGroupsBlock', () => {it('should format group types as a comma-separated list of group_type names', () => {@@ -219,3 +221,50 @@ describe('QueryToolCatalog', () => {})})})++describe('buildActiveEnvironmentContextPrompt', () => {+ const project = {+ id: 1,+ name: 'My App',+ timezone: 'America/New_York',+ person_on_events_querying_enabled: false,+ } as unknown as CachedProject+ const org = { id: 'org_1', name: 'Acme' } as unknown as CachedOrg+ const user = { first_name: 'Jane', last_name: 'Doe', email: '[email protected]' } as unknown as CachedUser++ it('renders the full project + org line when both are present', () => {+ const result = buildActiveEnvironmentContextPrompt(user, org, project)+ expect(result).toContain(+ 'You are currently in project "My App" (id: 1) within organization "Acme" (id: org_1).'+ )+ })++ it('omits the organization clause when org is undefined (scope-gated path)', () => {+ // Project-scoped personal API keys lack `organization:read`, so the org+ // fetch is skipped. The line drops the "within organization …" tail+ // rather than rendering a fabricated "Unknown" placeholder.+ const result = buildActiveEnvironmentContextPrompt(user, undefined, project)+ expect(result).toContain('You are currently in project "My App" (id: 1).')+ expect(result).not.toContain('within organization')+ expect(result).not.toContain('Unknown')+ expect(result).not.toContain('unknown')+ })++ it('keeps the timezone and user lines when org is omitted', () => {+ const result = buildActiveEnvironmentContextPrompt(user, undefined, project)+ expect(result).toContain('Project timezone: America/New_York.')+ expect(result).toContain("The user's name is Jane Doe ([email protected]).")+ })++ it('returns undefined when no context is available at all', () => {+ expect(buildActiveEnvironmentContextPrompt(undefined, undefined, undefined)).toBeUndefined()+ })++ it('still renders an "Unknown" project when org is present but project is missing', () => {+ // The org branch is unchanged — only the no-org branch was added.+ const result = buildActiveEnvironmentContextPrompt(user, org, undefined)+ expect(result).toContain(+ 'You are currently in project "Unknown" (id: unknown) within organization "Acme" (id: org_1).'+ )+ })+})diff --git a/services/mcp/tests/workers/org-project-resolution.test.ts b/services/mcp/tests/workers/org-project-resolution.test.tsindex 33eadc7b3b9f..9602e91f7cc5 100644--- a/services/mcp/tests/workers/org-project-resolution.test.ts+++ b/services/mcp/tests/workers/org-project-resolution.test.ts@@ -194,6 +194,44 @@ describe('MCP org/project resolution inside the real Workers runtime', () => {})})+ it('init completes for a project-scoped API key without organization:read (no org fetch)', async () => {+ // Production scenario behind the dogpile silenced by #58726 and now+ // fixed at the source: a personal API key scoped to a single project+ // carries `project:read` but not `organization:read`. Pre-guard, every+ // session init would still issue GET /api/organizations/{id}/ from+ // both getEnvironmentPrompt and getAiConsentGiven and 403. The guard+ // short-circuits the fetch so the request path completes without+ // capturing the expected denial.+ vi.spyOn(StateManager.prototype, 'getApiKey').mockResolvedValue({+ scopes: ['project:read', 'insight:read'],+ scoped_teams: [1],+ scoped_organizations: [],+ })+ // Wrap, don't replace: the real implementation still runs and we+ // observe its behavior. Without the guard this would resolve to the+ // captured org fixture; with the guard it resolves to `undefined`.+ const orgFetchSpy = vi.spyOn(StateManager.prototype, 'getCachedOrFetchOrg')++ const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-project-scoped-no-org-read'))++ await runInDurableObject(stub, async (mcp: MCP) => {+ const bg = interceptWaitUntil(mcp)+ ;(mcp as any).props = propsFor()++ await expect(mcp.init()).resolves.toBeUndefined()++ // getEnvironmentPrompt and getAiConsentGiven both go through the+ // org fetcher — assert it was invoked and that each invocation+ // returned `undefined` without throwing.+ expect(orgFetchSpy).toHaveBeenCalled()+ for (const call of orgFetchSpy.mock.results) {+ await expect(call.value).resolves.toBeUndefined()+ }++ await bg.flush()+ })+ })+it('getProjectId throws MissingProjectContextError with the scoped org when no project is resolvable', async () => {const stub = env.MCP_OBJECT.get(env.MCP_OBJECT.idFromName('session-missing-project'))