Skip to content

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

fix(mcp): stop capturing 404s from default-org projects lookup (#65815)

posthog[bot]8063d3350fce
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index 24c1ad656ed7..90b717671fa8 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -1,7 +1,13 @@
import type { ApiClient, GroupType } from '@/api/client'
import { hasScope } from '@/lib/api'
import type { ScopedCache } from '@/lib/cache/ScopedCache'
-import { ErrorCode, MissingOrganizationContextError, MissingProjectContextError, wrapError } from '@/lib/errors'
+import {
+ ErrorCode,
+ MissingOrganizationContextError,
+ MissingProjectContextError,
+ PostHogApiError,
+ wrapError,
+} from '@/lib/errors'
import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'
import { getPostHogClient } from '@/lib/posthog'
import { sanitizeHeaderValue } from '@/lib/utils'
@@ -153,9 +159,23 @@ export class StateManager {
return { organizationId, projectId: Number(projectsResult.data[0]!) }
}
if (!projectsResult.success) {
- this._reportException(projectsResult.error, 'default_org_project_projects_list_failed', {
- organization_id: organizationId,
- })
+ // A 404 here means the API key/OAuth token points at an org the
+ // requesting user can no longer access (or a deleted org): the
+ // org-nested projects endpoint is scoped to the user's
+ // memberships. That's a recoverable user-config state — the
+ // agent recovers via switch-project/switch-organization — so
+ // warn instead of capturing, mirroring the 403 permission_denied
+ // path in client.ts. Only genuine 5xx/unexpected failures reach
+ // error tracking.
+ if (this._isRecoverableNotFound(projectsResult.error)) {
+ console.warn(
+ `[StateManager] Scoped org ${organizationId} projects lookup returned 404 (org not accessible to this user or deleted); falling back to org-only context`
+ )
+ } else {
+ this._reportException(projectsResult.error, 'default_org_project_projects_list_failed', {
+ organization_id: organizationId,
+ })
+ }
}
} catch (error) {
this._reportException(error, 'default_org_project_projects_list_threw', {
@@ -166,6 +186,15 @@ export class StateManager {
return { organizationId }
}
+ /**
+ * A 404 from the scoped-org projects lookup is an expected missing-context
+ * state (org deleted, or the user lost access to a still-scoped org), not a
+ * service bug. Treat it as recoverable so it stays out of error tracking.
+ */
+ private _isRecoverableNotFound(error: unknown): boolean {
+ return error instanceof PostHogApiError && error.status === 404
+ }
+
private _reportException(error: unknown, context: string, extra: Record<string, unknown> = {}): void {
try {
getPostHogClient().captureException(error, undefined, { tag: 'mcp', team: 'posthog_ai', context, ...extra })
diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.ts
index 3a6459e1105c..c082bc1dca0d 100644
--- a/services/mcp/tests/unit/StateManager.test.ts
+++ b/services/mcp/tests/unit/StateManager.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ApiClient } from '@/api/client'
import { MemoryCache } from '@/lib/cache/MemoryCache'
+import { PostHogApiError } from '@/lib/errors'
import { StateManager } from '@/lib/StateManager'
import type { ApiRedactedPersonalApiKey, ApiUser } from '@/schema/api'
import type { State } from '@/tools/types'
@@ -283,6 +284,7 @@ describe('StateManager', () => {
const mockApi = stateManager as any
vi.spyOn(stateManager, 'getApiKey').mockResolvedValue(scopedOrgApiKey)
vi.spyOn(stateManager, 'getUser').mockResolvedValue(mockUser)
+ const reportSpy = vi.spyOn(stateManager as any, '_reportException').mockImplementation(() => {})
mockApi._api = {
organizations: () => ({
@@ -299,6 +301,47 @@ describe('StateManager', () => {
expect(result.organizationId).toBe('org-3')
expect(result.projectId).toBeUndefined()
+ // Unexpected failures still reach error tracking.
+ expect(reportSpy).toHaveBeenCalledOnce()
+ })
+
+ it('does not capture a 404 from the scoped-org projects lookup', async () => {
+ // A misconfigured key pointed at a deleted or inaccessible org makes
+ // the org-nested projects endpoint return 404 on every retry. This
+ // is a recoverable user-config state, so it must not flood error
+ // tracking — the agent recovers via switch-project/switch-organization.
+ const scopedOrgApiKey = {
+ ...mockApiKey,
+ scoped_organizations: ['org-3'],
+ }
+
+ const mockApi = stateManager as any
+ vi.spyOn(stateManager, 'getApiKey').mockResolvedValue(scopedOrgApiKey)
+ vi.spyOn(stateManager, 'getUser').mockResolvedValue(mockUser)
+ const reportSpy = vi.spyOn(stateManager as any, '_reportException').mockImplementation(() => {})
+
+ mockApi._api = {
+ organizations: () => ({
+ projects: () => ({
+ list: vi.fn().mockResolvedValue({
+ success: false,
+ error: new PostHogApiError({
+ status: 404,
+ statusText: 'Not Found',
+ body: '{"detail":"Organization not found."}',
+ url: 'https://app.posthog.com/api/organizations/org-3/projects/',
+ method: 'GET',
+ }),
+ }),
+ }),
+ }),
+ }
+
+ const result = await stateManager.setDefaultOrganizationAndProject()
+
+ expect(result.organizationId).toBe('org-3')
+ expect(result.projectId).toBeUndefined()
+ expect(reportSpy).not.toHaveBeenCalled()
})
})