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): accept project id aliases when switching projects (#123249)

Richard Solomouf6b40562d278
diff --git a/services/mcp/README.md b/services/mcp/README.md
index b6fc9d626b40..ec10f3b9b93f 100644
--- a/services/mcp/README.md
+++ b/services/mcp/README.md
@@ -414,6 +414,8 @@ Startup waits up to 45 seconds for Redis to become ready, including connection r
Each MCP transport session keeps its own active organization and project, including connections without a `project_id` or `organization_id` pin. An unpinned session starts from the user's active organization and project, within the credential's allowed scope. Later website changes and switches in other MCP sessions do not change that selection. `switch-project` and `switch-organization` update only the calling session; switching to another organization clears the previous project.
+`switch-project` requires a positive integer `projectId`. It also accepts `project_id` and `new_project_id` as aliases. If several are supplied, `projectId` takes precedence, followed by `project_id`.
+
Clients without an MCP session ID use the SDK's `conversation_id` instead. Echo the handle returned by the first tool call on subsequent calls. A switch without a carried session or conversation handle returns an error and a new handle; retry with that handle to apply the switch. Conversation state is bound to the credential and stored separately from transport sessions. Calls without either identity start from the connection's pin or default selection. If your client cannot retain conversation handles, pin the project or organization in the connection URL.
Legacy JSON-RPC batches restore each call's conversation handle independently. The wrapper's `sessionId` query parameter is an analytics hint and does not replace a conversation handle; wrapper-only calls still receive a new handle from the SDK.
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 89f06eb49e15..80bbcdac3bc1 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -787,9 +787,12 @@ export const PathCleaningRulesUpdateSchema = z.object({
),
})
-export const ProjectSetActiveSchema = z.object({
- projectId: z.number().int().positive(),
-})
+export const ProjectSetActiveSchema = z.preprocess(
+ normalizeParamAliases({ projectId: ['project_id', 'new_project_id'] }),
+ z.object({
+ projectId: z.number().int().positive(),
+ })
+)
const taskAgentRunOptions = {
// Use a pattern because JSON Schema's date-time format requires a timezone offset.
diff --git a/services/mcp/tests/hono/pinned-context-switch.test.ts b/services/mcp/tests/hono/pinned-context-switch.test.ts
index 76da246da854..d9260780f2cc 100644
--- a/services/mcp/tests/hono/pinned-context-switch.test.ts
+++ b/services/mcp/tests/hono/pinned-context-switch.test.ts
@@ -256,25 +256,32 @@ describe('pinned project with switch-project (Hono)', () => {
apiPaths.length = 0
})
- it('runs query and billing tools against the switched project, and keeps other sessions on the pin', async () => {
- const token = 'phx_switch'
- const switched = await callTool(
- 'switch-project',
- { projectId: Number(OTHER_PROJECT) },
- { token, sessionId: 'session-a' }
- )
- expect(switched.isError).toBeFalsy()
- expect(switched.text).toContain(`Switched to project ${OTHER_PROJECT}`)
+ it.each(['projectId', 'project_id', 'new_project_id'])(
+ 'switches via %s, runs tools against the switched project, and keeps other sessions on the pin',
+ async (key) => {
+ const token = `phx_switch_${key}`
+ const switched = await callTool(
+ 'switch-project',
+ { [key]: Number(OTHER_PROJECT) },
+ { token, sessionId: 'session-a' }
+ )
+ expect(switched.isError).toBeFalsy()
+ expect(switched.text).toContain(`Switched to project ${OTHER_PROJECT}`)
- // Each call resends the same pin, which must not revert the switch.
- expect(await runQueryAndBilling({ token, sessionId: 'session-a' })).toEqual(pathsFor(OTHER_PROJECT, OTHER_ORG))
+ // Each call resends the same pin, which must not revert the switch.
+ expect(await runQueryAndBilling({ token, sessionId: 'session-a' })).toEqual(
+ pathsFor(OTHER_PROJECT, OTHER_ORG)
+ )
- // A second session on the same credential keeps its own pin.
- expect(await runQueryAndBilling({ token, sessionId: 'session-b' })).toEqual(
- pathsFor(PINNED_PROJECT, PINNED_ORG)
- )
- expect(await runQueryAndBilling({ token, sessionId: 'session-a' })).toEqual(pathsFor(OTHER_PROJECT, OTHER_ORG))
- })
+ // A second session on the same credential keeps its own pin.
+ expect(await runQueryAndBilling({ token, sessionId: 'session-b' })).toEqual(
+ pathsFor(PINNED_PROJECT, PINNED_ORG)
+ )
+ expect(await runQueryAndBilling({ token, sessionId: 'session-a' })).toEqual(
+ pathsFor(OTHER_PROJECT, OTHER_ORG)
+ )
+ }
+ )
it.each([
['project', `?project_id=${PINNED_PROJECT}`],
diff --git a/services/mcp/tests/unit/switch-project.test.ts b/services/mcp/tests/unit/switch-project.test.ts
index bd6bc463dd76..d4cb82700308 100644
--- a/services/mcp/tests/unit/switch-project.test.ts
+++ b/services/mcp/tests/unit/switch-project.test.ts
@@ -76,14 +76,20 @@ describe('switch-project', () => {
expect(cache.get('projectId')).toBeUndefined()
})
- it('switches within the active organization without touching org state', async () => {
+ it.each([
+ ['projectId', { projectId: 42 }],
+ ['project_id', { project_id: 42 }],
+ ['new_project_id', { new_project_id: 42 }],
+ ['projectId over aliases', { projectId: 42, project_id: 77, new_project_id: 99 }],
+ ['project_id over new_project_id', { project_id: 42, new_project_id: 77 }],
+ ])('switches via %s within the active organization without touching org state', async (_label, input) => {
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 })
+ const result = await tool.handler(context, tool.schema.parse(input))
expect(result.content[0]!.text).toContain('Switched to project 42')
expect(result.content[0]!.text).not.toContain('also switched the active organization')
@@ -91,6 +97,12 @@ describe('switch-project', () => {
expect(getCachedOrFetchOrg).not.toHaveBeenCalled()
})
+ it.each(['projectId', 'project_id', 'new_project_id'])('rejects invalid identifiers supplied via %s', (key) => {
+ for (const value of [undefined, null, true, '42', 0, -1, 1.5]) {
+ expect(tool.schema.safeParse({ [key]: value }).success).toBe(false)
+ }
+ })
+
it('never exposes the project API token in the switch response', async () => {
const projectGet = vi.fn().mockResolvedValue({
success: true,