: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): add organization discovery to workspace tools (#71976)
posthog[bot]c02f03f6bbb0
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 4c999e65351d..c0bb49e654d2 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6950,6 +6950,20 @@"readOnlyHint": true}},+ "organizations-get": {+ "description": "Fetches the organizations that the user has access to, with their id, name, and membership level. Use this to discover organizations — including ones other than the active organization — and to resolve an organization name to the id you pass to `switch-organization`.",+ "category": "Organization & project management",+ "feature": "workspace",+ "summary": "Fetches the organizations that the user has access to.",+ "title": "Get organizations",+ "required_scopes": ["organization:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"organizations-list": {"description": "List all organizations the user has access to. Returns org ID, name, slug, and membership level. Use the ID with organization-get for details or switch-organization to change context.","category": "Platform Features",@@ -9232,7 +9246,7 @@}},"switch-organization": {- "description": "Switch the active PostHog organization for subsequent tool calls. Call this proactively whenever the user names an organization they want to operate on. Use `organizations-list` to resolve an organization name to an id. Default to the active organization when no specific organization is mentioned.",+ "description": "Switch the active PostHog organization for subsequent tool calls. Call this proactively whenever the user names an organization they want to operate on. Use `organizations-get` to resolve an organization name to an id. Default to the active organization when no specific organization is mentioned.","category": "Organization & project management","feature": "workspace","summary": "Switch the active PostHog organization for subsequent tool calls.",@@ -9246,7 +9260,7 @@}},"switch-project": {- "description": "Switch the active PostHog project for subsequent tool calls. Call this proactively whenever the user names a project or workspace they want to operate on. Use `projects-get` to resolve a project name to an id. If the project isn't found, the user may be referring to a project in a different organization, in which case call `organizations-list` and `switch-organization` first, then retry `projects-get`. Default to the active project when no specific project is mentioned.",+ "description": "Switch the active PostHog project for subsequent tool calls. Call this proactively whenever the user names a project or workspace they want to operate on. Use `projects-get` to resolve a project name to an id. If the project isn't found, the user may be referring to a project in a different organization, in which case call `organizations-get` and `switch-organization` first, then retry `projects-get`. Default to the active project when no specific project is mentioned.","category": "Organization & project management","feature": "workspace","summary": "Switch the active PostHog project for subsequent tool calls.",diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.jsonindex cc1f021c8d5d..bab733c9aedf 100644--- a/services/mcp/schema/tool-definitions.json+++ b/services/mcp/schema/tool-definitions.json@@ -351,8 +351,22 @@"readOnlyHint": true}},+ "organizations-get": {+ "description": "Fetches the organizations that the user has access to, with their id, name, and membership level. Use this to discover organizations — including ones other than the active organization — and to resolve an organization name to the id you pass to `switch-organization`.",+ "category": "Organization & project management",+ "feature": "workspace",+ "summary": "Fetches the organizations that the user has access to.",+ "title": "Get organizations",+ "required_scopes": ["organization:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"switch-organization": {- "description": "Switch the active PostHog organization for subsequent tool calls. Call this proactively whenever the user names an organization they want to operate on. Use `organizations-list` to resolve an organization name to an id. Default to the active organization when no specific organization is mentioned.",+ "description": "Switch the active PostHog organization for subsequent tool calls. Call this proactively whenever the user names an organization they want to operate on. Use `organizations-get` to resolve an organization name to an id. Default to the active organization when no specific organization is mentioned.","category": "Organization & project management","feature": "workspace","summary": "Switch the active PostHog organization for subsequent tool calls.",@@ -422,7 +436,7 @@}},"switch-project": {- "description": "Switch the active PostHog project for subsequent tool calls. Call this proactively whenever the user names a project or workspace they want to operate on. Use `projects-get` to resolve a project name to an id. If the project isn't found, the user may be referring to a project in a different organization, in which case call `organizations-list` and `switch-organization` first, then retry `projects-get`. Default to the active project when no specific project is mentioned.",+ "description": "Switch the active PostHog project for subsequent tool calls. Call this proactively whenever the user names a project or workspace they want to operate on. Use `projects-get` to resolve a project name to an id. If the project isn't found, the user may be referring to a project in a different organization, in which case call `organizations-get` and `switch-organization` first, then retry `projects-get`. Default to the active project when no specific project is mentioned.","category": "Organization & project management","feature": "workspace","summary": "Switch the active PostHog project for subsequent tool calls.",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex c14652efaa5a..1cb631d74a2c 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -531,6 +531,10 @@},"required": ["insightId"]},+ "OrganizationGetAllSchema": {+ "type": "object",+ "properties": {}+ },"OrganizationSetActiveSchema": {"anyOf": [{@@ -538,7 +542,7 @@"properties": {"orgId": {"type": "string",- "description": "The organization to switch to: the `id` returned by `organizations-list` (a UUID-like string, not the organization name). Use `organizations-list` to resolve a name to its id."+ "description": "The organization to switch to: the `id` returned by `organizations-get` (a UUID-like string, not the organization name). Use `organizations-get` to resolve a name to its id."}},"required": ["orgId"]diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.tsindex e41a586369b9..9da6141e62cb 100644--- a/services/mcp/src/lib/errors.ts+++ b/services/mcp/src/lib/errors.ts@@ -56,7 +56,7 @@ function formatMissingProjectContextMessage(organizationId: string | undefined):'2. If you already know the project id, call `switch-project { projectId: <id> }` directly.\n' +'3. (For MCP client maintainers) Pin a project at session start by sending the `x-posthog-project-id` header on the initialize request.' +'\n\n' +- 'If `projects-get` returns nothing, call `organizations-list` followed by `switch-organization` to pick a different org first — then retry `projects-get`.'+ 'If `projects-get` returns nothing, call `organizations-get` followed by `switch-organization` to pick a different org first — then retry `projects-get`.')}@@ -79,7 +79,7 @@ function formatMissingOrganizationContextMessage(): string {'No PostHog organization is selected for this MCP session, and a default could not be derived from your API key.' +'\n\n' +'To pick one (in order of preference):\n' +- '1. Call `organizations-list` to list organizations you can access, then `switch-organization` with the chosen organization id.\n' ++ '1. Call `organizations-get` to list organizations you can access, then `switch-organization` with the chosen organization id.\n' +'2. (For MCP client maintainers) Pin an organization at session start by sending the `x-posthog-organization-id` header on the initialize request.')}diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex e46cfced0172..477820566611 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -371,7 +371,7 @@ export const OrganizationSetActiveSchema = zorgId: z.string().describe(- 'The organization to switch to: the `id` returned by `organizations-list` (a UUID-like string, not the organization name). Use `organizations-list` to resolve a name to its id.'+ 'The organization to switch to: the `id` returned by `organizations-get` (a UUID-like string, not the organization name). Use `organizations-get` to resolve a name to its id.'),}),z.object({ id: z.string().describe(orgIdAliasDescription) }),@@ -379,7 +379,7 @@ export const OrganizationSetActiveSchema = zz.object({ organization_id: z.string().describe(orgIdAliasDescription) }),z.object({ org_id: z.string().describe(orgIdAliasDescription) }),],- { error: () => 'provide the organization id via "orgId" (get it from organizations-list)' }+ { error: () => 'provide the organization id via "orgId" (get it from organizations-get)' }).transform((data) => ({orgId:@@ -394,6 +394,8 @@ export const OrganizationSetActiveSchema = z: data.org_id,}))+export const OrganizationGetAllSchema = z.object({})+export const ProjectGetAllSchema = z.object({})export const EventDefinitionUpdateInputSchema = z.object({diff --git a/services/mcp/src/tools/index.ts b/services/mcp/src/tools/index.tsindex 3531a8e6ba8c..a54c0a174c05 100644--- a/services/mcp/src/tools/index.ts+++ b/services/mcp/src/tools/index.ts@@ -23,6 +23,7 @@ import generateAppUrl from './links/generate-app-url'// Notebooks (edit is hand-written — generated CRUD lives in generated/notebooks.ts)import notebookEdit from './notebooks/edit'// Organizations+import getOrganizations from './organizations/getOrganizations'import setActiveOrganization from './organizations/setActive'// PostHog AI toolsimport {@@ -60,6 +61,7 @@ import { workflowsArchive, workflowsEnable } from './workflows/lifecycle'// Map of tool names to tool factory functionsexport const TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> = {// Organizations+ 'organizations-get': getOrganizations,'switch-organization': setActiveOrganization,// Projectsdiff --git a/services/mcp/src/tools/organizations/getOrganizations.ts b/services/mcp/src/tools/organizations/getOrganizations.tsnew file mode 100644index 000000000000..7df5bcf2dfed--- /dev/null+++ b/services/mcp/src/tools/organizations/getOrganizations.ts@@ -0,0 +1,37 @@+import type { Schemas } from '@/api/generated'+import { wrapError } from '@/lib/errors'+import { OrganizationGetAllSchema } from '@/schema/tool-inputs'+import { pickResponseFields } from '@/tools/tool-utils'+import type { Context, ToolBase } from '@/tools/types'++const schema = OrganizationGetAllSchema++// Mirror the allowlist the generated `organizations-list` tool applies. The+// `/api/organizations/` rows are serialized by the full `OrganizationSerializer`+// (billing `customer_id`, `available_product_features`, 2FA/AI/security+// settings, nested teams/projects, ...), so returning them verbatim would+// broaden what workspace clients receive well beyond the id/name/membership+// data this discovery tool advertises.+const ORGANIZATION_FIELDS = ['id', 'name', 'slug', 'membership_level']++export const getOrganizationsHandler: ToolBase<typeof schema, Partial<Schemas.OrganizationBasic>[]>['handler'] = async (+ context: Context+) => {+ const orgsResult = await context.api.organizations().list()++ if (!orgsResult.success) {+ // Preserve the typed API error as `cause` so `handleToolError` can still+ // classify a recoverable 4xx and keep it out of exception tracking.+ throw wrapError(`Failed to get organizations: ${orgsResult.error.message}`, orgsResult.error)+ }++ return orgsResult.data.map((org: Schemas.OrganizationBasic) => pickResponseFields(org, ORGANIZATION_FIELDS))+}++const tool = (): ToolBase<typeof schema, Partial<Schemas.OrganizationBasic>[]> => ({+ name: 'organizations-get',+ schema,+ handler: getOrganizationsHandler,+})++export default tooldiff --git a/services/mcp/src/tools/projects/setActive.ts b/services/mcp/src/tools/projects/setActive.tsindex f1a01e255d92..1c170f50d619 100644--- a/services/mcp/src/tools/projects/setActive.ts+++ b/services/mcp/src/tools/projects/setActive.ts@@ -1,5 +1,6 @@import type { z } from 'zod'+import { wrapError } from '@/lib/errors'import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'import { ProjectSetActiveSchema } from '@/schema/tool-inputs'import type { CachedOrg, CachedProject, CachedUser, Context, ToolBase } from '@/tools/types'@@ -17,27 +18,67 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asynconst { projectId } = paramsconst projectIdStr = projectId.toString()- await context.cache.set('projectId', projectIdStr)+ // Resolve the active org the same way every other org-scoped tool does+ // (`getOrgID` falls back to the API-key default and the cached project),+ // rather than reading the raw `orgId` cache key which is often unset on the+ // first call and would make the org comparison below always look like a switch.+ const activeOrgId = await context.stateManager.getOrgID().catch(() => undefined)+ const activeOrgLabel = activeOrgId ?? 'unknown'- // Fetch fresh project data and cache it- let project: CachedProject | undefined+ // Validate before committing the session: only switch to a project the user+ // can actually access. Previously the projectId was cached before the fetch,+ // so a bad id (or a project the session can't reach) silently "succeeded" and+ // every later call failed with an opaque error instead.const projectResult = await context.api.projects().get({ projectId: projectIdStr })- if (projectResult.success) {- project = projectResult.data- await context.cache.set(`cachedProject:${projectIdStr}` as const, project)- await context.cache.set(`cachedProjectFetchedAt:${projectIdStr}` as const, Date.now())+ if (!projectResult.success) {+ // Preserve the typed API error as `cause`: a not-found / no-access 404-403+ // is a recoverable agent mistake that `handleToolError` should keep out of+ // exception tracking, while a genuine 5xx still gets captured.+ throw wrapError(+ `Could not switch to project ${projectIdStr}: it was not found or you don't have access to it from the active organization (${activeOrgLabel}). ` ++ 'If the project belongs to a different organization, call `organizations-get` to list your organizations, then `switch-organization` to the one that owns it, and retry. ' ++ 'Use `projects-get` to see the projects available in the active organization.',+ projectResult.error+ )+ }++ const project: CachedProject = projectResult.data+ await context.cache.set('projectId', projectIdStr)+ await context.cache.set(`cachedProject:${projectIdStr}` as const, project)+ await context.cache.set(`cachedProjectFetchedAt:${projectIdStr}` as const, Date.now())++ // Keep the active organization consistent with the project we just selected.+ // Switching to a project in another organization would otherwise leave+ // org-scoped tools pointed at the wrong organization.+ let orgId = activeOrgId+ let org: CachedOrg | undefined+ let switchedOrg = false+ const projectOrgId = project.organization+ if (projectOrgId && projectOrgId !== activeOrgId) {+ await context.cache.set('orgId', projectOrgId)+ orgId = projectOrgId+ // Only a genuine switch if a different org was already active; when no org+ // was resolved yet we're just establishing context, not switching away.+ switchedOrg = activeOrgId !== undefined+ // Fetch the org through the shared resolver so the scoped-token guard+ // (which skips the non-project-nested `/api/organizations/{id}/` call the+ // backend rejects for project-scoped keys) and org caching stay in one+ // place instead of being duplicated here and drifting.+ org = await context.stateManager.getCachedOrFetchOrg()}- // Read cached user and org for full metadata block+ // Read cached user (and org, when we didn't just fetch it) for the metadata blockconst distinctId = (await context.cache.get('distinctId')) ?? 'unknown'- const orgId = (await context.cache.get('orgId')) ?? 'unknown'const user = (await context.cache.get(`cachedUser:${distinctId}` as const)) as CachedUser | undefined- const org = (await context.cache.get(`cachedOrg:${orgId}` as const)) as CachedOrg | undefined+ if (!org && orgId) {+ org = (await context.cache.get(`cachedOrg:${orgId}` as const)) as CachedOrg | undefined+ }+ const orgNote = switchedOrg ? ` (also switched the active organization to ${orgId} to match)` : ''const metadata = buildActiveEnvironmentContextPrompt(user, org, project, context.api.publicBaseUrl)const text = metadata- ? `Switched to project ${projectId}.\n\nCurrent context:\n${metadata}`- : `Switched to project ${projectId}`+ ? `Switched to project ${projectId}${orgNote}.\n\nCurrent context:\n${metadata}`+ : `Switched to project ${projectId}${orgNote}`return {content: [{ type: 'text', text }],diff --git a/services/mcp/tests/integration/feature-routing.test.ts b/services/mcp/tests/integration/feature-routing.test.tsindex b54b6936227b..4d3a4e61fb83 100644--- a/services/mcp/tests/integration/feature-routing.test.ts+++ b/services/mcp/tests/integration/feature-routing.test.ts@@ -61,6 +61,14 @@ describe('Feature Routing Integration', () => {'projects-get',],},+ {+ // Organization discovery must ship with the workspace navigation tools —+ // otherwise an agent can switch orgs but has no way to enumerate them,+ // stranding any project that lives in a different organization.+ features: ['workspace'],+ description: 'workspace feature includes organization discovery',+ expectedTools: ['organizations-get', 'switch-organization', 'projects-get', 'switch-project'],+ },{features: ['invalid', 'flags', 'unknown'],description: 'valid tools ignoring invalid features',diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.tsindex 7eea103780d9..fa54487cd737 100644--- a/services/mcp/tests/integration/mcp-protocol-suite.ts+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts@@ -1024,19 +1024,18 @@ export function defineToolBehaviorTests(expect(text.toLowerCase()).toContain('invalid')})- it('switch-project does a soft switch: a non-existent project id still resolves', async () => {- // switch-project writes the requested id to the cache before- // calling PostHog to fetch project metadata. When the project- // doesn't exist the metadata fetch fails, but the cache write- // has already landed — so the tool returns success and the- // content references the requested id. This is the documented- // soft-switch contract: agents pinning to an id they don't- // strictly own won't get a hard error.+ it('switch-project validates the project: a non-existent project id returns an error', async () => {+ // switch-project fetches the project from PostHog before committing+ // the id to the session cache. When the project doesn't exist (or the+ // session can't reach it), the fetch fails with a 404 and the tool+ // returns an isError payload instead of silently "succeeding". This is+ // the validating contract: agents can't pin to a project they don't+ // actually have access to.const result = await client.callTool({name: 'switch-project',arguments: { projectId: 999_999_999 },})- expect(result.isError).toBeFalsy()+ expect(result.isError).toBe(true)const text = decodeText(result.content)expect(text).toContain('999999999')})diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/organizations-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/organizations-get.jsonnew file mode 100644index 000000000000..7b7ea9186078--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/organizations-get.json@@ -0,0 +1,5 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {},+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/switch-organization.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/switch-organization.jsonindex a57d012430db..0d24f14c5ca4 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/switch-organization.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/switch-organization.json@@ -4,7 +4,7 @@{"properties": {"orgId": {- "description": "The organization to switch to: the `id` returned by `organizations-list` (a UUID-like string, not the organization name). Use `organizations-list` to resolve a name to its id.",+ "description": "The organization to switch to: the `id` returned by `organizations-get` (a UUID-like string, not the organization name). Use `organizations-get` to resolve a name to its id.","type": "string"}},diff --git a/services/mcp/tests/unit/organizations-get.test.ts b/services/mcp/tests/unit/organizations-get.test.tsnew file mode 100644index 000000000000..cce65d6b9631--- /dev/null+++ b/services/mcp/tests/unit/organizations-get.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it, vi } from 'vitest'++import getOrganizationsTool from '@/tools/organizations/getOrganizations'+import type { Context } from '@/tools/types'++function createMockContext(list: ReturnType<typeof vi.fn>): Context {+ return {+ api: { organizations: () => ({ list }) },+ cache: {},+ stateManager: {},+ env: {},+ sessionManager: {},+ getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},+ } as unknown as Context+}++describe('organizations-get', () => {+ const tool = getOrganizationsTool()++ it('is registered under the expected tool name', () => {+ expect(tool.name).toBe('organizations-get')+ })++ it('returns accessible organizations filtered to the safe id/name/slug/membership fields', async () => {+ // The `/api/organizations/` rows carry the full serializer, so the raw+ // data includes billing/security fields the tool must not expose.+ const orgs = [+ {+ id: 'org-a',+ name: 'Org A',+ slug: 'org-a',+ membership_level: 8,+ customer_id: 'cus_secret',+ available_product_features: [{ key: 'sso' }],+ },+ {+ id: 'org-b',+ name: 'Org B',+ slug: 'org-b',+ membership_level: 1,+ enforce_2fa: true,+ is_hipaa: true,+ },+ ]+ const list = vi.fn().mockResolvedValue({ success: true, data: orgs })++ const result = await tool.handler(createMockContext(list), {})++ expect(result).toEqual([+ { id: 'org-a', name: 'Org A', slug: 'org-a', membership_level: 8 },+ { id: 'org-b', name: 'Org B', slug: 'org-b', membership_level: 1 },+ ])+ for (const org of result) {+ expect(org).not.toHaveProperty('customer_id')+ expect(org).not.toHaveProperty('available_product_features')+ expect(org).not.toHaveProperty('enforce_2fa')+ expect(org).not.toHaveProperty('is_hipaa')+ }+ })++ it('throws a descriptive error and preserves the API error cause when the list request fails', async () => {+ const apiError = new Error('boom')+ const list = vi.fn().mockResolvedValue({ success: false, error: apiError })++ let caught: (Error & { cause?: unknown }) | undefined+ try {+ await tool.handler(createMockContext(list), {})+ } catch (e) {+ caught = e as Error & { cause?: unknown }+ }++ expect(caught?.message).toMatch(/Failed to get organizations: boom/)+ // Preserving the cause lets handleToolError classify the recoverable 4xx+ // and keep it out of exception tracking.+ expect(caught?.cause).toBe(apiError)+ })+})diff --git a/services/mcp/tests/unit/switch-project.test.ts b/services/mcp/tests/unit/switch-project.test.tsnew file mode 100644index 000000000000..02b6c98c980f--- /dev/null+++ b/services/mcp/tests/unit/switch-project.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it, vi } from 'vitest'++import setActiveProjectTool from '@/tools/projects/setActive'+import type { Context } from '@/tools/types'++const ACTIVE_ORG = 'org-active'+const OTHER_ORG = 'org-other'++function createMockContext(overrides: {+ projectGet: ReturnType<typeof vi.fn>+ getOrgID?: ReturnType<typeof vi.fn>+ getCachedOrFetchOrg?: ReturnType<typeof vi.fn>+}): { context: Context; cache: Map<string, unknown>; getCachedOrFetchOrg: ReturnType<typeof vi.fn> } {+ const cache = new Map<string, unknown>()+ const getCachedOrFetchOrg = overrides.getCachedOrFetchOrg ?? vi.fn().mockResolvedValue(undefined)+ const context = {+ api: {+ publicBaseUrl: 'https://us.posthog.com',+ projects: () => ({ get: overrides.projectGet }),+ },+ cache: {+ get: async (key: string) => cache.get(key),+ set: async (key: string, value: unknown) => {+ cache.set(key, value)+ },+ },+ stateManager: {+ getOrgID: overrides.getOrgID ?? vi.fn().mockResolvedValue(ACTIVE_ORG),+ getCachedOrFetchOrg,+ },+ env: {},+ sessionManager: {},+ getDistinctId: async () => 'test-distinct-id',+ trackEvent: async () => {},+ } as unknown as Context+ return { context, cache, getCachedOrFetchOrg }+}++describe('switch-project', () => {+ const tool = setActiveProjectTool()++ it('does not commit the session, preserves the error cause, and guides the agent when the project is unreachable', async () => {+ const apiError = new Error('404')+ const projectGet = vi.fn().mockResolvedValue({ success: false, error: apiError })+ const { context, cache } = createMockContext({ projectGet })++ let caught: (Error & { cause?: unknown }) | undefined+ try {+ await tool.handler(context, { projectId: 999 })+ } catch (e) {+ caught = e as Error & { cause?: unknown }+ }++ expect(caught?.message).toMatch(+ /Could not switch to project 999.*active organization \(org-active\).*organizations-get.*switch-organization/s+ )+ // Keeping the typed error as cause keeps recoverable not-found/no-access+ // failures out of exception tracking.+ expect(caught?.cause).toBe(apiError)+ // A failed switch must not strand the session on an unreachable project.+ expect(cache.get('projectId')).toBeUndefined()+ })++ it('switches within the active organization without touching org state', async () => {+ const projectGet = vi.fn().mockResolvedValue({+ success: true,+ data: { id: 42, name: 'My project', organization: ACTIVE_ORG },+ })+ const { context, cache, getCachedOrFetchOrg } = createMockContext({ projectGet })++ const result = await tool.handler(context, { projectId: 42 })++ expect(result.content[0]!.text).toContain('Switched to project 42')+ expect(result.content[0]!.text).not.toContain('also switched the active organization')+ expect(cache.get('projectId')).toBe('42')+ expect(getCachedOrFetchOrg).not.toHaveBeenCalled()+ })++ it('syncs the active organization via the shared resolver when the project is in another org', async () => {+ const projectGet = vi.fn().mockResolvedValue({+ success: true,+ data: { id: 77, name: 'Cross-org project', organization: OTHER_ORG },+ })+ const getCachedOrFetchOrg = vi.fn().mockResolvedValue({ id: OTHER_ORG, name: 'Other org' })+ const { context, cache } = createMockContext({ projectGet, getCachedOrFetchOrg })++ const result = await tool.handler(context, { projectId: 77 })++ expect(result.content[0]!.text).toContain('also switched the active organization to org-other')+ expect(cache.get('projectId')).toBe('77')+ expect(cache.get('orgId')).toBe(OTHER_ORG)+ // Reuses the resolver (with its scoped-token guard) instead of calling the+ // org endpoint directly, which the backend rejects for project-scoped keys.+ expect(getCachedOrFetchOrg).toHaveBeenCalledTimes(1)+ })++ it('establishes org context without claiming a switch when no active org was resolved', async () => {+ const projectGet = vi.fn().mockResolvedValue({+ success: true,+ data: { id: 55, name: 'Scoped project', organization: OTHER_ORG },+ })+ // Team-scoped keys resolve no org on the first call, and getCachedOrFetchOrg+ // returns undefined for them (the org endpoint is rejected for such tokens).+ const getOrgID = vi.fn().mockRejectedValue(new Error('no org'))+ const { context, cache } = createMockContext({ projectGet, getOrgID })++ const result = await tool.handler(context, { projectId: 55 })++ expect(result.content[0]!.text).toContain('Switched to project 55')+ expect(result.content[0]!.text).not.toContain('also switched the active organization')+ expect(cache.get('orgId')).toBe(OTHER_ORG)+ })+})