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 a context pin overwriting the shared token cache (#108367)

posthog[bot]aeb0271c3987
diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.ts
index 5c24f10a8a11..4a3fd791bb53 100644
--- a/services/mcp/src/hono/dispatcher.ts
+++ b/services/mcp/src/hono/dispatcher.ts
@@ -23,6 +23,7 @@ import { randomUUID } from 'node:crypto'
import { mapErrorToAuthResponse } from '@/lib/auth-errors'
import { isLegacyDialectOnlyClient } from '@/lib/client-detection'
import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'
+import { McpSessionResetRequiredError, SESSION_RESET_REQUIRED_REASON } from '@/lib/errors'
import { resolveFeatureFlagOverrides } from '@/lib/posthog/flags'
import type { RequestProperties } from '@/lib/request-properties'
import {
@@ -259,6 +260,19 @@ class McpDispatcher {
if (hasInit) {
initTotal.inc({ status: mapErrorToAuthResponse(error) ? 'auth_error' : 'error' })
}
+ // A JSON-RPC error with HTTP 200 reaches the agent, which can tell the user to
+ // reconnect. Some transports, such as mcp-remote, treat any non-2xx status as fatal.
+ if (error instanceof McpSessionResetRequiredError) {
+ const errors = requests.map((r) =>
+ jsonRpcMethodError(r.id, ErrorCode.InvalidRequest, error.message, {
+ reason: SESSION_RESET_REQUIRED_REASON,
+ })
+ )
+ return new Response(JSON.stringify(!wasArray && errors.length === 1 ? errors[0] : errors), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ })
+ }
throw error
}
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index 045aaf9deaad..a0194e38bb24 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -13,7 +13,7 @@ import {
import type { RequestProperties } from '@/lib/request-properties'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
-import type { Context, Env, SessionScopedState, State } from '@/tools/types'
+import type { Context, Env, PinnedActiveContext, SessionScopedState, State } from '@/tools/types'
import { RedisCache, type RedisLike } from './cache/RedisCache'
import { getClientIpSigningKeys, getCustomApiBaseUrl, getPublicBaseUrl } from './constants'
@@ -34,6 +34,7 @@ const SESSION_CACHE_TTL_SECONDS = 24 * 60 * 60
export class RequestContext {
private tokenCacheInstance: RedisCache<State> | undefined
private sessionScopedCacheInstance: RedisCache<SessionScopedState> | undefined
+ private legacySessionScopedCacheInstance: RedisCache<SessionScopedState> | undefined
private apiInstance: ApiClient | undefined
private sessionManagerInstance: SessionManager | undefined
private distinctIdPromise: Promise<string> | undefined
@@ -43,6 +44,7 @@ export class RequestContext {
private readonly props: RequestProperties
private requestContext: MCPRequestContext
private sessionContext: MCPSessionContext | null = null
+ private pinnedContext: PinnedActiveContext | undefined
constructor(
redis: RedisLike,
@@ -75,6 +77,9 @@ export class RequestContext {
* 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.
+ *
+ * The key includes the credential: a caller chooses its session id, so a
+ * request must never restore context that another credential saved.
*/
get sessionScopedCache(): RedisCache<SessionScopedState> | undefined {
const mcpSessionId = this.requestContext.mcpSessionId
@@ -82,17 +87,42 @@ export class RequestContext {
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
- )
+ this.sessionScopedCacheInstance = this.sessionCacheFor(`${this.props.userHash ?? ''}\0${mcpSessionId}`)
}
return this.sessionScopedCacheInstance
}
+ /**
+ * The session store under its former key, which held only the session id.
+ * Read it only to find a session that started before the key included the
+ * credential. Never restore its values: another credential can send the same id.
+ */
+ get legacySessionScopedCache(): RedisCache<SessionScopedState> | undefined {
+ const mcpSessionId = this.requestContext.mcpSessionId
+ if (!mcpSessionId) {
+ return undefined
+ }
+ if (!this.legacySessionScopedCacheInstance) {
+ this.legacySessionScopedCacheInstance = this.sessionCacheFor(mcpSessionId)
+ }
+ return this.legacySessionScopedCacheInstance
+ }
+
+ private sessionCacheFor(keyMaterial: string): RedisCache<SessionScopedState> {
+ const digest = createHash('sha256').update(keyMaterial).digest()
+ return new RedisCache<SessionScopedState>(
+ digest.subarray(0, 16).toString('base64url'),
+ this.redis,
+ 'session',
+ SESSION_CACHE_TTL_SECONDS
+ )
+ }
+
+ /** Set by the resolver before `getContext()`, so every tool reads the pinned context. */
+ setPinnedContext(pinned: PinnedActiveContext | undefined): void {
+ this.pinnedContext = pinned
+ }
+
private async readCachedOAuthClientName(): Promise<string | undefined> {
if (!this.props.userHash) {
return undefined
@@ -199,7 +229,7 @@ export class RequestContext {
async getContext(): Promise<Context> {
const api = await this.api()
- const stateManager = new StateManager(this.tokenCache, api)
+ const stateManager = new StateManager(this.tokenCache, api, this.pinnedContext)
const sessionScopedCache = this.sessionScopedCache
const partialContext: Omit<Context, 'trackEvent'> = {
api,
diff --git a/services/mcp/src/hono/request-state-resolver.ts b/services/mcp/src/hono/request-state-resolver.ts
index 197fa6d5e894..4e36def8c28b 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -1,5 +1,6 @@
import { MCPClientProfile } from '@/lib/client-detection'
import { isCloudApi, isLocalApi, MCP_GATEWAY_FLAG } from '@/lib/constants'
+import { McpSessionResetRequiredError } from '@/lib/errors'
import { buildMCPAnalyticsGroups } from '@/lib/posthog/analytics'
import {
type EvaluatedFlags,
@@ -18,7 +19,7 @@ import {
getScopeGatedTools,
type ScopeGatedTool,
} from '@/tools/toolDefinitions'
-import type { Context, Tool, Env, ZodObjectAny } from '@/tools/types'
+import type { Context, Env, PinnedActiveContext, Tool, ZodObjectAny } from '@/tools/types'
import { McpSessionRedisStore } from './cache/McpSessionRedisStore'
import type { RedisLike } from './cache/RedisCache'
@@ -135,18 +136,17 @@ export class RequestStateResolver {
const reqCtx = new RequestContext(this.redis, this.env, props, requestContext)
const { features, tools, organizationId, projectId, readOnly } = props
- await this.applyPinnedContext(reqCtx, { organizationId, projectId })
+ const pinned = await this.resolvePinnedContext(reqCtx, { organizationId, projectId })
+ reqCtx.setPinnedContext(pinned)
// Start Redis reads only when Promise.all can observe their timeout rejections.
- // Read the active project back from the token cache (the source every tool
- // resolves through) rather than the request pin, so an in-session switch wins.
+ // A pinned request never writes a default into the token selection that other sessions share.
const [context, sessionContext, storedProjectId] = await Promise.all([
reqCtx.getContext(),
this.resolveSessionContext(requestContext),
- reqCtx.tokenCache.get('projectId'),
+ pinned ? undefined : reqCtx.tokenCache.get('projectId'),
])
- const cachedProjectId = storedProjectId || projectId
- if (!cachedProjectId) {
+ if (!pinned && !storedProjectId) {
await context.stateManager.setDefaultOrganizationAndProject()
}
const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)
@@ -264,48 +264,64 @@ export class RequestStateResolver {
}
/**
- * Apply an org/project pinned via request params to the token-scoped active
- * context every tool resolves through.
+ * Resolve the org and project that a request pinned via request params into
+ * the request-scoped 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.
+ * the client resending the same static pin on every request. The effective
+ * context is 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.
+ * The result never goes into the token cache. Every concurrent session on the
+ * same credential shares that cache, so a pin written there would revert a
+ * switch and leak into the other sessions.
+ *
+ * Many clients send the pin only on `initialize`. A later request in the same
+ * session that omits the pin restores the session's saved pin and switch, so
+ * it does not fall back to whatever another session left in the token cache.
+ * A session that never sent a pin stays on the token selection, even when it
+ * recorded a switch. A pin that differs in either field replaces the whole
+ * saved pin and discards the recorded switch.
+ *
+ * Without an MCP session id nothing records a switch across requests, so the
+ * pin wins on every request and the switch tools refuse to switch.
*/
- private async applyPinnedContext(
+ private async resolvePinnedContext(
reqCtx: RequestContext,
- pinned: { organizationId?: string | undefined; projectId?: string | undefined }
- ): Promise<void> {
- const { organizationId, projectId } = pinned
- if (!organizationId && !projectId) {
- return
- }
+ pin: { organizationId?: string | undefined; projectId?: string | undefined }
+ ): Promise<PinnedActiveContext | undefined> {
+ const { organizationId, projectId } = pin
+ const hasPin = Boolean(organizationId || projectId)
const sessionCache = reqCtx.sessionScopedCache
if (!sessionCache) {
- await reqCtx.tokenCache.setMany({
- ...(organizationId ? { orgId: organizationId } : {}),
- ...(projectId ? { projectId } : {}),
- })
- return
+ return hasPin ? { pin, sessionScoped: false, orgId: organizationId, projectId } : undefined
}
- const [appliedPinOrg, appliedPinProject, activeOrg, activeProject] = await Promise.all([
- sessionCache.get('appliedPinOrgId'),
- sessionCache.get('appliedPinProjectId'),
- sessionCache.get('activeOrgId'),
- sessionCache.get('activeProjectId'),
- ])
+ const legacyCache = reqCtx.legacySessionScopedCache
+ const [appliedPinOrg, appliedPinProject, activeOrg, activeProject, legacyPinOrg, legacyPinProject] =
+ await Promise.all([
+ sessionCache.get('appliedPinOrgId'),
+ sessionCache.get('appliedPinProjectId'),
+ sessionCache.get('activeOrgId'),
+ sessionCache.get('activeProjectId'),
+ legacyCache?.get('appliedPinOrgId'),
+ legacyCache?.get('appliedPinProjectId'),
+ ])
+ // A pin marker under the former key means a pinned session from before the
+ // key included the credential. Its saved switch would be lost silently, so
+ // stop before any tool runs. Legacy state without a pin marker never changed
+ // the selection, so it needs no reset.
+ const hasSessionState = Boolean(appliedPinOrg || appliedPinProject || activeOrg || activeProject)
+ if (!hasSessionState && (legacyPinOrg || legacyPinProject)) {
+ throw new McpSessionResetRequiredError()
+ }
+ if (!hasPin && !appliedPinOrg && !appliedPinProject) {
+ return undefined
+ }
// 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
@@ -314,9 +330,17 @@ export class RequestStateResolver {
// 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)
+ // An omitted pin is not a changed pin: keep the session's saved context.
+ if (!hasPin) {
+ return {
+ pin: { organizationId: appliedPinOrg, projectId: appliedPinProject },
+ sessionScoped: true,
+ orgId: activeOrg ?? appliedPinOrg,
+ projectId: activeProject ?? appliedPinProject,
+ }
+ }
+
+ const pinChanged = appliedPinOrg !== organizationId || appliedPinProject !== projectId
let overrideOrg = activeOrg
let overrideProject = activeProject
@@ -326,6 +350,8 @@ export class RequestStateResolver {
await Promise.all([
sessionCache.delete('activeOrgId'),
sessionCache.delete('activeProjectId'),
+ organizationId ? undefined : sessionCache.delete('appliedPinOrgId'),
+ projectId ? undefined : sessionCache.delete('appliedPinProjectId'),
sessionCache.setMany({
...(organizationId ? { appliedPinOrgId: organizationId } : {}),
...(projectId ? { appliedPinProjectId: projectId } : {}),
@@ -333,12 +359,12 @@ export class RequestStateResolver {
])
}
- const orgId = overrideOrg ?? organizationId
- const effectiveProjectId = overrideProject ?? projectId
- await reqCtx.tokenCache.setMany({
- ...(orgId ? { orgId } : {}),
- ...(effectiveProjectId ? { projectId: effectiveProjectId } : {}),
- })
+ return {
+ pin,
+ sessionScoped: true,
+ orgId: overrideOrg ?? organizationId,
+ projectId: overrideProject ?? projectId,
+ }
}
private async resolveSessionContext(requestContext: MCPRequestContext): Promise<MCPSessionContext | null> {
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 13ae062ff9be..a3de124b6337 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -14,6 +14,7 @@ import {
handleToolError,
MissingOrganizationContextError,
MissingProjectContextError,
+ PinnedContextSwitchError,
PostHogApiError,
PostHogValidationError,
ToolInputValidationError,
@@ -952,7 +953,11 @@ function resolveToolErrorClassification(error: unknown): ToolErrorClassification
const errorCode = error.errorCode ? sanitizeErrorToken(error.errorCode) : undefined
return { errorType: error.errorType, ...(errorCode ? { errorCode } : {}) }
}
- if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {
+ if (
+ error instanceof MissingProjectContextError ||
+ error instanceof MissingOrganizationContextError ||
+ error instanceof PinnedContextSwitchError
+ ) {
return { errorType: 'missing_context' }
}
if (error instanceof ToolInputValidationError) {
@@ -1058,7 +1063,11 @@ function resolveSafeErrorMessage(error: unknown): string | undefined {
return `Tool failed: ${error.errorType}`
}
// Static recovery walkthroughs generated by our own constructors.
- if (error instanceof MissingProjectContextError || error instanceof MissingOrganizationContextError) {
+ if (
+ error instanceof MissingProjectContextError ||
+ error instanceof MissingOrganizationContextError ||
+ error instanceof PinnedContextSwitchError
+ ) {
return error.message
}
// Documented value-free: offending field paths + issue codes, never input values.
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index b4450439d576..ecad4b0133aa 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -13,7 +13,7 @@ import {
import { getPostHogClient } from '@/lib/posthog'
import { sanitizeHeaderValue } from '@/lib/utils'
import type { ApiUser } from '@/schema/api'
-import type { CachedOrg, CachedProject, CachedUser, State } from '@/tools/types'
+import type { CachedOrg, CachedProject, CachedUser, PinnedActiveContext, State } from '@/tools/types'
const CACHE_TTL_MS = 10 * 60 * 1000 // 10 minutes
// A personal API key keeps its value when its scopes change, and the cache is keyed by token, so
@@ -32,9 +32,49 @@ export class StateManager {
private _cache: ScopedCache<State>
private _api: ApiClient
private _user?: ApiUser
- constructor(cache: ScopedCache<State>, api: ApiClient) {
+ private _pinned: PinnedActiveContext | undefined
+ private _pinnedOrgProject: Promise<string> | undefined
+ constructor(cache: ScopedCache<State>, api: ApiClient, pinned?: PinnedActiveContext) {
this._cache = cache
this._api = api
+ this._pinned = pinned
+ }
+
+ get pinnedContext(): PinnedActiveContext | undefined {
+ return this._pinned
+ }
+
+ /**
+ * Set the active org and project. On a pinned request the ids only update the
+ * request-scoped context: the session store records the switch, and the token
+ * cache must not, because other sessions on the same credential read it. A
+ * pinned request without a session still persists the keys the pin leaves open.
+ * A project pin also fixes the org, because the project owns it.
+ */
+ async setActiveContext(updates: { orgId?: string; projectId?: string }): Promise<void> {
+ const pinned = this._pinned
+ if (!pinned) {
+ await this._cache.setMany({
+ ...(updates.orgId ? { orgId: updates.orgId } : {}),
+ ...(updates.projectId ? { projectId: updates.projectId } : {}),
+ })
+ return
+ }
+ if (updates.orgId) {
+ pinned.orgId = updates.orgId
+ }
+ if (updates.projectId) {
+ pinned.projectId = updates.projectId
+ }
+ this._pinnedOrgProject = undefined
+ if (!pinned.sessionScoped) {
+ await this._cache.setMany({
+ ...(updates.orgId && !pinned.pin.organizationId && !pinned.pin.projectId
+ ? { orgId: updates.orgId }
+ : {}),
+ ...(updates.projectId && !pinned.pin.projectId ? { projectId: updates.projectId } : {}),
+ })
+ }
}
private async _fetchUser(): Promise<ApiUser> {
@@ -292,6 +332,19 @@ export class StateManager {
* fetch.
*/
private async _resolveOrganizationId(): Promise<string | undefined> {
+ const pinned = this._pinned
+ if (pinned?.orgId) {
+ return pinned.orgId
+ }
+ // A pinned project owns the org. The shared token cache can hold another
+ // session's org, so when the project cannot name its org, report missing
+ // context instead of falling back to the cache.
+ if (pinned?.projectId) {
+ const project = await this.getCachedOrFetchProject().catch(() => undefined)
+ pinned.orgId = project?.organization ?? undefined
+ return pinned.orgId
+ }
+
const cached = await this._cache.get('orgId')
if (cached) {
return cached
@@ -319,6 +372,15 @@ export class StateManager {
}
async getProjectId(): Promise<string> {
+ const pinned = this._pinned
+ if (pinned) {
+ if (pinned.projectId) {
+ return pinned.projectId
+ }
+ this._pinnedOrgProject ??= this._resolvePinnedOrgProjectId(pinned)
+ return this._pinnedOrgProject
+ }
+
const projectId = await this._cache.get('projectId')
if (!projectId) {
@@ -332,6 +394,35 @@ export class StateManager {
return projectId
}
+ /**
+ * An organization pin selects an org but no project. The shared token cache and
+ * the user's default can name a project in another org, so accept a candidate
+ * only when its lookup proves that it belongs to the selected org. A failed
+ * lookup rejects the candidate. The choice is never written to the shared
+ * cache, because other sessions on the credential read it.
+ */
+ private async _resolvePinnedOrgProjectId(pinned: PinnedActiveContext): Promise<string> {
+ const orgId = pinned.orgId
+ const belongsToOrg = async (candidate: string | undefined): Promise<boolean> => {
+ if (!orgId || !candidate) {
+ return false
+ }
+ const project = await this._getCachedOrFetchProjectById(candidate).catch(() => undefined)
+ return project?.organization === orgId
+ }
+
+ const cachedCandidate = await this._cache.get('projectId')
+ if (await belongsToOrg(cachedCandidate)) {
+ return cachedCandidate!
+ }
+ const { projectId } = await this._getDefaultOrganizationAndProject().catch(() => ({ projectId: undefined }))
+ const defaultCandidate = projectId?.toString()
+ if (defaultCandidate !== cachedCandidate && (await belongsToOrg(defaultCandidate))) {
+ return defaultCandidate!
+ }
+ throw new MissingProjectContextError({ organizationId: orgId })
+ }
+
private isCacheStale(fetchedAt: number | undefined, ttlMs: number = CACHE_TTL_MS): boolean {
return !fetchedAt || Date.now() - fetchedAt > ttlMs
}
@@ -415,6 +506,10 @@ export class StateManager {
if (!projectId) {
return undefined
}
+ return this._getCachedOrFetchProjectById(projectId)
+ }
+
+ private async _getCachedOrFetchProjectById(projectId: string): Promise<CachedProject | undefined> {
return this.getOrFetchCached({
name: 'project',
cacheKey: `cachedProject:${projectId}` as const,
@@ -492,7 +587,7 @@ export class StateManager {
projectName?: string
}> {
const [orgId, project] = await Promise.all([
- this._cache.get('orgId'),
+ this._pinned ? this._pinned.orgId : this._cache.get('orgId'),
this.getCachedOrFetchProject().catch(() => undefined),
])
diff --git a/services/mcp/src/lib/errors.ts b/services/mcp/src/lib/errors.ts
index 246b0aea8908..66081803613d 100644
--- a/services/mcp/src/lib/errors.ts
+++ b/services/mcp/src/lib/errors.ts
@@ -96,6 +96,52 @@ function formatMissingOrganizationContextMessage(): string {
)
}
+/**
+ * Thrown by `switch-project` and `switch-organization` when the request pins the
+ * context and carries no MCP session id. Nothing records the switch across
+ * requests, so the next request applies the pin again. Failing here tells the
+ * agent the truth instead of a success that the next call silently reverts.
+ */
+export class PinnedContextSwitchError extends Error {
+ constructor(pinned: { organizationId?: string | undefined; projectId?: string | undefined }) {
+ super(formatPinnedContextSwitchMessage(pinned))
+ this.name = 'PinnedContextSwitchError'
+ }
+}
+
+function formatPinnedContextSwitchMessage(pinned: {
+ organizationId?: string | undefined
+ projectId?: string | undefined
+}): string {
+ const target = pinned.projectId ? `project \`${pinned.projectId}\`` : `organization \`${pinned.organizationId}\``
+ return (
+ `This connection pins ${target} on every request and sends no MCP session id, so a switch cannot persist. ` +
+ 'The next tool call would run against the pinned context again, so the switch was not applied.' +
+ '\n\n' +
+ `Keep working in the pinned ${pinned.projectId ? 'project' : 'organization'}, or ask the user to change the pin in the MCP client configuration ` +
+ '(the `project_id` / `organization_id` URL parameters or the `x-posthog-project-id` / `x-posthog-organization-id` headers).'
+ )
+}
+
+export const SESSION_RESET_REQUIRED_REASON = 'session_reset_required'
+
+/**
+ * Thrown before any tool runs when an MCP session saved its project and
+ * organization selection under the store key that held only the session id.
+ * The server does not trust those values, because any credential can send the
+ * same session id, and it does not silently start over from the pin or the
+ * shared token selection either. A new session starts with a clean selection.
+ */
+export class McpSessionResetRequiredError extends Error {
+ constructor() {
+ super(
+ 'This MCP session started before a PostHog MCP server update, and the server cannot restore its project and organization selection. ' +
+ 'No tool ran. Reconnect the PostHog MCP server to start a new session, then try again.'
+ )
+ this.name = 'McpSessionResetRequiredError'
+ }
+}
+
export interface PostHogValidationErrorOptions {
detail: string
attr: string | undefined
@@ -511,6 +557,7 @@ export function handleToolError(
if (
error instanceof MissingProjectContextError ||
error instanceof MissingOrganizationContextError ||
+ error instanceof PinnedContextSwitchError ||
error instanceof ToolInputValidationError ||
error instanceof ExecCommandError ||
(error instanceof MCPToolResultError && ['validation', 'permission'].includes(error.errorType))
diff --git a/services/mcp/src/tools/organizations/setActive.ts b/services/mcp/src/tools/organizations/setActive.ts
index a37acb405e6f..a834a300e751 100644
--- a/services/mcp/src/tools/organizations/setActive.ts
+++ b/services/mcp/src/tools/organizations/setActive.ts
@@ -1,5 +1,6 @@
import type { z } from 'zod'
+import { PinnedContextSwitchError } from '@/lib/errors'
import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'
import { OrganizationSetActiveSchema } from '@/schema/tool-inputs'
import type { CachedOrg, CachedProject, Context, ToolBase } from '@/tools/types'
@@ -15,7 +16,16 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn
params: Params
) => {
const { orgId } = params
- await context.cache.set('orgId', orgId)
+ // Without a session, the next request applies the pin again: a pinned project
+ // brings back its own org. Refuse rather than report a switch that reverts.
+ const pinned = context.stateManager.pinnedContext
+ if (pinned && !pinned.sessionScoped) {
+ const pinnedOrgId = pinned.pin.organizationId ?? (await context.stateManager.getOrgID().catch(() => undefined))
+ if (pinnedOrgId !== orgId) {
+ throw new PinnedContextSwitchError(pinned.pin)
+ }
+ }
+ await context.stateManager.setActiveContext({ 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 })
@@ -30,7 +40,7 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn
}
// Read cached project for full metadata block
- const projectId = (await context.cache.get('projectId')) ?? 'unknown'
+ const projectId = pinned?.projectId ?? (await context.cache.get('projectId')) ?? 'unknown'
const project = (await context.cache.get(`cachedProject:${projectId}` as const)) as CachedProject | undefined
const integrationKinds = project
diff --git a/services/mcp/src/tools/projects/setActive.ts b/services/mcp/src/tools/projects/setActive.ts
index b0753f5b0f0c..82b2345b41f9 100644
--- a/services/mcp/src/tools/projects/setActive.ts
+++ b/services/mcp/src/tools/projects/setActive.ts
@@ -1,6 +1,6 @@
import type { z } from 'zod'
-import { wrapError } from '@/lib/errors'
+import { PinnedContextSwitchError, wrapError } from '@/lib/errors'
import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'
import { ProjectSetActiveSchema } from '@/schema/tool-inputs'
import type { CachedOrg, CachedProject, Context, ToolBase } from '@/tools/types'
@@ -18,6 +18,14 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn
const { projectId } = params
const projectIdStr = projectId.toString()
+ // Without a session, the next request applies the pin again. Refuse up front
+ // rather than report a switch that the next tool call reverts.
+ const pinned = context.stateManager.pinnedContext
+ const pinLocksContext = pinned !== undefined && !pinned.sessionScoped
+ if (pinLocksContext && pinned.pin.projectId && pinned.pin.projectId !== projectIdStr) {
+ throw new PinnedContextSwitchError(pinned.pin)
+ }
+
// 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
@@ -43,7 +51,16 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn
}
const project: CachedProject = projectResult.data
- await context.cache.set('projectId', projectIdStr)
+ const projectOrgId = project.organization
+ if (pinLocksContext && pinned.pin.organizationId && projectOrgId && projectOrgId !== pinned.pin.organizationId) {
+ throw new PinnedContextSwitchError({ organizationId: pinned.pin.organizationId })
+ }
+
+ const orgChanged = Boolean(projectOrgId && projectOrgId !== activeOrgId)
+ await context.stateManager.setActiveContext({
+ projectId: projectIdStr,
+ ...(orgChanged ? { orgId: projectOrgId } : {}),
+ })
await context.cache.set(`cachedProject:${projectIdStr}` as const, project)
await context.cache.set(`cachedProjectFetchedAt:${projectIdStr}` as const, Date.now())
@@ -53,9 +70,7 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn
let orgId = activeOrgId
let org: CachedOrg | undefined
let switchedOrg = false
- const projectOrgId = project.organization
- if (projectOrgId && projectOrgId !== activeOrgId) {
- await context.cache.set('orgId', projectOrgId)
+ if (orgChanged) {
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.
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
index 30992824be8f..39436daee94f 100644
--- a/services/mcp/src/tools/types.ts
+++ b/services/mcp/src/tools/types.ts
@@ -19,7 +19,7 @@ export type SessionState = {
// `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.
+// RequestStateResolver.resolvePinnedContext.
export type SessionScopedState = {
activeProjectId: string | undefined
activeOrgId: string | undefined
@@ -27,6 +27,22 @@ export type SessionScopedState = {
appliedPinOrgId: string | undefined
}
+/**
+ * The org and project a pinned request runs against. The resolver builds it once
+ * per request from the pin and the session's recorded switch, and `StateManager`
+ * reads it before the token cache. The token cache is shared by every session on
+ * the same credential, so the pin never goes there.
+ */
+export type PinnedActiveContext = {
+ /** The org and project ids that the request params, or the session's saved pin, pinned. */
+ pin: { organizationId?: string | undefined; projectId?: string | undefined }
+ /** True when an MCP session records switches across requests. */
+ sessionScoped: boolean
+ /** Effective ids for this request. A switch updates them in place. */
+ orgId?: string | undefined
+ projectId?: string | undefined
+}
+
export type CachedUser = ApiUser
export type CachedOrg = Schemas.OrganizationBasic
export type CachedProject = Schemas.ProjectBackwardCompat
@@ -130,7 +146,7 @@ export type Context = {
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
+ * doesn't revert it (see RequestStateResolver.resolvePinnedContext). Absent
* when the request carries no MCP session id — there is no cross-request
* session state to record for.
*/
diff --git a/services/mcp/tests/hono/pinned-context-switch.test.ts b/services/mcp/tests/hono/pinned-context-switch.test.ts
new file mode 100644
index 000000000000..05becb6a6aaa
--- /dev/null
+++ b/services/mcp/tests/hono/pinned-context-switch.test.ts
@@ -0,0 +1,441 @@
+import { http, HttpResponse } from 'msw'
+import { setupServer } from 'msw/node'
+import { createHash } from 'node:crypto'
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+
+import { createApp } from '@/hono/app'
+import { RedisCache, type RedisLike } from '@/hono/cache/RedisCache'
+import { hash } from '@/lib/utils'
+import type { SessionScopedState, State } from '@/tools/types'
+
+import { contextMillHandler, handlers } from '../workers/fixtures/handlers'
+import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'
+
+const PINNED_PROJECT = '1'
+const PINNED_ORG = '019d85ef-7e7d-0000-090c-f2f598b3949b'
+const OTHER_PROJECT = '2'
+const OTHER_ORG = '019d85ef-7e7d-0000-090c-000000000002'
+const MISSING_PROJECT = '404'
+
+const apiPaths: string[] = []
+
+const mswServer = setupServer(
+ http.get('*/api/projects/:projectId/', ({ params }) =>
+ params.projectId === MISSING_PROJECT
+ ? HttpResponse.json({ detail: 'Not found.' }, { status: 404 })
+ : HttpResponse.json({
+ id: Number(params.projectId),
+ uuid: `0000000${String(params.projectId)}-0000-0000-0000-000000000000`,
+ name: `Project ${String(params.projectId)}`,
+ organization: params.projectId === OTHER_PROJECT ? OTHER_ORG : PINNED_ORG,
+ })
+ ),
+ http.post('*/api/environments/:projectId/mcp_tools/execute_sql/', ({ request }) => {
+ apiPaths.push(new URL(request.url).pathname)
+ return HttpResponse.json({ success: true, content: 'ok' })
+ }),
+ http.get('*/api/organizations/:orgId/billing/subscription/', ({ request }) => {
+ apiPaths.push(new URL(request.url).pathname)
+ return HttpResponse.json({})
+ }),
+ ...handlers,
+ contextMillHandler
+)
+
+function createInMemoryRedis(): RedisLike & {
+ ping(): Promise<string>
+ incrby(key: string, increment: number): Promise<number>
+} {
+ const store = new Map<string, string>()
+ return {
+ get: async (key) => store.get(key) ?? null,
+ set: async (key, value) => {
+ store.set(key, String(value))
+ return 'OK'
+ },
+ del: async (...keys) => keys.filter((key) => store.delete(key)).length,
+ scan: async () => ['0', Array.from(store.keys())] as [string, string[]],
+ ...makeRedisRateLimitStubs(store),
+ ping: async () => 'PONG',
+ }
+}
+
+let app: ReturnType<typeof createApp>['app']
+let redis: ReturnType<typeof createInMemoryRedis>
+
+beforeAll(async () => {
+ process.env.TEST = '1'
+ process.env.MCP_APPS_BASE_URL = 'https://apps.test'
+ mswServer.listen({ onUnhandledRequest: 'bypass' })
+ redis = createInMemoryRedis()
+ const created = createApp(redis)
+ app = created.app
+ await created.warmup()
+})
+
+afterAll(() => {
+ mswServer.close()
+})
+
+type CallOptions = {
+ // Each test uses its own token, so the shared token cache never carries state between tests.
+ token?: string
+ query?: string
+ sessionId?: string
+}
+
+function requestHeaders({ token = 'phx_default', sessionId }: CallOptions): Record<string, string> {
+ return {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json, text/event-stream',
+ 'x-posthog-mcp-mode': 'tools',
+ 'x-posthog-flag-overrides': JSON.stringify({ 'organization-billing-api': true }),
+ ...(sessionId ? { 'mcp-session-id': sessionId } : {}),
+ }
+}
+
+async function initialize(options: CallOptions): Promise<string> {
+ const response = await app.request(`/mcp${options.query ?? ''}`, {
+ method: 'POST',
+ headers: requestHeaders(options),
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 0,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2025-06-18',
+ capabilities: {},
+ clientInfo: { name: 'pin-test', version: '0.0.0' },
+ },
+ }),
+ })
+ const sessionId = response.headers.get('mcp-session-id')
+ if (!sessionId) {
+ throw new Error(`initialize returned no session id: ${await response.text()}`)
+ }
+ return sessionId
+}
+
+type ToolCallResponse = {
+ status: number
+ result?: { isError?: boolean; content?: Array<{ text?: string }> }
+ error?: { code?: number; message?: string; data?: { reason?: string } }
+}
+
+async function postToolCall(
+ name: string,
+ args: Record<string, unknown>,
+ { query = `?project_id=${PINNED_PROJECT}`, ...options }: CallOptions = {}
+): Promise<ToolCallResponse> {
+ const response = await app.request(`/mcp${query}`, {
+ method: 'POST',
+ headers: requestHeaders(options),
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }),
+ })
+ const raw = await response.text()
+ const json = JSON.parse(raw.startsWith('{') ? raw : raw.slice(raw.indexOf('{'))) as Omit<ToolCallResponse, 'status'>
+ return { status: response.status, ...json }
+}
+
+async function callTool(
+ name: string,
+ args: Record<string, unknown>,
+ options: CallOptions = {}
+): Promise<{ isError?: boolean; text: string }> {
+ const { result, error } = await postToolCall(name, args, options)
+ if (!result) {
+ throw new Error(`tools/call ${name} failed: ${error?.message ?? 'no result'}`)
+ }
+ return { isError: result.isError, text: result.content?.[0]?.text ?? '' }
+}
+
+// The project the query tool and the org the billing tool really call, or null when the tool calls nothing.
+async function targets(options: CallOptions): Promise<{ project: string | null; org: string | null }> {
+ apiPaths.length = 0
+ await postToolCall('execute-sql', { query: 'SELECT 1' }, options)
+ const project = apiPaths.map((path) => /^\/api\/environments\/([^/]+)\//.exec(path)?.[1]).find(Boolean) ?? null
+ apiPaths.length = 0
+ await postToolCall('billing-subscription-get', {}, options)
+ const org = apiPaths.map((path) => /^\/api\/organizations\/([^/]+)\//.exec(path)?.[1]).find(Boolean) ?? null
+ apiPaths.length = 0
+ return { project, org }
+}
+
+const tokenCache = (token: string): RedisCache<State> => new RedisCache<State>(hash(token), redis, 'token')
+
+// The session store key that deployed servers used before it included the credential.
+async function seedLegacySession(sessionId: string, state: Partial<SessionScopedState>): Promise<void> {
+ const legacyPrefix = createHash('sha256').update(sessionId).digest().subarray(0, 16).toString('base64url')
+ await new RedisCache<SessionScopedState>(legacyPrefix, redis, 'session', 3600).setMany(state)
+}
+
+async function runQueryAndBilling(options: CallOptions = {}): Promise<string[]> {
+ apiPaths.length = 0
+ expect((await callTool('execute-sql', { query: 'SELECT 1' }, options)).isError).toBeFalsy()
+ expect((await callTool('billing-subscription-get', {}, options)).isError).toBeFalsy()
+ return [...apiPaths]
+}
+
+async function runBilling(options: CallOptions): Promise<{ isError?: boolean; paths: string[] }> {
+ apiPaths.length = 0
+ const result = await callTool('billing-subscription-get', {}, options)
+ return { isError: result.isError, paths: [...apiPaths] }
+}
+
+const pathsFor = (projectId: string, orgId: string): string[] => [
+ `/api/environments/${projectId}/mcp_tools/execute_sql/`,
+ `/api/organizations/${orgId}/billing/subscription/`,
+]
+const billingPathFor = (orgId: string): string[] => [`/api/organizations/${orgId}/billing/subscription/`]
+
+// An unpinned, sessionless switch writes the shared token cache, as another session on the credential would.
+async function cacheOtherProjectOnToken(token: string): Promise<void> {
+ const switched = await callTool('switch-project', { projectId: Number(OTHER_PROJECT) }, { token, query: '' })
+ expect(switched.isError).toBeFalsy()
+ expect(await runQueryAndBilling({ token, query: '' })).toEqual(pathsFor(OTHER_PROJECT, OTHER_ORG))
+}
+
+describe('pinned project with switch-project (Hono)', () => {
+ beforeEach(() => {
+ 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}`)
+
+ // 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))
+ })
+
+ it('refuses switch-project without an MCP session instead of reporting a switch the pin reverts', async () => {
+ const token = 'phx_sessionless'
+ const switched = await callTool('switch-project', { projectId: Number(OTHER_PROJECT) }, { token })
+ expect(switched.isError).toBe(true)
+ expect(switched.text).toContain('sends no MCP session id')
+
+ expect(await runQueryAndBilling({ token })).toEqual(pathsFor(PINNED_PROJECT, PINNED_ORG))
+ })
+
+ it.each([
+ ['project', `?project_id=${PINNED_PROJECT}`],
+ ['organization', `?organization_id=${PINNED_ORG}`],
+ ])('keeps a %s pin sent only on initialize for later requests in the session', async (kind, pinQuery) => {
+ const token = `phx_init_${kind}`
+ await cacheOtherProjectOnToken(token)
+
+ const sessionId = await initialize({ token, query: pinQuery })
+
+ expect(await targets({ token, sessionId, query: '' })).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+
+ // The saved pin belongs to the credential: another token that reuses the session id keeps its own state.
+ const otherToken = `phx_init_${kind}_other`
+ await cacheOtherProjectOnToken(otherToken)
+ expect(await targets({ token: otherToken, sessionId, query: '' })).toEqual({
+ project: OTHER_PROJECT,
+ org: OTHER_ORG,
+ })
+ })
+
+ it("reports missing context instead of using another session's org when the pinned project lookup fails", async () => {
+ const token = 'phx_missing_project'
+ await cacheOtherProjectOnToken(token)
+
+ const result = await runBilling({ token, query: `?project_id=${MISSING_PROJECT}` })
+
+ expect(result.isError).toBe(true)
+ expect(result.paths).toEqual([])
+ })
+
+ it("lets a sessionless project pin switch only to the project's own organization", async () => {
+ const token = 'phx_switch_org'
+ const ownOrg = await callTool('switch-organization', { orgId: PINNED_ORG }, { token })
+ expect(ownOrg.isError).toBeFalsy()
+ expect(await runBilling({ token })).toEqual({ isError: undefined, paths: billingPathFor(PINNED_ORG) })
+
+ const otherOrg = await callTool('switch-organization', { orgId: OTHER_ORG }, { token })
+ expect(otherOrg.isError).toBe(true)
+ expect(otherOrg.text).toContain('sends no MCP session id')
+ expect(await runBilling({ token })).toEqual({ isError: undefined, paths: billingPathFor(PINNED_ORG) })
+ })
+ it('keeps an unpinned session on the shared token selection across repeated switches', async () => {
+ const token = 'phx_unpinned_switches'
+ const session = { token, sessionId: await initialize({ token, query: '' }), query: '' }
+ const otherRequest = { token, query: '' }
+
+ for (const [projectId, orgId] of [
+ [OTHER_PROJECT, OTHER_ORG],
+ [PINNED_PROJECT, PINNED_ORG],
+ [OTHER_PROJECT, OTHER_ORG],
+ ]) {
+ expect((await callTool('switch-project', { projectId: Number(projectId) }, session)).isError).toBeFalsy()
+ expect(await targets(session)).toEqual({ project: projectId, org: orgId })
+ expect(await targets(otherRequest)).toEqual({ project: projectId, org: orgId })
+ }
+ })
+
+ it.each([
+ {
+ label: 'a project pin replaced by an organization pin',
+ initPin: `?project_id=${PINNED_PROJECT}`,
+ switchTo: undefined,
+ replacementPin: `?organization_id=${OTHER_ORG}`,
+ expected: { project: OTHER_PROJECT, org: OTHER_ORG },
+ },
+ {
+ label: 'an organization pin replaced by a project pin',
+ initPin: `?organization_id=${OTHER_ORG}`,
+ switchTo: undefined,
+ replacementPin: `?project_id=${PINNED_PROJECT}`,
+ expected: { project: PINNED_PROJECT, org: PINNED_ORG },
+ },
+ {
+ label: 'a two-field pin that drops the organization',
+ initPin: `?organization_id=${PINNED_ORG}&project_id=${PINNED_PROJECT}`,
+ switchTo: OTHER_PROJECT,
+ replacementPin: `?project_id=${PINNED_PROJECT}`,
+ expected: { project: PINNED_PROJECT, org: PINNED_ORG },
+ },
+ {
+ label: 'a two-field pin that drops the project',
+ initPin: `?organization_id=${PINNED_ORG}&project_id=${PINNED_PROJECT}`,
+ switchTo: OTHER_PROJECT,
+ replacementPin: `?organization_id=${PINNED_ORG}`,
+ expected: { project: PINNED_PROJECT, org: PINNED_ORG },
+ },
+ ])('replaces the whole saved pin for $label', async ({ label, initPin, switchTo, replacementPin, expected }) => {
+ const token = `phx_replace_${label.replaceAll(' ', '_')}`
+ await cacheOtherProjectOnToken(token)
+ const sessionId = await initialize({ token, query: initPin })
+ const switched = switchTo
+ ? await callTool('switch-project', { projectId: Number(switchTo) }, { token, sessionId, query: initPin })
+ : undefined
+ expect(switched?.isError).toBeFalsy()
+
+ expect(await targets({ token, sessionId, query: replacementPin })).toEqual(expected)
+ // A later request that omits the pin restores only what the replacement pin set.
+ expect(await targets({ token, sessionId, query: '' })).toEqual(expected)
+ })
+
+ const cacheDefaultProjectOnToken = async (token: string): Promise<void> => {
+ expect(await targets({ token, query: '' })).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+ }
+ const cacheMissingProjectOnToken = async (token: string): Promise<void> => {
+ await tokenCache(token).set('projectId', MISSING_PROJECT)
+ }
+
+ it.each([
+ {
+ label: 'a cached project in another organization',
+ seed: cacheDefaultProjectOnToken,
+ pinnedOrg: OTHER_ORG,
+ expected: { project: null, org: OTHER_ORG },
+ },
+ {
+ label: 'no cached project and a default in another organization',
+ seed: undefined,
+ pinnedOrg: OTHER_ORG,
+ expected: { project: null, org: OTHER_ORG },
+ },
+ {
+ label: 'an inaccessible cached project',
+ seed: cacheMissingProjectOnToken,
+ pinnedOrg: OTHER_ORG,
+ expected: { project: null, org: OTHER_ORG },
+ },
+ {
+ label: 'a cached project in the pinned organization',
+ seed: cacheOtherProjectOnToken,
+ pinnedOrg: OTHER_ORG,
+ expected: { project: OTHER_PROJECT, org: OTHER_ORG },
+ },
+ {
+ label: 'no cached project and a default in the pinned organization',
+ seed: undefined,
+ pinnedOrg: PINNED_ORG,
+ expected: { project: PINNED_PROJECT, org: PINNED_ORG },
+ },
+ {
+ label: 'a cached project in another organization and a default in the pinned organization',
+ seed: cacheOtherProjectOnToken,
+ pinnedOrg: PINNED_ORG,
+ expected: { project: PINNED_PROJECT, org: PINNED_ORG },
+ },
+ ])('limits an organization pin to its own projects with $label', async ({ label, seed, pinnedOrg, expected }) => {
+ const token = `phx_org_pin_${label.replaceAll(' ', '_')}`
+ await seed?.(token)
+ const cachedBefore = await tokenCache(token).get('projectId')
+
+ expect(await targets({ token, query: `?organization_id=${pinnedOrg}` })).toEqual(expected)
+ // The org pin never writes its project choice into the selection that other requests share.
+ expect(await tokenCache(token).get('projectId')).toEqual(cachedBefore)
+ })
+
+ it('keeps an explicit cross-organization switch in an organization-pinned session', async () => {
+ const token = 'phx_org_pin_cross_switch'
+ const pin = `?organization_id=${PINNED_ORG}`
+ const sessionId = await initialize({ token, query: pin })
+ const switched = await callTool(
+ 'switch-project',
+ { projectId: Number(OTHER_PROJECT) },
+ { token, sessionId, query: pin }
+ )
+ expect(switched.isError).toBeFalsy()
+
+ expect(await targets({ token, sessionId, query: pin })).toEqual({ project: OTHER_PROJECT, org: OTHER_ORG })
+ expect(await targets({ token, sessionId, query: '' })).toEqual({ project: OTHER_PROJECT, org: OTHER_ORG })
+ })
+
+ it.each([
+ ['with the original pin resent', `?project_id=${PINNED_PROJECT}`],
+ ['with the pin omitted', ''],
+ ])('asks a switched session from before the credential-bound store to reconnect, %s', async (label, query) => {
+ const token = `phx_legacy_${label.replaceAll(' ', '_')}`
+ const sessionId = `legacy-session-${label.replaceAll(' ', '-')}`
+ await seedLegacySession(sessionId, {
+ appliedPinProjectId: PINNED_PROJECT,
+ activeProjectId: OTHER_PROJECT,
+ activeOrgId: OTHER_ORG,
+ })
+
+ for (const credential of [token, `${token}_other`]) {
+ for (const [name, args] of [
+ ['execute-sql', { query: 'SELECT 1' }],
+ ['billing-subscription-get', {}],
+ ] as const) {
+ const response = await postToolCall(name, args, { token: credential, sessionId, query })
+ expect(response).toMatchObject({ status: 200, error: { data: { reason: 'session_reset_required' } } })
+ expect(response.result).toBeUndefined()
+ }
+ }
+ expect(apiPaths).toEqual([])
+
+ const freshSessionId = await initialize({ token, query: `?project_id=${PINNED_PROJECT}` })
+ expect(await targets({ token, sessionId: freshSessionId, query: '' })).toEqual({
+ project: PINNED_PROJECT,
+ org: PINNED_ORG,
+ })
+ })
+
+ it('ignores legacy session state that never held a pin', async () => {
+ const token = 'phx_legacy_unpinned'
+ const sessionId = 'legacy-session-unpinned'
+ await cacheOtherProjectOnToken(token)
+ await seedLegacySession(sessionId, { activeProjectId: PINNED_PROJECT, activeOrgId: PINNED_ORG })
+
+ expect(await targets({ token, sessionId, query: '' })).toEqual({ project: OTHER_PROJECT, org: OTHER_ORG })
+ })
+})
diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.ts
index 3e407f80c9bc..a88be6028e7a 100644
--- a/services/mcp/tests/hono/request-state-resolver.test.ts
+++ b/services/mcp/tests/hono/request-state-resolver.test.ts
@@ -7,6 +7,7 @@ const {
mockSessionScopedStores,
mockRefreshTtlCalls,
mockRedisFailures,
+ mockPinned,
} = vi.hoisted(() => ({
mockSessionStore: new Map<string, unknown>(),
mockTokenStore: new Map<string, unknown>(),
@@ -23,8 +24,11 @@ const {
mockRedisFailures: {
contextError: undefined as Error | undefined,
pinWriteGate: undefined as Promise<void> | undefined,
+ legacyReadError: undefined as Error | undefined,
contextReads: 0,
},
+ // The request-scoped context the last resolve handed to RequestContext.
+ mockPinned: { last: undefined as { orgId?: string; projectId?: string; sessionScoped: boolean } | undefined },
}))
vi.mock('@/lib/posthog/flags', () => ({
@@ -65,7 +69,7 @@ vi.mock('@/hono/request-context', () => {
store.set(key, value)
}),
setMany: vi.fn(async (entries: Record<string, unknown>) => {
- if (store === mockTokenStore) {
+ if (store !== mockTokenStore) {
await mockRedisFailures.pinWriteGate
}
for (const [key, value] of Object.entries(entries)) {
@@ -100,6 +104,16 @@ vi.mock('@/hono/request-context', () => {
return {
tokenCache: makeCache(mockTokenStore),
sessionScopedCache: props.mcpSessionId ? makeCache(sessionScopedStore(props.mcpSessionId)) : undefined,
+ legacySessionScopedCache: props.mcpSessionId
+ ? {
+ get: vi.fn(async () => {
+ if (mockRedisFailures.legacyReadError) {
+ throw mockRedisFailures.legacyReadError
+ }
+ return undefined
+ }),
+ }
+ : undefined,
getContext: vi.fn(async () => {
mockRedisFailures.contextReads += 1
if (mockRedisFailures.contextError) {
@@ -117,6 +131,9 @@ vi.mock('@/hono/request-context', () => {
safelyGetAnalyticsContext: vi.fn(async () => undefined),
getDistinctId: vi.fn(async () => 'distinct-id'),
setMcpContexts: vi.fn(),
+ setPinnedContext: vi.fn((pinned: typeof mockPinned.last) => {
+ mockPinned.last = pinned
+ }),
}
}),
}
@@ -172,7 +189,9 @@ describe('RequestStateResolver MCP client contexts', () => {
mockRefreshTtlCalls.length = 0
mockRedisFailures.contextError = undefined
mockRedisFailures.pinWriteGate = undefined
+ mockRedisFailures.legacyReadError = undefined
mockRedisFailures.contextReads = 0
+ mockPinned.last = undefined
mockApiKey.scopes = ['*']
mockApiKey.is_impersonated = undefined
mockApiKey.suppress_analytics = undefined
@@ -229,6 +248,17 @@ describe('RequestStateResolver MCP client contexts', () => {
}
})
+ it.each([
+ ['a pinned request', { projectId: '1' }],
+ ['a request without a pin', { projectId: undefined }],
+ ])('fails %s when the legacy session store cannot be read', async (_label, pin) => {
+ // Skipping the check would let a pre-upgrade session run tools against a silently reset selection.
+ mockRedisFailures.legacyReadError = new Error('Command timed out')
+
+ await expect(makeResolver().resolve(makeProps(pin))).rejects.toThrow('Command timed out')
+ expect(mockRedisFailures.contextReads).toBe(0)
+ })
+
it.each([
['cli', false],
['cli', true],
@@ -477,11 +507,13 @@ describe('RequestStateResolver MCP client contexts', () => {
})
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)
+ // What the switch-project handler records on the session (Context.setSessionActiveContext).
+ const simulateSwitch = (mcpSessionId: string, projectId: string, orgId?: string): void => {
+ const store = mockSessionScopedStores.get(mcpSessionId)
+ store?.set('activeProjectId', projectId)
+ if (orgId) {
+ store?.set('activeOrgId', orgId)
+ }
}
it('does not revert an in-session switch-project when the same pin is resent', async () => {
@@ -489,12 +521,12 @@ describe('RequestStateResolver MCP client contexts', () => {
// 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')
+ expect(mockPinned.last?.projectId).toBe('1')
simulateSwitch('mcp-session-1', '2')
await makeResolver().resolve(makeProps({ projectId: '1' }))
- expect(mockTokenStore.get('projectId')).toBe('2')
+ expect(mockPinned.last?.projectId).toBe('2')
})
it('re-applies a changed pin and discards the recorded switch', async () => {
@@ -502,7 +534,7 @@ describe('RequestStateResolver MCP client contexts', () => {
simulateSwitch('mcp-session-1', '2')
await makeResolver().resolve(makeProps({ projectId: '9' }))
- expect(mockTokenStore.get('projectId')).toBe('9')
+ expect(mockPinned.last?.projectId).toBe('9')
expect(mockSessionScopedStores.get('mcp-session-1')?.get('activeProjectId')).toBeUndefined()
})
@@ -512,38 +544,42 @@ describe('RequestStateResolver MCP client contexts', () => {
// 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')
+ simulateSwitch('mcp-session-1', '2', 'org-2')
await makeResolver().resolve(makeProps({ organizationId: 'org-1', projectId: '9' }))
- expect(mockTokenStore.get('orgId')).toBe('org-1')
- expect(mockTokenStore.get('projectId')).toBe('9')
+ expect(mockPinned.last).toMatchObject({ orgId: 'org-1', projectId: '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).
+ // No session means no cross-request continuity, so the pin wins each
+ // request and the switch tools must refuse instead of reporting success.
await makeResolver().resolve(makeProps({ projectId: '1', mcpSessionId: undefined }))
+ expect(mockPinned.last).toMatchObject({ projectId: '1', sessionScoped: false })
+ })
+
+ it.each([
+ ['with an MCP session', 'mcp-session-1'],
+ ['without an MCP session', undefined],
+ ])('never writes the pin into the shared token cache %s', async (_label, mcpSessionId) => {
+ // The token cache is shared by every session on the credential. A pin
+ // written there reverts a switch-project and leaks into other sessions.
mockTokenStore.set('projectId', '2')
+ mockTokenStore.set('orgId', 'org-2')
- await makeResolver().resolve(makeProps({ projectId: '1', mcpSessionId: undefined }))
- expect(mockTokenStore.get('projectId')).toBe('1')
+ await makeResolver().resolve(makeProps({ organizationId: 'org-1', projectId: '1', mcpSessionId }))
+
+ expect(mockTokenStore.get('projectId')).toBe('2')
+ expect(mockTokenStore.get('orgId')).toBe('org-2')
+ expect(mockPinned.last).toMatchObject({ orgId: 'org-1', projectId: '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')
+ expect(mockPinned.last?.projectId).toBe('2')
await makeResolver().resolve(makeProps({ projectId: '1', mcpSessionId: 'session-a' }))
- expect(mockTokenStore.get('projectId')).toBe('1')
+ expect(mockPinned.last?.projectId).toBe('1')
})
it('renews the session-scoped keys TTL on every pinned request', async () => {
diff --git a/services/mcp/tests/unit/switch-project.test.ts b/services/mcp/tests/unit/switch-project.test.ts
index e3b2b8adbfbc..c0dda18cf6c7 100644
--- a/services/mcp/tests/unit/switch-project.test.ts
+++ b/services/mcp/tests/unit/switch-project.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import setActiveProjectTool from '@/tools/projects/setActive'
-import type { Context } from '@/tools/types'
+import type { Context, PinnedActiveContext } from '@/tools/types'
const ACTIVE_ORG = 'org-active'
const OTHER_ORG = 'org-other'
@@ -10,6 +10,7 @@ function createMockContext(overrides: {
projectGet: ReturnType<typeof vi.fn>
getOrgID?: ReturnType<typeof vi.fn>
getCachedOrFetchOrg?: ReturnType<typeof vi.fn>
+ pinnedContext?: PinnedActiveContext
}): {
context: Context
cache: Map<string, unknown>
@@ -34,6 +35,15 @@ function createMockContext(overrides: {
getOrgID: overrides.getOrgID ?? vi.fn().mockResolvedValue(ACTIVE_ORG),
getCachedOrFetchOrg,
getOrFetchIntegrationKinds: vi.fn().mockResolvedValue(undefined),
+ pinnedContext: overrides.pinnedContext,
+ setActiveContext: async (updates: { orgId?: string; projectId?: string }) => {
+ if (updates.orgId) {
+ cache.set('orgId', updates.orgId)
+ }
+ if (updates.projectId) {
+ cache.set('projectId', updates.projectId)
+ }
+ },
},
env: {},
sessionManager: {},
@@ -133,4 +143,21 @@ describe('switch-project', () => {
expect(result.content[0]!.text).not.toContain('also switched the active organization')
expect(cache.get('orgId')).toBe(OTHER_ORG)
})
+
+ it.each<[string, PinnedActiveContext['pin'], number, string]>([
+ ['a project pin', { projectId: '1' }, 42, ACTIVE_ORG],
+ ['an org pin, to a project in another org', { organizationId: ACTIVE_ORG }, 77, OTHER_ORG],
+ ])('refuses a switch that %s would revert when there is no MCP session', async (_label, pin, projectId, org) => {
+ const projectGet = vi.fn().mockResolvedValue({
+ success: true,
+ data: { id: projectId, name: 'Project', organization: org },
+ })
+ const { context, cache } = createMockContext({
+ projectGet,
+ pinnedContext: { pin, sessionScoped: false, orgId: pin.organizationId, projectId: pin.projectId },
+ })
+
+ await expect(tool.handler(context, { projectId })).rejects.toThrow(/sends no MCP session id/)
+ expect(cache.get('projectId')).toBeUndefined()
+ })
})