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): keep switch-project from being reverted by a resent context pin (#73934)

posthog[bot]a1db1ba08753
diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.ts
index 7f601bc78c27..4aa834e1c48a 100644
--- a/services/mcp/src/hono/cache/RedisCache.ts
+++ b/services/mcp/src/hono/cache/RedisCache.ts
@@ -77,6 +77,18 @@ export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {
await this.redis.del(scopedKey)
}
+ /**
+ * Renew the TTL on `keys` without rewriting their values. `set` stamps a
+ * fresh TTL on every write, so a value only read on later requests would
+ * otherwise expire while its session is still active. A caller whose
+ * lifetime should track session activity rather than last write refreshes
+ * here on each request. EXPIRE on a missing key is a no-op, so refreshing a
+ * key that was never written is harmless.
+ */
+ async refreshTtl<K extends keyof T>(keys: K[]): Promise<void> {
+ await Promise.all(keys.map((key) => this.redis.expire(this.getScopedKey(key as string), this.ttl)))
+ }
+
async clear(): Promise<void> {
const pattern = `mcp:${this.prefix}:${this.scope}:*`
let cursor = '0'
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index 75f0c5536c37..a53b992b217d 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -1,3 +1,5 @@
+import { createHash } from 'node:crypto'
+
import { ApiClient } from '@/api/client'
import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'
import { wrapError } from '@/lib/errors'
@@ -12,7 +14,7 @@ import type { RequestProperties } from '@/lib/request-properties'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
import { hash } from '@/lib/utils'
-import type { Context, Env, State } from '@/tools/types'
+import type { Context, Env, SessionScopedState, State } from '@/tools/types'
import { RedisCache, type RedisLike } from './cache/RedisCache'
import { getCustomApiBaseUrl, getPublicBaseUrl } from './constants'
@@ -25,12 +27,14 @@ import {
type MCPSessionContext,
} from './mcp-context'
-// A session's gate markers only need to outlive the session itself.
+// Matches McpSessionRedisStore's idle TTL: every session-scoped store describes
+// the same MCP protocol session, so their lifetimes should agree.
const SESSION_CACHE_TTL_SECONDS = 24 * 60 * 60
export class RequestContext {
private tokenCacheInstance: RedisCache<State> | undefined
private userCacheInstance: RedisCache<State> | undefined
+ private sessionScopedCacheInstance: RedisCache<SessionScopedState> | undefined
private apiInstance: ApiClient | undefined
private sessionManagerInstance: SessionManager | undefined
private distinctIdPromise: Promise<string> | undefined
@@ -78,6 +82,29 @@ export class RequestContext {
return this.tokenCache
}
+ /**
+ * State scoped to the MCP protocol session rather than the token, holding the
+ * session's in-session context switches and last-applied request pin. The
+ * token cache can't hold these: it is shared by every concurrent session on
+ * the same credential. Undefined when the request carries no session id.
+ */
+ get sessionScopedCache(): RedisCache<SessionScopedState> | undefined {
+ const mcpSessionId = this.requestContext.mcpSessionId
+ if (!mcpSessionId) {
+ return undefined
+ }
+ if (!this.sessionScopedCacheInstance) {
+ const digest = createHash('sha256').update(mcpSessionId).digest()
+ this.sessionScopedCacheInstance = new RedisCache<SessionScopedState>(
+ digest.subarray(0, 16).toString('base64url'),
+ this.redis,
+ 'session',
+ SESSION_CACHE_TTL_SECONDS
+ )
+ }
+ return this.sessionScopedCacheInstance
+ }
+
private async readCachedOAuthClientName(): Promise<string | undefined> {
if (!this.props.userHash) {
return undefined
@@ -169,6 +196,7 @@ export class RequestContext {
async getContext(): Promise<Context> {
const api = await this.api()
const stateManager = new StateManager(this.tokenCache, api)
+ const sessionScopedCache = this.sessionScopedCache
const partialContext: Omit<Context, 'trackEvent'> = {
api,
cache: this.tokenCache,
@@ -176,6 +204,16 @@ export class RequestContext {
stateManager,
sessionManager: this.sessionManager,
getDistinctId: () => this.getDistinctId(),
+ ...(sessionScopedCache
+ ? {
+ setSessionActiveContext: async (updates: { orgId?: string; projectId?: string }) => {
+ await sessionScopedCache.setMany({
+ ...(updates.orgId ? { activeOrgId: updates.orgId } : {}),
+ ...(updates.projectId ? { activeProjectId: updates.projectId } : {}),
+ })
+ },
+ }
+ : {}),
}
const trackEvent: Context['trackEvent'] = async (event, properties = {}) => {
const analyticsContext = await this.safelyGetAnalyticsContext(partialContext)
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index f7d55d1b5ef5..c2efe431e0ef 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -150,12 +150,12 @@ export class RequestStateResolver {
const contextPromise = reqCtx.getContext()
const pinnedSessionContextPromise = projectId ? this.resolveSessionContext(requestContext) : undefined
- await reqCtx.tokenCache.setMany({
- ...(organizationId ? { orgId: organizationId } : {}),
- ...(projectId ? { projectId } : {}),
- })
+ await this.applyPinnedContext(reqCtx, { organizationId, projectId })
- let cachedProjectId = projectId || (await reqCtx.tokenCache.get('projectId'))
+ // Read the active project back from the token cache (the source every tool
+ // resolves through) rather than the request pin, so the banner and group
+ // types reflect an in-session switch instead of the resent pin value.
+ let cachedProjectId = (await reqCtx.tokenCache.get('projectId')) || projectId
if (!cachedProjectId) {
const contextForDefault = await contextPromise
await contextForDefault.stateManager.setDefaultOrganizationAndProject()
@@ -287,6 +287,84 @@ export class RequestStateResolver {
}
}
+ /**
+ * Apply an org/project pinned via request params to the token-scoped active
+ * context every tool resolves through.
+ *
+ * A pin sets the session's default active context, not a per-request hard
+ * lock: `switch-project` stays available on a project pin (the documented
+ * cross-org flow depends on it), so a switch made mid-session must survive
+ * the client resending the same static pin on every request. The token cache
+ * is shared by every concurrent session on the same credential, though, so
+ * the pin can't simply be written once and left alone either — two sessions
+ * pinned to different projects would bleed into each other. Instead each
+ * request re-asserts its own session's effective context: the session's
+ * recorded switch (see `Context.setSessionActiveContext`) when one exists,
+ * otherwise the pin. A genuinely changed pin retargets the session and
+ * discards the recorded switch.
+ *
+ * Without an MCP session id there is no cross-request session state, so the
+ * pin is applied unconditionally as before.
+ */
+ private async applyPinnedContext(
+ reqCtx: RequestContext,
+ pinned: { organizationId?: string | undefined; projectId?: string | undefined }
+ ): Promise<void> {
+ const { organizationId, projectId } = pinned
+ if (!organizationId && !projectId) {
+ return
+ }
+
+ const sessionCache = reqCtx.sessionScopedCache
+ if (!sessionCache) {
+ await reqCtx.tokenCache.setMany({
+ ...(organizationId ? { orgId: organizationId } : {}),
+ ...(projectId ? { projectId } : {}),
+ })
+ return
+ }
+
+ const [appliedPinOrg, appliedPinProject, activeOrg, activeProject] = await Promise.all([
+ sessionCache.get('appliedPinOrgId'),
+ sessionCache.get('appliedPinProjectId'),
+ sessionCache.get('activeOrgId'),
+ sessionCache.get('activeProjectId'),
+ ])
+
+ // These keys carry a write-based TTL, but the MCP session they belong to
+ // renews its own context store on every request. Renew them too, so a
+ // switch recorded early in a long-lived session does not expire before
+ // the session ends and read back as a missing marker — which reads as a
+ // changed pin, discards the switch, and reverts to the pin mid-session.
+ await sessionCache.refreshTtl(['appliedPinOrgId', 'appliedPinProjectId', 'activeOrgId', 'activeProjectId'])
+
+ const pinChanged =
+ (organizationId !== undefined && appliedPinOrg !== organizationId) ||
+ (projectId !== undefined && appliedPinProject !== projectId)
+
+ let overrideOrg = activeOrg
+ let overrideProject = activeProject
+ if (pinChanged) {
+ overrideOrg = undefined
+ overrideProject = undefined
+ await Promise.all([
+ sessionCache.delete('activeOrgId'),
+ sessionCache.delete('activeProjectId'),
+ sessionCache.setMany({
+ ...(organizationId ? { appliedPinOrgId: organizationId } : {}),
+ ...(projectId ? { appliedPinProjectId: projectId } : {}),
+ }),
+ ])
+ }
+
+ const orgId = overrideOrg ?? organizationId
+ const effectiveProjectId = overrideProject ?? projectId
+ await reqCtx.tokenCache.setMany({
+ ...(orgId ? { orgId } : {}),
+ ...(effectiveProjectId ? { projectId: effectiveProjectId } : {}),
+ })
+ }
+
private async resolveSessionContext(requestContext: MCPRequestContext): Promise<MCPSessionContext | null> {
if (!requestContext.mcpSessionId) {
return null
diff --git a/services/mcp/src/tools/organizations/setActive.ts b/services/mcp/src/tools/organizations/setActive.ts
index 0777a58bc9fa..eb8d4d89fcd5 100644
--- a/services/mcp/src/tools/organizations/setActive.ts
+++ b/services/mcp/src/tools/organizations/setActive.ts
@@ -16,6 +16,9 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn
) => {
const { orgId } = params
await context.cache.set('orgId', orgId)
+ // Record the switch on the MCP session so a pinned connection's resent pin
+ // doesn't revert it on the next request.
+ await context.setSessionActiveContext?.({ orgId })
// Fetch fresh org data and cache it
let org: CachedOrg | undefined
diff --git a/services/mcp/src/tools/projects/setActive.ts b/services/mcp/src/tools/projects/setActive.ts
index 333123afc2e0..d31576f38fa8 100644
--- a/services/mcp/src/tools/projects/setActive.ts
+++ b/services/mcp/src/tools/projects/setActive.ts
@@ -67,6 +67,10 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn
org = await context.stateManager.getCachedOrFetchOrg()
}
+ // Record the switch on the MCP session so a pinned connection's resent pin
+ // doesn't revert it on the next request.
+ await context.setSessionActiveContext?.({ projectId: projectIdStr, ...(orgId ? { orgId } : {}) })
+
// Read cached user (and org, when we didn't just fetch it) for the metadata block
const distinctId = (await context.cache.get('distinctId')) ?? 'unknown'
const user = (await context.cache.get(`cachedUser:${distinctId}` as const)) as CachedUser | undefined
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
index c2e4ed3e30de..0edfe15fa340 100644
--- a/services/mcp/src/tools/types.ts
+++ b/services/mcp/src/tools/types.ts
@@ -15,6 +15,18 @@ export type SessionState = {
uuid: string
}
+// Per-MCP-session context, keyed on the protocol session id (not the token).
+// `activeOrgId`/`activeProjectId` record an in-session switch-organization /
+// switch-project; `appliedPin*` record the request pin the session last saw so
+// the resolver can tell a resent pin from a genuinely changed one. See
+// RequestStateResolver.applyPinnedContext.
+export type SessionScopedState = {
+ activeProjectId: string | undefined
+ activeOrgId: string | undefined
+ appliedPinProjectId: string | undefined
+ appliedPinOrgId: string | undefined
+}
+
export type CachedUser = ApiUser
export type CachedOrg = Schemas.OrganizationBasic
export type CachedProject = Schemas.ProjectBackwardCompat
@@ -116,6 +128,13 @@ export type Context = {
* stateManager when not provided.
*/
trackEvent: (event: AnalyticsEvent, properties?: Record<string, unknown>) => Promise<void>
+ /**
+ * Record an in-session context switch so a pinned connection's resent pin
+ * doesn't revert it (see RequestStateResolver.applyPinnedContext). Absent
+ * when the request carries no MCP session id — there is no cross-request
+ * session state to record for.
+ */
+ setSessionActiveContext?: (updates: { orgId?: string; projectId?: string }) => Promise<void>
/**
* Which PostHog connection this context runs through, when it runs through one at all. Set only
* by the forwarded context (see lib/connection-forwarding.ts); absent on a local call.
diff --git a/services/mcp/tests/hono/redis-cache.test.ts b/services/mcp/tests/hono/redis-cache.test.ts
index 21fe8543ea30..63d28f44c999 100644
--- a/services/mcp/tests/hono/redis-cache.test.ts
+++ b/services/mcp/tests/hono/redis-cache.test.ts
@@ -43,6 +43,8 @@ function createMockRedis(): MockRedis {
return ['0', matching] as [string, string[]]
}),
...makeRedisRateLimitStubs(),
+ // Override the trivial stub with a spy so TTL-renewal calls are assertable.
+ expire: vi.fn(async () => 1),
_store: store,
}
}
@@ -154,6 +156,16 @@ describe('RedisCache', () => {
})
})
+ describe('refreshTtl', () => {
+ it('renews the TTL on the given keys using the cache TTL', async () => {
+ const sessionCache = new RedisCache<TestState>('sess', mockRedis, 'session', 3600)
+ await sessionCache.refreshTtl(['projectId', 'orgId'])
+
+ expect(mockRedis.expire).toHaveBeenCalledWith('mcp:session:sess:projectId', 3600)
+ expect(mockRedis.expire).toHaveBeenCalledWith('mcp:session:sess:orgId', 3600)
+ })
+ })
+
describe('clear', () => {
it('should only clear keys for the scoped user', async () => {
mockRedis._store.set('mcp:token:test-user-hash:region', '"us"')
diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.ts
index a075667613f5..da6e66d278ac 100644
--- a/services/mcp/tests/hono/request-state-resolver.test.ts
+++ b/services/mcp/tests/hono/request-state-resolver.test.ts
@@ -1,10 +1,16 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-const { mockSessionStore, mockTokenStore, mockApiKey } = vi.hoisted(() => ({
- mockSessionStore: new Map<string, unknown>(),
- mockTokenStore: new Map<string, unknown>(),
- mockApiKey: { scopes: ['*'], scoped_teams: [] },
-}))
+const { mockSessionStore, mockTokenStore, mockApiKey, mockSessionScopedStores, mockRefreshTtlCalls } = vi.hoisted(
+ () => ({
+ mockSessionStore: new Map<string, unknown>(),
+ mockTokenStore: new Map<string, unknown>(),
+ mockApiKey: { scopes: ['*'], scoped_teams: [] },
+ mockSessionScopedStores: new Map<string, Map<string, unknown>>(),
+ // Records the keys passed to every session-scoped refreshTtl call (only the
+ // session cache refreshes, so any recorded call is a session refresh).
+ mockRefreshTtlCalls: [] as string[][],
+ })
+)
vi.mock('@/lib/posthog/flags', () => ({
evaluateFeatureFlags: vi.fn(async () => ({})),
@@ -35,6 +41,7 @@ vi.mock('@/hono/request-context', () => {
setMany: (entries: Record<string, unknown>) => Promise<void>
delete: (key: string) => Promise<void>
clear: () => Promise<void>
+ refreshTtl: (keys: string[]) => Promise<void>
}
const makeCache = (store: Map<string, unknown>): MockCache => ({
@@ -55,12 +62,26 @@ vi.mock('@/hono/request-context', () => {
clear: vi.fn(async () => {
store.clear()
}),
+ refreshTtl: vi.fn(async (keys: string[]) => {
+ mockRefreshTtlCalls.push(keys)
+ }),
})
+ const sessionScopedStore = (mcpSessionId: string): Map<string, unknown> => {
+ let store = mockSessionScopedStores.get(mcpSessionId)
+ if (!store) {
+ store = new Map<string, unknown>()
+ mockSessionScopedStores.set(mcpSessionId, store)
+ }
+ return store
+ }
+
return {
- RequestContext: vi.fn().mockImplementation(function () {
+ RequestContext: vi.fn().mockImplementation(function (...args: unknown[]) {
+ const props = args[2] as { mcpSessionId?: string }
return {
tokenCache: makeCache(mockTokenStore),
+ sessionScopedCache: props.mcpSessionId ? makeCache(sessionScopedStore(props.mcpSessionId)) : undefined,
getContext: vi.fn(async () => ({
stateManager: {
setDefaultOrganizationAndProject: vi.fn(async () => {}),
@@ -125,6 +146,8 @@ describe('RequestStateResolver MCP client contexts', () => {
beforeEach(() => {
mockSessionStore.clear()
mockTokenStore.clear()
+ mockSessionScopedStores.clear()
+ mockRefreshTtlCalls.length = 0
mockApiKey.scopes = ['*']
})
@@ -375,6 +398,88 @@ describe('RequestStateResolver MCP client contexts', () => {
expect(result.toolFeatureFlags?.['dev-forced-flag']).toBe(true)
})
+ describe('pinned project/org context', () => {
+ // What the switch-project handler does: write the token cache and record
+ // the switch on the session (Context.setSessionActiveContext).
+ const simulateSwitch = (mcpSessionId: string, projectId: string): void => {
+ mockTokenStore.set('projectId', projectId)
+ mockSessionScopedStores.get(mcpSessionId)?.set('activeProjectId', projectId)
+ }
+
+ it('does not revert an in-session switch-project when the same pin is resent', async () => {
+ // Pinning clients resend `?project_id=` on every request. The first
+ // request establishes the pin; a later switch-project selects a new
+ // active project that the resent pin must not clobber.
+ await makeResolver().resolve(makeProps({ projectId: '1' }))
+ expect(mockTokenStore.get('projectId')).toBe('1')
+
+ simulateSwitch('mcp-session-1', '2')
+
+ await makeResolver().resolve(makeProps({ projectId: '1' }))
+ expect(mockTokenStore.get('projectId')).toBe('2')
+ })
+
+ it('re-applies a changed pin and discards the recorded switch', async () => {
+ await makeResolver().resolve(makeProps({ projectId: '1' }))
+ simulateSwitch('mcp-session-1', '2')
+
+ await makeResolver().resolve(makeProps({ projectId: '9' }))
+ expect(mockTokenStore.get('projectId')).toBe('9')
+ expect(mockSessionScopedStores.get('mcp-session-1')?.get('activeProjectId')).toBeUndefined()
+ })
+
+ it('reverts org and project together when only the project pin changes after a cross-org switch', async () => {
+ // A both-pins client that switch-projects across orgs, then changes only
+ // its project pin, must not keep the switched org: pin is one context, so
+ // any changed pin value reverts both fields. Otherwise org-scoped tools
+ // stay on the switched org while project-scoped tools use the new pin.
+ await makeResolver().resolve(makeProps({ organizationId: 'org-1', projectId: '1' }))
+
+ // A cross-org switch-project records both fields on the session and the token cache.
+ mockTokenStore.set('orgId', 'org-2')
+ mockTokenStore.set('projectId', '2')
+ mockSessionScopedStores.get('mcp-session-1')?.set('activeOrgId', 'org-2')
+ mockSessionScopedStores.get('mcp-session-1')?.set('activeProjectId', '2')
+
+ await makeResolver().resolve(makeProps({ organizationId: 'org-1', projectId: '9' }))
+ expect(mockTokenStore.get('orgId')).toBe('org-1')
+ expect(mockTokenStore.get('projectId')).toBe('9')
+ })
+
+ it('applies the pin on every request without an MCP session id', async () => {
+ // No session means no cross-request continuity to protect, so the pin
+ // must keep winning each request (single-exec CLI stands alone).
+ await makeResolver().resolve(makeProps({ projectId: '1', mcpSessionId: undefined }))
+ mockTokenStore.set('projectId', '2')
+
+ await makeResolver().resolve(makeProps({ projectId: '1', mcpSessionId: undefined }))
+ expect(mockTokenStore.get('projectId')).toBe('1')
+ })
+
+ it('keeps concurrent sessions with different pins on one token isolated', async () => {
+ // The token cache is shared by every session on the same credential.
+ // Each request must re-assert its own session's context, or one
+ // session's pin leaks into the other's queries.
+ await makeResolver().resolve(makeProps({ projectId: '1', mcpSessionId: 'session-a' }))
+ await makeResolver().resolve(makeProps({ projectId: '2', mcpSessionId: 'session-b' }))
+ expect(mockTokenStore.get('projectId')).toBe('2')
+
+ await makeResolver().resolve(makeProps({ projectId: '1', mcpSessionId: 'session-a' }))
+ expect(mockTokenStore.get('projectId')).toBe('1')
+ })
+
+ it('renews the session-scoped keys TTL on every pinned request', async () => {
+ // The keys carry a write-based TTL; without a per-request refresh a
+ // switch recorded early in a long session expires first, reads back as
+ // a changed pin, and the pin silently wins again.
+ await makeResolver().resolve(makeProps({ projectId: '1' }))
+
+ expect(mockRefreshTtlCalls).toContainEqual(
+ expect.arrayContaining(['appliedPinOrgId', 'appliedPinProjectId', 'activeOrgId', 'activeProjectId'])
+ )
+ })
+ })
+
it('captures consumer from a later request when initialize omitted the header', async () => {
await makeResolver().resolve(
makeProps({
diff --git a/services/mcp/tests/integration/mcp-protocol-suite.ts b/services/mcp/tests/integration/mcp-protocol-suite.ts
index 13c2b2f4a21d..d49175b96855 100644
--- a/services/mcp/tests/integration/mcp-protocol-suite.ts
+++ b/services/mcp/tests/integration/mcp-protocol-suite.ts
@@ -1215,10 +1215,10 @@ export function defineToolBehaviorTests(
expect(decodeText(orgResult.content)).toContain(harness.orgId)
})
- // ?projectId=N in the URL pins the active project for the whole
- // session — agents pass this to avoid needing a switch-project
- // tool call first. The state resolver writes it to the cache on
- // every request, so a project-scoped tool should resolve it
+ // ?projectId=N in the URL pins the session's default active project,
+ // so agents pass this to avoid needing a switch-project tool call
+ // first. The state resolver asserts the pin (unless an in-session
+ // switch overrides it), so a project-scoped tool should resolve it
// without an explicit switch.
it('reads the active project pinned via ?projectId= URL param', async ({ skip }) => {
if (!harness.projectId) {
diff --git a/services/mcp/tests/unit/switch-project.test.ts b/services/mcp/tests/unit/switch-project.test.ts
index 352ea530688c..5f88dac12201 100644
--- a/services/mcp/tests/unit/switch-project.test.ts
+++ b/services/mcp/tests/unit/switch-project.test.ts
@@ -10,9 +10,15 @@ 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> } {
+}): {
+ context: Context
+ cache: Map<string, unknown>
+ getCachedOrFetchOrg: ReturnType<typeof vi.fn>
+ setSessionActiveContext: ReturnType<typeof vi.fn>
+} {
const cache = new Map<string, unknown>()
const getCachedOrFetchOrg = overrides.getCachedOrFetchOrg ?? vi.fn().mockResolvedValue(undefined)
+ const setSessionActiveContext = vi.fn().mockResolvedValue(undefined)
const context = {
api: {
publicBaseUrl: 'https://us.posthog.com',
@@ -33,8 +39,9 @@ function createMockContext(overrides: {
sessionManager: {},
getDistinctId: async () => 'test-distinct-id',
trackEvent: async () => {},
+ setSessionActiveContext,
} as unknown as Context
- return { context, cache, getCachedOrFetchOrg }
+ return { context, cache, getCachedOrFetchOrg, setSessionActiveContext }
}
describe('switch-project', () => {
@@ -67,7 +74,7 @@ describe('switch-project', () => {
success: true,
data: { id: 42, name: 'My project', organization: ACTIVE_ORG },
})
- const { context, cache, getCachedOrFetchOrg } = createMockContext({ projectGet })
+ const { context, cache, getCachedOrFetchOrg, setSessionActiveContext } = createMockContext({ projectGet })
const result = await tool.handler(context, { projectId: 42 })
@@ -75,6 +82,9 @@ describe('switch-project', () => {
expect(result.content[0]!.text).not.toContain('also switched the active organization')
expect(cache.get('projectId')).toBe('42')
expect(getCachedOrFetchOrg).not.toHaveBeenCalled()
+ // Recording the switch on the session is what stops a pinned connection's
+ // resent pin from reverting it on the next request.
+ expect(setSessionActiveContext).toHaveBeenCalledWith({ projectId: '42', orgId: ACTIVE_ORG })
})
it('syncs the active organization via the shared resolver when the project is in another org', async () => {