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): guard StateManager against null current_team and current_organization (#59870)

posthog[bot]7a9e38f15612
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index 15b24aba7c29..83fcb93303d9 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -117,22 +117,33 @@ export class StateManager {
// otherwise pick the first scoped team deterministically. The org is
// omitted here — `getAnalyticsContext` recovers it from the project.
if (scoped_teams.length > 0) {
- if (scoped_teams.includes(activeTeam.id)) {
+ if (activeTeam && scoped_teams.includes(activeTeam.id)) {
return { projectId: activeTeam.id }
}
return { projectId: scoped_teams[0]! }
}
// No team scoping: prefer the user's active org/team when the scope
- // allows it.
- if (scoped_organizations.length === 0 || scoped_organizations.includes(activeOrganization.id)) {
- return { organizationId: activeOrganization.id, projectId: activeTeam.id }
+ // allows it. `activeOrganization` / `activeTeam` can be null for users
+ // with no `current_organization` / `current_team` (newly provisioned
+ // accounts, users who left their last org) — fall through to the
+ // scoped-org fallback below when either is missing.
+ if (activeOrganization && (scoped_organizations.length === 0 || scoped_organizations.includes(activeOrganization.id))) {
+ return activeTeam
+ ? { organizationId: activeOrganization.id, projectId: activeTeam.id }
+ : { organizationId: activeOrganization.id }
}
- // Active org isn't in the scope. Pick the first allowed org and fall
- // back to its first project. If the project lookup fails or the org has
- // no projects, return the org alone and let the agent disambiguate.
- const organizationId = scoped_organizations[0]!
+ // Active org isn't in the scope (or the user has no active org). Pick
+ // the first allowed org and fall back to its first project. If the
+ // project lookup fails or the org has no projects, return the org alone
+ // and let the agent disambiguate. With no scoped orgs and no active
+ // org, we have nothing to anchor on — return empty and let the caller
+ // surface a recoverable missing-context error.
+ const organizationId = scoped_organizations[0]
+ if (!organizationId) {
+ return {}
+ }
try {
const projectsResult = await this._api.organizations().projects({ orgId: organizationId }).list()
if (projectsResult.success && projectsResult.data.length > 0) {
diff --git a/services/mcp/src/schema/api.ts b/services/mcp/src/schema/api.ts
index 2b072b69bb78..ad1e5e6573be 100644
--- a/services/mcp/src/schema/api.ts
+++ b/services/mcp/src/schema/api.ts
@@ -9,16 +9,20 @@ export interface ApiUser {
last_name?: string
email: string
organizations: Array<{ id: string; name: string }>
+ // `team` and `organization` mirror the Django User's nullable `current_team`
+ // / `current_organization` FKs — the `/api/users/@me/` serializer returns
+ // `null` when the user has no current selection (e.g. newly provisioned
+ // accounts or users who left their last org). Callers must null-check.
team: {
id: number
name: string
timezone: string
organization: string
- }
+ } | null
organization: {
id: string
name: string
- }
+ } | null
}
// `scoped_teams` and `scoped_organizations` arrive from the API as either an
diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.ts
index 033cc77e71cb..1a5e0dc76e1a 100644
--- a/services/mcp/tests/unit/StateManager.test.ts
+++ b/services/mcp/tests/unit/StateManager.test.ts
@@ -212,6 +212,68 @@ describe('StateManager', () => {
expect(await cache.get('projectId')).toBeUndefined()
})
+ it('falls back to the first scoped team when the user has no active team', async () => {
+ // Regression: `/api/users/@me/` returns `team: null` when the user
+ // has no `current_team` (newly provisioned account, left last
+ // org). Reading `.id` on the null team would 500 the whole request
+ // before any tool dispatch.
+ const teamScopedApiKey = {
+ ...mockApiKey,
+ scoped_teams: [123, 456],
+ }
+ const userWithoutCurrent: ApiUser = { ...mockUser, team: null, organization: null }
+
+ vi.spyOn(stateManager, 'getApiKey').mockResolvedValue(teamScopedApiKey)
+ vi.spyOn(stateManager, 'getUser').mockResolvedValue(userWithoutCurrent)
+
+ const result = await stateManager.setDefaultOrganizationAndProject()
+
+ expect(result.projectId).toBe(123)
+ expect(result.organizationId).toBeUndefined()
+ })
+
+ it('falls back to the first scoped org when the user has no active org', async () => {
+ // Same regression for the org-scoped branch: reading
+ // `activeOrganization.id` on null would 500 the request.
+ const scopedOrgApiKey = {
+ ...mockApiKey,
+ scoped_organizations: ['org-3'],
+ }
+ const userWithoutCurrent: ApiUser = { ...mockUser, team: null, organization: null }
+
+ const mockApi = stateManager as any
+ vi.spyOn(stateManager, 'getApiKey').mockResolvedValue(scopedOrgApiKey)
+ vi.spyOn(stateManager, 'getUser').mockResolvedValue(userWithoutCurrent)
+
+ mockApi._api = {
+ organizations: () => ({
+ projects: () => ({
+ list: vi.fn().mockResolvedValue({ success: true, data: [789] }),
+ }),
+ }),
+ }
+
+ const result = await stateManager.setDefaultOrganizationAndProject()
+
+ expect(result.organizationId).toBe('org-3')
+ expect(result.projectId).toBe(789)
+ })
+
+ it('returns empty context when the user has no active org and the key is unscoped', async () => {
+ // With nothing to anchor on (no scoped teams, no scoped orgs, no
+ // current_organization) the resolver should surface a recoverable
+ // missing-context state rather than crash or fabricate an org id.
+ const userWithoutCurrent: ApiUser = { ...mockUser, team: null, organization: null }
+
+ vi.spyOn(stateManager, 'getApiKey').mockResolvedValue(mockApiKey)
+ vi.spyOn(stateManager, 'getUser').mockResolvedValue(userWithoutCurrent)
+
+ const result = await stateManager.setDefaultOrganizationAndProject()
+
+ expect(result.organizationId).toBeUndefined()
+ expect(result.projectId).toBeUndefined()
+ })
+
it('returns the org alone when the projects fetch fails', async () => {
const scopedOrgApiKey = {
...mockApiKey,