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): isolate project context across mcp and cli (#120215)

Richard Solomou836ca745eedc
diff --git a/cli/Cargo.toml b/cli/Cargo.toml
index 475bfce7ee83..eee963b74cfa 100644
--- a/cli/Cargo.toml
+++ b/cli/Cargo.toml
@@ -77,7 +77,6 @@ similar = "2.7"
open = "5"
zip = { version = "2.2", default-features = false, features = ["deflate", "deflate-zlib"] }
tempfile = "3"
-zstd = "0.13"
symbolic = { version = "12.12", features = ["debuginfo"] }
plist = "1"
@@ -86,6 +85,7 @@ libc = "0.2"
[dev-dependencies]
test-log = "0.2.17"
+zstd = "0.13"
[workspace.lints.rust]
# See https://doc.rust-lang.org/stable/rustc/lints/listing/allowed-by-default.html
diff --git a/cli/README.md b/cli/README.md
index 7043abfadfd4..777fb8937e00 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -192,6 +192,20 @@ posthog-cli api agents-md install
Destructive tools require `--confirm` when executed. Use `--dry-run` before mutations.
+### Concurrent agents and project targeting
+
+Give each API call its own target with `--project-id` and optionally `--organization-id`:
+
+```bash
+posthog-cli api call --project-id 123 --json feature-flag-get-all '{"limit":5}'
+posthog-cli api call --project-id 456 --json feature-flag-get-all '{"limit":5}'
+posthog-cli api call --organization-id 00000000-0000-0000-0000-000000000001 --json projects-get '{}'
+```
+
+These calls can run concurrently with the same API key, including against projects in different organizations. The key must already grant access to both targets. A project-only target derives its organization from the project. An organization-only target never falls back to a project in another organization; pass a project ID for project-scoped tools.
+
+Explicit target flags replace both inherited target defaults, so an organization override does not inherit the project from your saved login, and a project override does not inherit another organization. Targets apply to one invocation and do not update your saved login or website selection. Repeat the flags on each call, or set `POSTHOG_CLI_PROJECT_ID` and `POSTHOG_CLI_ORGANIZATION_ID` separately in each agent's environment. The API bundle also accepts `POSTHOG_PROJECT_ID` and `POSTHOG_ORGANIZATION_ID`, which take precedence over the `POSTHOG_CLI_*` aliases. Switch tools do not persist a selection across CLI invocations.
+
`posthog-cli api --agent-help` prints the full agent-facing guide — the same exec tool reference the PostHog MCP server serves, rewritten for CLI invocation — so agents can load it into context before interacting with PostHog APIs.
### Agent steering instructions
diff --git a/cli/src/api_proxy.rs b/cli/src/api_proxy.rs
index d2ca92fbeb64..def75b946934 100644
--- a/cli/src/api_proxy.rs
+++ b/cli/src/api_proxy.rs
@@ -256,6 +256,8 @@ fn inject_credentials(cmd: &mut Command, invocation_context: Option<&InvocationC
"POSTHOG_PROJECT_ID",
"POSTHOG_CLI_PROJECT_ID",
"POSTHOG_CLI_ENV_ID",
+ "POSTHOG_ORGANIZATION_ID",
+ "POSTHOG_CLI_ORGANIZATION_ID",
]) {
cmd.env("POSTHOG_CLI_PROJECT_ID", &config.env_id);
}
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index 4668a440b99b..a860a8dd40e9 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -73,6 +73,24 @@ Copying only the message loses the HTTP status and retry guidance.
For HTTP 503 responses, the shared client passes a numeric `Retry-After` value to the agent as a minimum wait.
It does not retry these requests automatically.
+## Project and organization context
+
+Resolve tool targets through `context.stateManager.getProjectId()` or `getOrgID()`. The Hono server snapshots the active selection for each request and stores it per credential and MCP transport session. Separate sessions can use the same credential concurrently in different organizations and projects, with or without URL pins. Unpinned sessions initialize from the user's active selection within the credential's allowed scope; later website changes do not retarget an existing session. Organization switches clear the previous project, and project switches keep the organization consistent with the selected project.
+
+The shared token cache holds credential and entity metadata. Its `orgId` and `projectId` selection keys remain only for requests without a session or conversation identity. Session-aware tools must use the state manager instead of reading those keys directly. Session selections expire after 24 hours without requests.
+
+For sessionless clients, the server scopes selection to the SDK's echoed `conversation_id`, bound to the credential and separated from transport session IDs. The dispatcher restores echoed handles before state resolution. When the SDK mints a handle on the first tool call, the executor resolves state with that handle before running the tool. Switches require a carried session or conversation handle, including when called through `exec`. A switch without one returns an error and a new handle; the client must retry with that handle and echo it on subsequent calls. Calls without either identity start from the connection's pin or default selection. Clients unable to retain handles should pin the project or organization in the connection URL. The SDK remains responsible for generating and normalizing conversation handles and producing analytics.
+
+Sessionless legacy batches resolve each call's handle and state independently before checking whether a switch is allowed. The wrapper's `sessionId` query parameter groups analytics but cannot restore selections; wrapper-only calls still receive SDK-minted conversation handles.
+
+State managers share credential, user, and entity lookups within one HTTP request, including when a new conversation handle requires another resolution. Lookup keys include the credential cache scope and entity ID. Each call retains its own state manager, selection, flags, and API client. Redis TTLs still govern freshness, and rejected lookup promises are removed so later attempts can retry.
+
+Remote flag evaluations share the same request-local cache when the credential, distinct ID, groups, and requested flag keys match. Flag values and payloads stay separate across different evaluation contexts. Request overrides are applied after the shared evaluation, and failed evaluations remain retryable.
+
+Session defaults are saved once with `SET NX` and kept separate from explicit selections. Lazy organization and project resolution updates only the request snapshot, so a delayed read cannot replace a newer switch in the same session.
+
+An org-only default does not freeze a failed project lookup. Project discovery retries within the saved organization and records the first successful result separately with `SET NX`. Organization-scoped discovery establishes project ownership without a second global metadata lookup. Organization switches can retain a selected project using the destination organization's team list when project metadata is unavailable.
+
## SQL-first data retrieval
The MCP server instructs the agent to read data through a unified HogQL interface
diff --git a/services/mcp/ARCHITECTURE.md b/services/mcp/ARCHITECTURE.md
index 8f0b2b8b4ed2..317322b284a9 100644
--- a/services/mcp/ARCHITECTURE.md
+++ b/services/mcp/ARCHITECTURE.md
@@ -79,6 +79,14 @@ The Hono runtime keeps per-user session state (active project/organization, regi
- **Deterministic**: Same token always produces the same hash/prefix
- **Secure**: Tokens can't be reversed from the hash
+Project and organization selections are scoped to the credential and transport session, or to the SDK's conversation handle for sessionless clients. Conversation and transport namespaces are separate. Echoed handles resolve before the state lookup; a newly minted handle binds state before tool execution. Both direct and exec-routed switches require the request to carry a session or conversation handle. A switch without one returns an error and the SDK's new handle for retrying. Switching does not update the shared credential selection.
+
+Each sessionless legacy batch item resolves its own request properties, state, and carried-handle guard. A wrapper-only `sessionId` cannot restore selections, so it does not suppress SDK conversation-handle minting.
+
+Credential, user, and entity lookup promises are shared within an HTTP request, keyed by credential cache scope and entity. Per-item state managers and active selections remain independent. Existing Redis TTLs control freshness; rejected promises are removed to permit retries. A newly minted conversation's state resolution uses the same request-local lookup cache.
+
+Remote flag evaluation uses this cache too, keyed by credential, distinct ID, normalized groups, and flag keys. Both flag values and payloads are shared only for matching contexts; each call applies its own overrides afterward. Failed evaluations leave the cache before the resolver returns its empty fallback.
+
### Wide Logging Pattern
Instead of scattered log statements, we accumulate data into a single log object and emit once at the end:
diff --git a/services/mcp/README.md b/services/mcp/README.md
index 465249d4d589..6efca8502d21 100644
--- a/services/mcp/README.md
+++ b/services/mcp/README.md
@@ -410,6 +410,16 @@ The server defaults to port **8787**, reads config from `.env` (see `.env.exampl
### Session cache
+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.
+
+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.
+
+Session defaults are stored once, separately from explicit selections. A delayed lookup can resolve context for its own request without overwriting a completed switch.
+
+If default project discovery fails, later requests retry within the session's original organization. The first successful project discovery wins, and explicit switches still take precedence. An organization switch retains a selected project when the destination's team list confirms that it belongs there, even if the credential cannot read project metadata.
+
A session's client context lives in one `mcp:s:<id>:c` key with a 24-hour idle expiry, refreshed on every request in the session.
Concurrent requests merge their fields through a Lua compare-and-merge, so a field first seen mid-session is never lost to an overlapping write.
diff --git a/services/mcp/src/api/client.ts b/services/mcp/src/api/client.ts
index d7483648c7c3..1ece3ba95e90 100644
--- a/services/mcp/src/api/client.ts
+++ b/services/mcp/src/api/client.ts
@@ -773,8 +773,8 @@ export class ApiClient {
return result
},
- get: async ({ orgId }: { orgId: string }): Promise<Result<Schemas.OrganizationBasic>> => {
- return this.fetchJson<Schemas.OrganizationBasic>(`${this.baseUrl}/api/organizations/${orgId}/`)
+ get: async ({ orgId }: { orgId: string }): Promise<Result<Schemas.Organization>> => {
+ return this.fetchJson<Schemas.Organization>(`${this.baseUrl}/api/organizations/${orgId}/`)
},
projects: ({ orgId }: { orgId: string }) => {
diff --git a/services/mcp/src/cli/agent-help.ts b/services/mcp/src/cli/agent-help.ts
index cb2e5f7dbc29..36acd011e246 100644
--- a/services/mcp/src/cli/agent-help.ts
+++ b/services/mcp/src/cli/agent-help.ts
@@ -9,6 +9,7 @@ const AGENT_HELP_HEADER = `# PostHog API guide for agents
On top of the reference below, the CLI adds:
+- Add \`--project-id <id>\` and optionally \`--organization-id <id>\` to \`posthog-cli api call\` to select the target for that invocation. Explicit target flags replace both inherited project and organization defaults. Repeat the flags on every call, or set \`POSTHOG_CLI_PROJECT_ID\` and \`POSTHOG_CLI_ORGANIZATION_ID\` in each agent's environment. Project-only targets derive their organization from the project. Organization-only targets never fall back to a project in another organization; pass a project ID for project-scoped tools. Switch tools do not persist a selection across CLI invocations.
- \`posthog-cli api call --dry-run <tool> '<json>'\` — validate input against the tool schema without executing. Use it before any mutation.
- Destructive tools refuse to run without \`--confirm\`; add it only after verifying the exact target IDs.
- \`posthog-cli api skill list\` and \`posthog-cli api skill install <skill-id>\` — install PostHog agent skills into \`.agents/skills/\`. Before starting a PostHog task, check the skill list for a match; if one exists, install it, read its \`SKILL.md\`, and follow it — skills contain task-specific workflows that individual tools do not.
diff --git a/services/mcp/src/cli/config.ts b/services/mcp/src/cli/config.ts
index 370c3a1d1c02..0c588d21edfc 100644
--- a/services/mcp/src/cli/config.ts
+++ b/services/mcp/src/cli/config.ts
@@ -1,3 +1,5 @@
+import { takeOption } from './args'
+
export interface CliConfig {
apiKey?: string
host: string
@@ -26,10 +28,20 @@ function parseVersion(value: string | undefined): number {
return Number.isFinite(parsed) && parsed > 0 ? parsed : 2
}
-export function resolveCliConfig(): CliConfig {
+export function resolveCliConfig(args: string[] = []): CliConfig {
const apiKey = firstEnv(['POSTHOG_API_KEY', 'POSTHOG_CLI_API_KEY', 'POSTHOG_CLI_TOKEN'])
- const organizationId = firstEnv(['POSTHOG_ORGANIZATION_ID', 'POSTHOG_CLI_ORGANIZATION_ID'])
- const projectId = firstEnv(['POSTHOG_PROJECT_ID', 'POSTHOG_CLI_PROJECT_ID', 'POSTHOG_CLI_ENV_ID'])
+ const targetOrganizationId = takeOption(args, '--organization-id')
+ const targetProjectId = takeOption(args, '--project-id')
+ const hasTarget = targetOrganizationId !== undefined || targetProjectId !== undefined
+ if (targetOrganizationId === '' || targetProjectId === '') {
+ throw new Error('Project and organization IDs must not be empty.')
+ }
+ const organizationId = hasTarget
+ ? targetOrganizationId
+ : firstEnv(['POSTHOG_ORGANIZATION_ID', 'POSTHOG_CLI_ORGANIZATION_ID'])
+ const projectId = hasTarget
+ ? targetProjectId
+ : firstEnv(['POSTHOG_PROJECT_ID', 'POSTHOG_CLI_PROJECT_ID', 'POSTHOG_CLI_ENV_ID'])
return {
host: firstEnv(['POSTHOG_HOST', 'POSTHOG_CLI_HOST']) ?? DEFAULT_HOST,
diff --git a/services/mcp/src/cli/context.ts b/services/mcp/src/cli/context.ts
index d1a47d0dcff3..ab50c16d4d40 100644
--- a/services/mcp/src/cli/context.ts
+++ b/services/mcp/src/cli/context.ts
@@ -9,7 +9,7 @@ import { resolveScopePreset } from '@/lib/scope-preset'
import { SessionManager } from '@/lib/SessionManager'
import { StateManager } from '@/lib/StateManager'
import { sanitizeHeaderValue } from '@/lib/utils'
-import type { Context, Env, State } from '@/tools/types'
+import type { Context, Env, PinnedActiveContext, State } from '@/tools/types'
import type { CliConfig } from './config'
@@ -30,7 +30,7 @@ const pendingAnalytics = new Set<Promise<void>>()
export async function flushAnalytics(timeoutMs = 2000): Promise<void> {
try {
await Promise.race([
- Promise.allSettled([...pendingAnalytics]),
+ Promise.allSettled(pendingAnalytics),
new Promise((resolve) => setTimeout(resolve, timeoutMs).unref()),
])
await getPostHogClient().shutdown(timeoutMs)
@@ -44,11 +44,17 @@ export async function buildCliContext(config: CliConfig): Promise<Context> {
const fallbackDistinctId = `posthog-cli:${identityKey}`
// Set by the Rust wrapper; joins these events to its telemetry for the same run.
const cliInvocationId = process.env.POSTHOG_CLI_INVOCATION_ID
- const cache = new MemoryCache<State>(`cli:${identityKey}:${config.host}`)
- await cache.setMany({
- ...(config.organizationId ? { orgId: config.organizationId } : {}),
- ...(config.projectId ? { projectId: config.projectId } : {}),
- })
+ const sessionId = randomUUID()
+ const cache = new MemoryCache<State>(`cli:${identityKey}:${config.host}:${sessionId}`)
+ const pinned: PinnedActiveContext | undefined =
+ config.organizationId || config.projectId
+ ? {
+ pin: { organizationId: config.organizationId, projectId: config.projectId },
+ sessionScoped: false,
+ orgId: config.organizationId,
+ projectId: config.projectId,
+ }
+ : undefined
let privateResponse = false
const api = new ApiClient({
@@ -62,9 +68,8 @@ export async function buildCliContext(config: CliConfig): Promise<Context> {
privateResponse = true
},
})
- const stateManager = new StateManager(cache, api)
+ const stateManager = new StateManager(cache, api, pinned)
const sessionManager = new SessionManager(cache)
- const sessionId = randomUUID()
const context: Context = {
api,
diff --git a/services/mcp/src/cli/index.ts b/services/mcp/src/cli/index.ts
index 6687465f198b..fb2996ef14db 100644
--- a/services/mcp/src/cli/index.ts
+++ b/services/mcp/src/cli/index.ts
@@ -44,6 +44,9 @@ Usage:
posthog-cli api skill install [--force] <skill-id>
posthog-cli api agents-md install [--path AGENTS.md]
+Call targets: --project-id <id> and --organization-id <id> override environment and login defaults.
+Targets apply to this invocation. Repeat them on each call or set per-process environment variables.
+
Destructive tools require --confirm when executed. Use --dry-run before mutations.
Agents: run \`posthog-cli api --agent-help\` and load the output into context before anything else.`
}
@@ -109,8 +112,7 @@ async function runStaticExecCommand(command: string): Promise<void> {
printResult(result)
}
-async function runExecCommand(command: string): Promise<void> {
- const config = resolveCliConfig()
+async function runExecCommand(command: string, config: CliConfig): Promise<void> {
if (command.startsWith('call ')) {
requireApiKey(config)
}
@@ -238,6 +240,7 @@ async function main(): Promise<void> {
return
}
case 'call': {
+ const config = resolveCliConfig(args)
const dryRun = takeFlag(args, '--dry-run')
if (dryRun) {
await runDryCall(args)
@@ -250,7 +253,10 @@ async function main(): Promise<void> {
if (!toolName) {
throw new Error('Usage: posthog-cli api call [--json] [--dry-run] [--confirm] <tool> [json]')
}
- await runExecCommand(`call ${json ? '--json ' : ''}${confirmed ? '--confirm ' : ''}${toolName} ${jsonBody}`)
+ await runExecCommand(
+ `call ${json ? '--json ' : ''}${confirmed ? '--confirm ' : ''}${toolName} ${jsonBody}`,
+ config
+ )
return
}
case 'skill':
diff --git a/services/mcp/src/hono/cache/RedisCache.ts b/services/mcp/src/hono/cache/RedisCache.ts
index 79851c493952..bac55d92bb7b 100644
--- a/services/mcp/src/hono/cache/RedisCache.ts
+++ b/services/mcp/src/hono/cache/RedisCache.ts
@@ -77,6 +77,23 @@ export class RedisCache<T extends Record<string, any>> extends ScopedCache<T> {
await this.redis.del(scopedKey)
}
+ async setIfAbsent<K extends keyof T>(key: K, value: T[K]): Promise<boolean> {
+ try {
+ const result = await this.redis.set(
+ this.getScopedKey(key as string),
+ JSON.stringify(value),
+ 'EX',
+ this.ttl,
+ 'NX'
+ )
+ redisOperationsTotal.inc({ operation: 'set', status: 'success' })
+ return result === 'OK'
+ } catch (error) {
+ redisOperationsTotal.inc({ operation: 'set', status: 'error' })
+ throw error
+ }
+ }
+
/**
* 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
diff --git a/services/mcp/src/hono/dispatcher.ts b/services/mcp/src/hono/dispatcher.ts
index 996810d64b87..bdaee4edde91 100644
--- a/services/mcp/src/hono/dispatcher.ts
+++ b/services/mcp/src/hono/dispatcher.ts
@@ -21,6 +21,7 @@ import GUIDELINES from '@shared/guidelines.md'
import { randomUUID } from 'node:crypto'
import { mapErrorToAuthResponse } from '@/lib/auth-errors'
+import { StateLookupCache } from '@/lib/cache/StateLookupCache'
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'
@@ -108,6 +109,15 @@ function isRequest(msg: JSONRPCMessage): msg is JSONRPCRequest {
)
}
+// The SDK owns minting; only restore handles it accepts before resolving tool targets.
+const SDK_CONVERSATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+
+function echoedConversationId(request: JSONRPCRequest): string | undefined {
+ const value = (request.params?.arguments as { conversation_id?: unknown } | undefined)?.conversation_id
+ const id = typeof value === 'string' ? value.trim().toLowerCase() : undefined
+ return id && SDK_CONVERSATION_ID.test(id) ? id : undefined
+}
+
type JsonRpcResultResponse = { jsonrpc: typeof JSONRPC_VERSION; id: number | string; result: unknown }
type JsonRpcErrorResponse = {
jsonrpc: typeof JSONRPC_VERSION
@@ -261,7 +271,14 @@ class McpDispatcher {
props.mcpSessionId = randomUUID()
}
- const needsState = requests.some((r) => TRACKED_METHODS.has(r.method))
+ if (!props.mcpSessionId && requests.length === 1 && requests[0]!.method === Method.ToolsCall) {
+ props.mcpConversationId = echoedConversationId(requests[0]!) ?? props.mcpConversationId
+ }
+
+ const carriedContextHandle = Boolean(props.mcpSessionId || props.mcpConversationId)
+ const sessionlessBatch = wasArray && !props.mcpSessionId
+ const lookups = sessionlessBatch ? new StateLookupCache() : undefined
+ const needsState = !sessionlessBatch && requests.some((r) => TRACKED_METHODS.has(r.method))
let state: ResolvedState | undefined
try {
state = needsState ? await this.stateResolver.resolve(props) : undefined
@@ -309,6 +326,7 @@ class McpDispatcher {
props,
state,
getPublicUrl(req).origin,
+ carriedContextHandle,
canStream
? (request) => {
elicitation = request
@@ -329,7 +347,36 @@ class McpDispatcher {
return new Response(JSON.stringify(result), { status, headers })
}
- const results = await Promise.all(requests.map((r) => this.dispatch(r, props, state, getPublicUrl(req).origin)))
+ const results = await Promise.all(
+ requests.map(async (request) => {
+ if (!sessionlessBatch) {
+ return this.dispatch(request, props, state, getPublicUrl(req).origin, carriedContextHandle)
+ }
+ const itemProps = { ...props }
+ if (request.method === Method.ToolsCall) {
+ itemProps.mcpConversationId = echoedConversationId(request) ?? props.mcpConversationId
+ }
+ let itemState: ResolvedState | undefined
+ try {
+ itemState = TRACKED_METHODS.has(request.method)
+ ? await this.stateResolver.resolve(itemProps, lookups)
+ : undefined
+ } catch (error) {
+ if (mapErrorToAuthResponse(error)) {
+ throw error
+ }
+ console.error('[McpDispatcher] Internal error:', error)
+ return jsonRpcMethodError(request.id, ErrorCode.InternalError, 'Internal error')
+ }
+ return this.dispatch(
+ request,
+ itemProps,
+ itemState,
+ getPublicUrl(req).origin,
+ Boolean(itemProps.mcpSessionId || itemProps.mcpConversationId)
+ )
+ })
+ )
return new Response(JSON.stringify(results), { status: 200, headers })
}
@@ -338,6 +385,7 @@ class McpDispatcher {
props: RequestProperties,
state: ResolvedState | undefined,
requestOrigin: string,
+ carriedContextHandle: boolean,
onLegacyElicitation?: (request: JSONRPCRequest) => void
): Promise<JsonRpcResponse> {
const { id, method, params } = request
@@ -356,6 +404,7 @@ class McpDispatcher {
stateless,
id,
requestOrigin,
+ carriedContextHandle,
onLegacyElicitation
)
if (result === METHOD_NOT_FOUND) {
@@ -380,6 +429,7 @@ class McpDispatcher {
stateless: boolean,
requestId: string | number,
requestOrigin: string,
+ carriedContextHandle: boolean,
onLegacyElicitation?: (request: JSONRPCRequest) => void
): Promise<unknown> {
// SEP-2575 removed `initialize` and `ping` from the modern dialect.
@@ -399,6 +449,11 @@ class McpDispatcher {
state!,
params
? {
+ carriedContextHandle,
+ resolveConversation: (conversationId) => {
+ props.mcpConversationId = conversationId
+ return this.stateResolver.resolve(props, state!.reqCtx.lookups)
+ },
beforeExecute: (callState) =>
this.interviewRecruitment.beforeToolCall(
params,
diff --git a/services/mcp/src/hono/mcp-context.ts b/services/mcp/src/hono/mcp-context.ts
index f91f0bc34329..bf4c3617f158 100644
--- a/services/mcp/src/hono/mcp-context.ts
+++ b/services/mcp/src/hono/mcp-context.ts
@@ -64,9 +64,8 @@ export function buildMCPRequestContext(props: RequestProperties): MCPRequestCont
/**
* The id a request carries to group its events by, most specific first. MCP 2026-07-28
* removed `initialize` and the `Mcp-Session-Id` header, so for those clients only the
- * agent's handle is ever present. One definition because two callers must agree on the
- * order: `getEffectiveSessionUuid` turns this into `$session_id`, and the executor hands
- * the same value to the SDK, which mints a handle only when nothing was carried.
+ * agent's handle is ever present. `getEffectiveSessionUuid` turns this into `$session_id`.
+ * Wrapper-only hints group analytics but do not replace conversation handles for context switches.
*/
export function resolveSessionKey(requestContext: MCPRequestContext): string | undefined {
return requestContext.mcpConversationId ?? requestContext.sessionId ?? requestContext.mcpSessionId
diff --git a/services/mcp/src/hono/request-context.ts b/services/mcp/src/hono/request-context.ts
index a0194e38bb24..189d998453f9 100644
--- a/services/mcp/src/hono/request-context.ts
+++ b/services/mcp/src/hono/request-context.ts
@@ -1,8 +1,8 @@
import { createHash } from 'node:crypto'
import { ApiClient } from '@/api/client'
+import { StateLookupCache } from '@/lib/cache/StateLookupCache'
import { MCP_ANALYTICS_SOURCE, MCP_SERVER_NAME, MCP_SERVER_VERSION } from '@/lib/constants'
-import { wrapError } from '@/lib/errors'
import { getPostHogClient } from '@/lib/posthog'
import {
AnalyticsEvent,
@@ -37,6 +37,7 @@ export class RequestContext {
private legacySessionScopedCacheInstance: RedisCache<SessionScopedState> | undefined
private apiInstance: ApiClient | undefined
private sessionManagerInstance: SessionManager | undefined
+ private stateManagerInstance: StateManager | undefined
private distinctIdPromise: Promise<string> | undefined
private readonly sessionUuidPromises = new Map<string, Promise<string>>()
private readonly redis: RedisLike
@@ -50,7 +51,8 @@ export class RequestContext {
redis: RedisLike,
env: Env,
props: RequestProperties,
- requestContext: MCPRequestContext = buildMCPRequestContext(props)
+ requestContext: MCPRequestContext = buildMCPRequestContext(props),
+ readonly lookups = new StateLookupCache()
) {
this.redis = redis
this.env = env
@@ -73,21 +75,18 @@ export class RequestContext {
}
/**
- * 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.
- *
- * The key includes the credential: a caller chooses its session id, so a
- * request must never restore context that another credential saved.
+ * Selections cannot live in the token cache shared by concurrent connections.
+ * Include the credential because callers choose their session and conversation IDs.
*/
get sessionScopedCache(): RedisCache<SessionScopedState> | undefined {
const mcpSessionId = this.requestContext.mcpSessionId
- if (!mcpSessionId) {
+ const conversationId = this.requestContext.mcpConversationId
+ if (!mcpSessionId && !conversationId) {
return undefined
}
if (!this.sessionScopedCacheInstance) {
- this.sessionScopedCacheInstance = this.sessionCacheFor(`${this.props.userHash ?? ''}\0${mcpSessionId}`)
+ const scopeId = mcpSessionId ?? `conversation\0${conversationId}`
+ this.sessionScopedCacheInstance = this.sessionCacheFor(`${this.props.userHash ?? ''}\0${scopeId}`)
}
return this.sessionScopedCacheInstance
}
@@ -207,30 +206,18 @@ export class RequestContext {
}
getDistinctId(): Promise<string> {
- if (!this.distinctIdPromise) {
- this.distinctIdPromise = this.resolveDistinctId()
- }
- return this.distinctIdPromise
- }
-
- private async resolveDistinctId(): Promise<string> {
- const cached = await this.tokenCache.get('distinctId')
- if (cached) {
- return cached
- }
- const userResult = await (await this.api()).users().me()
- if (!userResult.success) {
- throw wrapError(`Failed to get user: ${userResult.error.message}`, userResult.error)
- }
- const distinctId = userResult.data.distinct_id as string
- await this.tokenCache.set('distinctId', distinctId)
- return distinctId
+ return (this.distinctIdPromise ??= this.getContext().then(({ stateManager }) => stateManager.getDistinctId()))
}
async getContext(): Promise<Context> {
const api = await this.api()
- const stateManager = new StateManager(this.tokenCache, api, this.pinnedContext)
- const sessionScopedCache = this.sessionScopedCache
+ const stateManager = (this.stateManagerInstance ??= new StateManager(
+ this.tokenCache,
+ api,
+ this.pinnedContext,
+ this.sessionScopedCache,
+ this.lookups
+ ))
const partialContext: Omit<Context, 'trackEvent'> = {
api,
cache: this.tokenCache,
@@ -238,16 +225,6 @@ 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 866a977e5fe1..0a593fc25c21 100644
--- a/services/mcp/src/hono/request-state-resolver.ts
+++ b/services/mcp/src/hono/request-state-resolver.ts
@@ -1,3 +1,4 @@
+import type { StateLookupCache } from '@/lib/cache/StateLookupCache'
import { MCPClientProfile } from '@/lib/client-detection'
import { isCloudApi, isLocalApi, MCP_GATEWAY_FLAG } from '@/lib/constants'
import { env } from '@/lib/env'
@@ -161,9 +162,9 @@ export class RequestStateResolver {
this.env = env
}
- async resolve(props: RequestProperties): Promise<ResolvedState> {
+ async resolve(props: RequestProperties, lookups?: StateLookupCache): Promise<ResolvedState> {
const requestContext = buildMCPRequestContext(props)
- const reqCtx = new RequestContext(this.redis, this.env, props, requestContext)
+ const reqCtx = new RequestContext(this.redis, this.env, props, requestContext, lookups)
const { features, tools, organizationId, projectId, readOnly } = props
const pinned = await this.resolvePinnedContext(reqCtx, { organizationId, projectId })
@@ -176,7 +177,10 @@ export class RequestStateResolver {
this.resolveSessionContext(requestContext),
pinned ? undefined : reqCtx.tokenCache.get('projectId'),
])
- if (!pinned && !storedProjectId) {
+ const needsDefaultContext = pinned
+ ? pinned.sessionScoped && !pinned.orgId && !pinned.projectId
+ : !storedProjectId
+ if (needsDefaultContext) {
await context.stateManager.setDefaultOrganizationAndProject()
}
const clientContext = getEffectiveMCPClientContext(requestContext, sessionContext)
@@ -362,30 +366,9 @@ export class RequestStateResolver {
}
/**
- * 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 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.
- *
- * 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.
+ * Capture the session selection once per request so another connection's
+ * switches cannot redirect an in-flight call. A resent pin preserves switches;
+ * a changed pin replaces the whole selection. Clients may send pins only on initialize.
*/
private async resolvePinnedContext(
reqCtx: RequestContext,
@@ -400,12 +383,13 @@ export class RequestStateResolver {
}
const legacyCache = reqCtx.legacySessionScopedCache
- const [appliedPinOrg, appliedPinProject, activeOrg, activeProject, legacyPinOrg, legacyPinProject] =
+ const [appliedPinOrg, appliedPinProject, activeOrg, activeProject, defaults, legacyPinOrg, legacyPinProject] =
await Promise.all([
sessionCache.get('appliedPinOrgId'),
sessionCache.get('appliedPinProjectId'),
sessionCache.get('activeOrgId'),
sessionCache.get('activeProjectId'),
+ sessionCache.get('defaultContext'),
legacyCache?.get('appliedPinOrgId'),
legacyCache?.get('appliedPinProjectId'),
])
@@ -413,28 +397,39 @@ export class RequestStateResolver {
// 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)
+ const hasSessionState = Boolean(appliedPinOrg || appliedPinProject || activeOrg || activeProject || defaults)
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
// 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'])
+ await sessionCache.refreshTtl([
+ 'appliedPinOrgId',
+ 'appliedPinProjectId',
+ 'activeOrgId',
+ 'activeProjectId',
+ 'defaultContext',
+ 'defaultProjectId',
+ ])
// An omitted pin is not a changed pin: keep the session's saved context.
if (!hasPin) {
+ const useDefaults =
+ activeOrg === undefined && activeProject === undefined && !appliedPinOrg && !appliedPinProject
return {
pin: { organizationId: appliedPinOrg, projectId: appliedPinProject },
sessionScoped: true,
- orgId: activeOrg ?? appliedPinOrg,
- projectId: activeProject ?? appliedPinProject,
+ orgId:
+ activeOrg !== undefined
+ ? (activeOrg ?? undefined)
+ : (appliedPinOrg ?? (useDefaults ? defaults?.organizationId : undefined)),
+ projectId:
+ activeProject !== undefined
+ ? (activeProject ?? undefined)
+ : (appliedPinProject ?? (useDefaults ? defaults?.projectId?.toString() : undefined)),
}
}
@@ -460,8 +455,8 @@ export class RequestStateResolver {
return {
pin,
sessionScoped: true,
- orgId: overrideOrg ?? organizationId,
- projectId: overrideProject ?? projectId,
+ orgId: overrideOrg !== undefined ? (overrideOrg ?? undefined) : organizationId,
+ projectId: overrideProject !== undefined ? (overrideProject ?? undefined) : projectId,
}
}
@@ -495,7 +490,15 @@ export class RequestStateResolver {
}
try {
const distinctId = await reqCtx.getDistinctId()
- return await evaluateFeatureFlags(flagKeys, distinctId, groups)
+ const key = JSON.stringify([
+ 'featureFlags',
+ distinctId,
+ Object.entries(groups ?? {}).sort(([a], [b]) => a.localeCompare(b)),
+ [...flagKeys].sort(),
+ ])
+ return await reqCtx.lookups.get(reqCtx.tokenCache.scope, key, () =>
+ evaluateFeatureFlags(flagKeys, distinctId, groups)
+ )
} catch {
return { flags: {}, payloads: {} }
}
diff --git a/services/mcp/src/hono/tool-executor.ts b/services/mcp/src/hono/tool-executor.ts
index 05580274e098..84e4f584b6de 100644
--- a/services/mcp/src/hono/tool-executor.ts
+++ b/services/mcp/src/hono/tool-executor.ts
@@ -146,6 +146,8 @@ function stateForToolCall(state: ResolvedState, intent: string | undefined): Res
// Hooks run after SDK preparation to share its conversation handle and preserve per-call privacy suppression.
export interface ToolCallHooks {
+ carriedContextHandle?: boolean
+ resolveConversation?(conversationId: string): Promise<ResolvedState>
beforeExecute(state: ResolvedState): Promise<Record<string, unknown> | undefined>
afterExecute(state: ResolvedState, result: unknown): Promise<void>
}
@@ -236,6 +238,9 @@ export class ToolExecutor {
rawRequestMeta && typeof rawRequestMeta === 'object' && !Array.isArray(rawRequestMeta)
? (rawRequestMeta as Record<string, unknown>)
: undefined
+ const carriedContextHandle =
+ hooks?.carriedContextHandle ??
+ Boolean(state.requestContext.mcpSessionId || state.requestContext.mcpConversationId)
const { analyticsMeta, args, preparedCall } = this.extractAnalyticsMetadata(
toolName,
rawArgs,
@@ -243,16 +248,42 @@ export class ToolExecutor {
requestMeta,
state.requestContext
)
- // In place, not copied: `RequestStateResolver` gives this one object to both the state
- // and `RequestContext`, so events emitted through `RequestContext.trackEvent` resolve the
- // same session. A batch never reaches here holding a handle, because the dispatcher
- // refuses a batch containing a modern message and a legacy client carries a session.
+ // RequestContext shares this object so analytics follows the SDK's conversation handle.
if (preparedCall?.conversationId) {
+ const previousConversationId = state.requestContext.mcpConversationId
state.requestContext.mcpConversationId = preparedCall.conversationId
+ if (
+ !state.requestContext.mcpSessionId &&
+ preparedCall.conversationId !== previousConversationId &&
+ hooks?.resolveConversation
+ ) {
+ // Bind the new handle before execution so this call and its retry share defaults.
+ state = await hooks.resolveConversation(preparedCall.conversationId)
+ }
}
const callState = stateForToolCall(state, analyticsMeta.intent)
const callParams = { ...params, arguments: args }
+ const targetToolName =
+ toolName === 'exec' && typeof args.command === 'string'
+ ? parseExecCallInnerToolName(args.command)
+ : toolName
+ const isContextSwitch = targetToolName === 'switch-project' || targetToolName === 'switch-organization'
+ if (isContextSwitch && !carriedContextHandle) {
+ return this.deliverConversationHandle(
+ {
+ isError: true,
+ content: [
+ {
+ type: 'text',
+ text: 'Switch not applied. Retry with the returned `conversation_id` and include it on subsequent calls. If your client cannot retain it, pin the project or organization in the connection URL.',
+ },
+ ],
+ },
+ preparedCall
+ )
+ }
+
const invitation = await hooks?.beforeExecute(callState)
if (invitation) {
return invitation
@@ -356,12 +387,12 @@ export class ToolExecutor {
preparedCall: PreparedToolCall | undefined
} {
try {
+ const carriesContext = Boolean(requestContext.mcpSessionId || requestContext.mcpConversationId)
const prepared = getPostHogClient().prepareToolCall(toolName, rawArgs, {
originalTool,
requestMeta,
- // The SDK mints a handle only when nothing was carried, so a client that already
- // has a session keeps it and never sees the prompt-back.
- sessionId: resolveSessionKey(requestContext),
+ // Wrapper-only analytics hints cannot restore selections, so they must not suppress minting.
+ sessionId: carriesContext ? resolveSessionKey(requestContext) : undefined,
})
return {
analyticsMeta: {
diff --git a/services/mcp/src/lib/StateManager.ts b/services/mcp/src/lib/StateManager.ts
index 22faf4a759af..318803164a35 100644
--- a/services/mcp/src/lib/StateManager.ts
+++ b/services/mcp/src/lib/StateManager.ts
@@ -3,6 +3,7 @@ import type { Schemas } from '@/api/generated'
import { hasScope } from '@/lib/api'
import { classifyAuthMethod } from '@/lib/auth-method'
import type { ScopedCache } from '@/lib/cache/ScopedCache'
+import { StateLookupCache } from '@/lib/cache/StateLookupCache'
import {
ErrorCode,
MissingOrganizationContextError,
@@ -13,7 +14,14 @@ import {
import { getPostHogClient } from '@/lib/posthog'
import { sanitizeHeaderValue } from '@/lib/utils'
import type { ApiUser } from '@/schema/api'
-import type { CachedOrg, CachedProject, CachedUser, PinnedActiveContext, State } from '@/tools/types'
+import type {
+ CachedOrg,
+ CachedProject,
+ CachedUser,
+ PinnedActiveContext,
+ SessionScopedState,
+ 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
@@ -39,27 +47,23 @@ type OrgEntitlementFields = {
}
export class StateManager {
- private _cache: ScopedCache<State>
- private _api: ApiClient
- private _user?: ApiUser
- 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
- }
+
+ constructor(
+ private readonly _cache: ScopedCache<State>,
+ private readonly _api: ApiClient,
+ private readonly _pinned?: PinnedActiveContext,
+ private readonly _sessionCache?: ScopedCache<SessionScopedState>,
+ private readonly lookups = new StateLookupCache()
+ ) {}
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.
+ * Session selections never enter the token cache because other sessions on
+ * the credential share it. Sessionless pins persist only the keys they leave open.
*/
async setActiveContext(updates: { orgId?: string; projectId?: string }): Promise<void> {
const pinned = this._pinned
@@ -71,13 +75,21 @@ export class StateManager {
return
}
if (updates.orgId) {
+ if (updates.orgId !== pinned.orgId && !updates.projectId) {
+ pinned.projectId = undefined
+ }
pinned.orgId = updates.orgId
}
if (updates.projectId) {
pinned.projectId = updates.projectId
}
this._pinnedOrgProject = undefined
- if (!pinned.sessionScoped) {
+ if (pinned.sessionScoped) {
+ await this._sessionCache?.setMany({
+ activeOrgId: pinned.orgId ?? null,
+ activeProjectId: pinned.projectId ?? null,
+ })
+ } else {
await this._cache.setMany({
...(updates.orgId && !pinned.pin.organizationId && !pinned.pin.projectId
? { orgId: updates.orgId }
@@ -96,11 +108,7 @@ export class StateManager {
}
async getUser(): Promise<ApiUser> {
- if (!this._user) {
- this._user = await this._fetchUser()
- }
-
- return this._user
+ return this.lookups.get(this._cache.scope, 'user', () => this._fetchUser())
}
private async _fetchApiKey(): Promise<NonNullable<State['apiKey']>> {
@@ -150,10 +158,6 @@ export class StateManager {
const sanitizedClientName = sanitizeHeaderValue(client_name)
if (sanitizedClientName) {
await this._cache.set('clientName', sanitizedClientName)
- // Introspection is the first point the OAuth app name is known, and the client was
- // already built for this request — stamp it on so the rest of the request forwards
- // `x-posthog-mcp-oauth-client-name` instead of waiting for the next cache hit.
- this._api.config.oauthClientName = sanitizedClientName
}
return {
@@ -172,7 +176,7 @@ export class StateManager {
}
}
- async getApiKey(): Promise<NonNullable<State['apiKey']>> {
+ private async _getApiKey(): Promise<NonNullable<State['apiKey']>> {
// An OAuth token gets a new value, and so a new cache entry, whenever its scopes change.
const refreshable = classifyAuthMethod(this._api.config.apiToken) !== 'oauth'
const [cached, fetchedAt] = await Promise.all([
@@ -185,7 +189,9 @@ export class StateManager {
}
try {
- const apiKey = await this._fetchApiKey()
+ const apiKey = await this.lookups.get(this._cache.scope, JSON.stringify(['apiKey', fetchedAt]), () =>
+ this._fetchApiKey()
+ )
await Promise.all([
this._cache.set('apiKey', apiKey),
refreshable ? this._cache.set('apiKeyFetchedAt', Date.now()) : undefined,
@@ -203,6 +209,15 @@ export class StateManager {
}
}
+ async getApiKey(): Promise<NonNullable<State['apiKey']>> {
+ const apiKey = await this._getApiKey()
+ const clientName = await this._cache.get('clientName')
+ if (clientName) {
+ this._api.config.oauthClientName = sanitizeHeaderValue(clientName)
+ }
+ return apiKey
+ }
+
async getDistinctId(): Promise<NonNullable<State['distinctId']>> {
let _distinctId = await this._cache.get('distinctId')
@@ -216,20 +231,37 @@ export class StateManager {
return _distinctId
}
- /**
- * Resolve a default `(organizationId, projectId)` for a session that hasn't
- * pinned them via header. The user's currently active team/org from
- * `users/@me` is the source of truth; the API key's `scoped_teams` /
- * `scoped_organizations` are treated as filters, not directives.
- *
- * Never throws. The agent can always recover via `switch-project` /
- * `switch-organization` tools, so an opaque 500 here would be strictly
- * worse than a best-effort default.
- */
- private async _getDefaultOrganizationAndProject(): Promise<{
- organizationId?: string
- projectId?: number
- }> {
+ private async _getDefaultOrganizationAndProject(): Promise<NonNullable<SessionScopedState['defaultContext']>> {
+ const sessionCache = this._pinned?.sessionScoped ? this._sessionCache : undefined
+ if (!sessionCache) {
+ return this._fetchDefaultOrganizationAndProject()
+ }
+ const saved = await sessionCache.get('defaultContext')
+ if (saved) {
+ if (saved.projectId !== undefined || !saved.organizationId) {
+ return saved
+ }
+ const cachedProjectId = await sessionCache.get('defaultProjectId')
+ if (cachedProjectId !== undefined) {
+ return { ...saved, projectId: cachedProjectId }
+ }
+ const projectId = await this._fetchDefaultProjectInOrganization(saved.organizationId)
+ if (projectId !== undefined) {
+ await sessionCache.setIfAbsent('defaultProjectId', projectId)
+ }
+ return { ...saved, projectId: await sessionCache.get('defaultProjectId') }
+ }
+ const defaults = await this._fetchDefaultOrganizationAndProject()
+ if (!defaults.organizationId && defaults.projectId === undefined) {
+ return defaults
+ }
+ if (await sessionCache.setIfAbsent('defaultContext', defaults)) {
+ return defaults
+ }
+ return (await sessionCache.get('defaultContext')) ?? defaults
+ }
+
+ private async _fetchDefaultOrganizationAndProject(): Promise<NonNullable<SessionScopedState['defaultContext']>> {
const [{ scoped_organizations, scoped_teams }, user] = await Promise.all([this.getApiKey(), this.getUser()])
const { organization: activeOrganization, team: activeTeam } = user
@@ -267,37 +299,36 @@ export class StateManager {
if (!organizationId) {
return {}
}
+ return { organizationId, projectId: await this._fetchDefaultProjectInOrganization(organizationId) }
+ }
+
+ private async _fetchDefaultProjectInOrganization(organizationId: string): Promise<number | undefined> {
try {
- const projectsResult = await this._api.organizations().projects({ orgId: organizationId }).list()
- if (projectsResult.success && projectsResult.data.length > 0) {
- return { organizationId, projectId: Number(projectsResult.data[0]!.id) }
- }
- if (!projectsResult.success) {
- // A 404 here means the API key/OAuth token points at an org the
- // requesting user can no longer access (or a deleted org): the
- // org-nested projects endpoint is scoped to the user's
- // memberships. That's a recoverable user-config state — the
- // agent recovers via switch-project/switch-organization — so
- // warn instead of capturing, mirroring the 403 permission_denied
- // path in client.ts. Only genuine 5xx/unexpected failures reach
- // error tracking.
- if (this._isRecoverableNotFound(projectsResult.error)) {
- console.warn(
- `[StateManager] Scoped org ${organizationId} projects lookup returned 404 (org not accessible to this user or deleted); falling back to org-only context`
- )
- } else {
- await this._reportException(projectsResult.error, 'default_org_project_projects_list_failed', {
- organization_id: organizationId,
- })
+ const projects = await this.lookups.get<Schemas.ProjectBackwardCompat[]>(
+ this._cache.scope,
+ `organizationProjects:${organizationId}`,
+ async () => {
+ const result = await this._api.organizations().projects({ orgId: organizationId }).list()
+ if (!result.success) {
+ throw result.error
+ }
+ return result.data
}
- }
+ )
+ return projects.length > 0 ? Number(projects[0]!.id) : undefined
} catch (error) {
- await this._reportException(error, 'default_org_project_projects_list_threw', {
- organization_id: organizationId,
- })
+ if (this._isRecoverableNotFound(error)) {
+ console.warn(
+ `[StateManager] Scoped org ${organizationId} projects lookup returned 404 (org not accessible to this user or deleted); falling back to org-only context`
+ )
+ } else {
+ await this._reportException(error, 'default_org_project_projects_list_failed', {
+ organization_id: organizationId,
+ })
+ }
}
- return { organizationId }
+ return undefined
}
/**
@@ -335,12 +366,11 @@ export class StateManager {
}> {
const { organizationId, projectId } = await this._getDefaultOrganizationAndProject()
- if (organizationId) {
- await this._cache.set('orgId', organizationId)
- }
-
- if (projectId !== undefined) {
- await this._cache.set('projectId', projectId.toString())
+ if (this._pinned?.sessionScoped) {
+ this._pinned.orgId = organizationId
+ this._pinned.projectId = projectId?.toString()
+ } else {
+ await this.setActiveContext({ orgId: organizationId, projectId: projectId?.toString() })
}
return { organizationId, projectId }
@@ -370,6 +400,9 @@ export class StateManager {
pinned.orgId = project?.organization ?? undefined
return pinned.orgId
}
+ if (pinned) {
+ return undefined
+ }
const cached = await this._cache.get('orgId')
if (cached) {
@@ -421,11 +454,9 @@ export class StateManager {
}
/**
- * 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.
+ * An organization selection can outlive its project, so accept a default only
+ * when its lookup proves that it belongs to the selected org. Sessionless
+ * requests also consider the token selection for compatibility.
*/
private async _resolvePinnedOrgProjectId(pinned: PinnedActiveContext): Promise<string> {
const orgId = pinned.orgId
@@ -437,14 +468,24 @@ export class StateManager {
return project?.organization === orgId
}
- const cachedCandidate = await this._cache.get('projectId')
+ const cachedCandidate = pinned.sessionScoped ? undefined : await this._cache.get('projectId')
if (await belongsToOrg(cachedCandidate)) {
return cachedCandidate!
}
- const { projectId } = await this._getDefaultOrganizationAndProject().catch(() => ({ projectId: undefined }))
+ const { organizationId, projectId } = await this._getDefaultOrganizationAndProject().catch(() => ({
+ organizationId: undefined,
+ projectId: undefined,
+ }))
const defaultCandidate = projectId?.toString()
- if (defaultCandidate !== cachedCandidate && (await belongsToOrg(defaultCandidate))) {
- return defaultCandidate!
+ if (
+ defaultCandidate &&
+ defaultCandidate !== cachedCandidate &&
+ ((organizationId !== undefined && organizationId === orgId) || (await belongsToOrg(defaultCandidate)))
+ ) {
+ if (pinned.sessionScoped) {
+ pinned.projectId = defaultCandidate
+ }
+ return defaultCandidate
}
throw new MissingProjectContextError({ organizationId: orgId })
}
@@ -477,7 +518,11 @@ export class StateManager {
}
try {
- const data = await opts.fetcher()
+ const data = await this.lookups.get(
+ this._cache.scope,
+ JSON.stringify([opts.cacheKey, fetchedAt]),
+ opts.fetcher
+ )
await Promise.all([
this._cache.set(opts.cacheKey, data as State[D]),
this._cache.set(opts.fetchedAtKey, Date.now() as State[F]),
diff --git a/services/mcp/src/lib/cache/MemoryCache.ts b/services/mcp/src/lib/cache/MemoryCache.ts
index 21f42a674cb6..6faf2dc23ade 100644
--- a/services/mcp/src/lib/cache/MemoryCache.ts
+++ b/services/mcp/src/lib/cache/MemoryCache.ts
@@ -24,6 +24,14 @@ export class MemoryCache<T extends Record<string, any>> extends ScopedCache<T> {
this.cache.delete(key as string)
}
+ async setIfAbsent<K extends keyof T>(key: K, value: T[K]): Promise<boolean> {
+ if (this.cache.has(key as string)) {
+ return false
+ }
+ this.cache.set(key as string, value)
+ return true
+ }
+
async clear(): Promise<void> {
this.cache.clear()
}
diff --git a/services/mcp/src/lib/cache/ScopedCache.ts b/services/mcp/src/lib/cache/ScopedCache.ts
index 6185216553b0..749b03b8923a 100644
--- a/services/mcp/src/lib/cache/ScopedCache.ts
+++ b/services/mcp/src/lib/cache/ScopedCache.ts
@@ -1,8 +1,9 @@
export abstract class ScopedCache<T extends Record<string, any>> {
- constructor(protected scope: string) {}
+ constructor(readonly scope: string) {}
abstract get<K extends keyof T>(key: K): Promise<T[K] | undefined>
abstract set<K extends keyof T>(key: K, value: T[K]): Promise<void>
+ abstract setIfAbsent<K extends keyof T>(key: K, value: T[K]): Promise<boolean>
abstract delete<K extends keyof T>(key: K): Promise<void>
abstract clear(): Promise<void>
diff --git a/services/mcp/src/lib/cache/StateLookupCache.ts b/services/mcp/src/lib/cache/StateLookupCache.ts
new file mode 100644
index 000000000000..cbdb4b2aa701
--- /dev/null
+++ b/services/mcp/src/lib/cache/StateLookupCache.ts
@@ -0,0 +1,18 @@
+/** Read snapshots for one inbound request; never reuse across requests. */
+export class StateLookupCache {
+ private readonly promises = new Map<string, Promise<unknown>>()
+
+ get<T>(scope: string, key: string, load: () => Promise<T>): Promise<T> {
+ const scopedKey = JSON.stringify([scope, key])
+ const cached = this.promises.get(scopedKey)
+ if (cached) {
+ return cached as Promise<T>
+ }
+ const pending = load().catch((error: unknown) => {
+ this.promises.delete(scopedKey)
+ throw error
+ })
+ this.promises.set(scopedKey, pending)
+ return pending
+ }
+}
diff --git a/services/mcp/src/tools/organizations/setActive.ts b/services/mcp/src/tools/organizations/setActive.ts
index a834a300e751..e5559bb4f665 100644
--- a/services/mcp/src/tools/organizations/setActive.ts
+++ b/services/mcp/src/tools/organizations/setActive.ts
@@ -1,9 +1,10 @@
import type { z } from 'zod'
-import { PinnedContextSwitchError } from '@/lib/errors'
+import type { Schemas } from '@/api/generated'
+import { PinnedContextSwitchError, wrapError } from '@/lib/errors'
import { buildActiveEnvironmentContextPrompt } from '@/lib/instructions'
import { OrganizationSetActiveSchema } from '@/schema/tool-inputs'
-import type { CachedOrg, CachedProject, Context, ToolBase } from '@/tools/types'
+import type { CachedProject, Context, ToolBase } from '@/tools/types'
const schema = OrganizationSetActiveSchema
@@ -25,22 +26,26 @@ export const setActiveHandler: ToolBase<typeof schema, Result>['handler'] = asyn
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 })
-
- // Fetch fresh org data and cache it
- let org: CachedOrg | undefined
const orgResult = await context.api.organizations().get({ orgId })
- if (orgResult.success) {
- org = orgResult.data
- await context.cache.set(`cachedOrg:${orgId}` as const, org)
- await context.cache.set(`cachedOrgFetchedAt:${orgId}` as const, Date.now())
+ if (!orgResult.success) {
+ throw wrapError(
+ `Could not switch to organization ${orgId}: it was not found or you do not have access. ` +
+ 'Use `organizations-get` to list available organizations.',
+ orgResult.error
+ )
}
- // Read cached project for full metadata block
- const projectId = pinned?.projectId ?? (await context.cache.get('projectId')) ?? 'unknown'
+ const org: Schemas.Organization = orgResult.data
+ const selectedProjectId = pinned?.projectId
+ const keepProject = org.id === orgId && org.teams?.some((team) => String(team.id) === selectedProjectId)
+ await context.stateManager.setActiveContext({
+ orgId,
+ ...(keepProject ? { projectId: selectedProjectId } : {}),
+ })
+ await context.cache.set(`cachedOrg:${orgId}` as const, org)
+ await context.cache.set(`cachedOrgFetchedAt:${orgId}` as const, Date.now())
+
+ const projectId = (pinned ? 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 82b2345b41f9..f71546eacbf7 100644
--- a/services/mcp/src/tools/projects/setActive.ts
+++ b/services/mcp/src/tools/projects/setActive.ts
@@ -82,10 +82,6 @@ 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 the cached org, when we didn't just fetch it, for the metadata block
if (!org && orgId) {
org = (await context.cache.get(`cachedOrg:${orgId}` as const)) as CachedOrg | undefined
diff --git a/services/mcp/src/tools/types.ts b/services/mcp/src/tools/types.ts
index ee1bd77d63c2..33f7d5735c30 100644
--- a/services/mcp/src/tools/types.ts
+++ b/services/mcp/src/tools/types.ts
@@ -15,23 +15,20 @@ 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.resolvePinnedContext.
+// Null clears a selection without restoring the pin; undefined means no override was saved.
export type SessionScopedState = {
- activeProjectId: string | undefined
- activeOrgId: string | undefined
+ // Defaults are separate from explicit switches so delayed initialization cannot undo a switch.
+ defaultContext: { organizationId?: string; projectId?: number } | undefined
+ defaultProjectId: number | undefined
+ activeProjectId: string | null | undefined
+ activeOrgId: string | null | undefined
appliedPinProjectId: string | undefined
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.
+ * The resolver snapshots the session selection and optional pin per request.
+ * The token cache is shared across sessions, so it cannot hold their selections.
*/
export type PinnedActiveContext = {
/** The org and project ids that the request params, or the session's saved pin, pinned. */
@@ -44,7 +41,7 @@ export type PinnedActiveContext = {
}
export type CachedUser = ApiUser
-export type CachedOrg = Schemas.OrganizationBasic
+export type CachedOrg = Schemas.Organization
export type CachedProject = Schemas.ProjectBackwardCompat
export type State = {
@@ -146,13 +143,6 @@ 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.resolvePinnedContext). 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/pinned-context-switch.test.ts b/services/mcp/tests/hono/pinned-context-switch.test.ts
index 05becb6a6aaa..76da246da854 100644
--- a/services/mcp/tests/hono/pinned-context-switch.test.ts
+++ b/services/mcp/tests/hono/pinned-context-switch.test.ts
@@ -1,10 +1,15 @@
-import { http, HttpResponse } from 'msw'
+import { http, HttpResponse, type DefaultBodyType, type StrictRequest } from 'msw'
import { setupServer } from 'msw/node'
import { createHash } from 'node:crypto'
-import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { createApp } from '@/hono/app'
import { RedisCache, type RedisLike } from '@/hono/cache/RedisCache'
+import { MCP_INTENT_PROMPT_FLAG } from '@/hono/intent-prompt'
+import { MCP_INTERVIEW_RECRUITMENT_FLAG } from '@/hono/interview-recruitment'
+import { RequestStateResolver } from '@/hono/request-state-resolver'
+import * as constants from '@/lib/constants'
+import { getPostHogClient } from '@/lib/posthog'
import { hash } from '@/lib/utils'
import type { SessionScopedState, State } from '@/tools/types'
@@ -18,8 +23,21 @@ const OTHER_ORG = '019d85ef-7e7d-0000-090c-000000000002'
const MISSING_PROJECT = '404'
const apiPaths: string[] = []
+const apiPathsByIntent = new Map<string, string[]>()
+
+function recordApiPath(request: StrictRequest<DefaultBodyType>): void {
+ const path = new URL(request.url).pathname
+ apiPaths.push(path)
+ const intent = request.headers.get('x-posthog-intent')
+ if (intent) {
+ const paths = apiPathsByIntent.get(intent) ?? []
+ paths.push(path)
+ apiPathsByIntent.set(intent, paths)
+ }
+}
const mswServer = setupServer(
+ http.get('*/api/projects/:projectId/integrations/', () => HttpResponse.json({ results: [] })),
http.get('*/api/projects/:projectId/', ({ params }) =>
params.projectId === MISSING_PROJECT
? HttpResponse.json({ detail: 'Not found.' }, { status: 404 })
@@ -31,11 +49,15 @@ const mswServer = setupServer(
})
),
http.post('*/api/environments/:projectId/mcp_tools/execute_sql/', ({ request }) => {
- apiPaths.push(new URL(request.url).pathname)
+ recordApiPath(request)
return HttpResponse.json({ success: true, content: 'ok' })
}),
+ http.post('*/api/projects/:projectId/feature_flags/', ({ request }) => {
+ recordApiPath(request)
+ return HttpResponse.json({ id: 123, key: 'batch-routing', active: true, filters: { groups: [] } })
+ }),
http.get('*/api/organizations/:orgId/billing/subscription/', ({ request }) => {
- apiPaths.push(new URL(request.url).pathname)
+ recordApiPath(request)
return HttpResponse.json({})
}),
...handlers,
@@ -49,12 +71,19 @@ function createInMemoryRedis(): RedisLike & {
const store = new Map<string, string>()
return {
get: async (key) => store.get(key) ?? null,
- set: async (key, value) => {
+ set: async (key, value, ...args) => {
+ if (args.includes('NX') && store.has(key)) {
+ return null
+ }
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[]],
+ scan: async (_cursor, ...args) => {
+ const match = args.indexOf('MATCH')
+ const prefix = match === -1 ? '' : String(args[match + 1]).replace(/\*$/, '')
+ return ['0', Array.from(store.keys()).filter((key) => key.startsWith(prefix))] as [string, string[]]
+ },
...makeRedisRateLimitStubs(store),
ping: async () => 'PONG',
}
@@ -77,11 +106,16 @@ afterAll(() => {
mswServer.close()
})
+afterEach(() => {
+ mswServer.resetHandlers()
+})
+
type CallOptions = {
// Each test uses its own token, so the shared token cache never carries state between tests.
token?: string
query?: string
sessionId?: string
+ conversationId?: string
}
function requestHeaders({ token = 'phx_default', sessionId }: CallOptions): Record<string, string> {
@@ -126,12 +160,17 @@ type ToolCallResponse = {
async function postToolCall(
name: string,
args: Record<string, unknown>,
- { query = `?project_id=${PINNED_PROJECT}`, ...options }: CallOptions = {}
+ { query = `?project_id=${PINNED_PROJECT}`, conversationId, ...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 } }),
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name, arguments: conversationId ? { ...args, conversation_id: conversationId } : args },
+ }),
})
const raw = await response.text()
const json = JSON.parse(raw.startsWith('{') ? raw : raw.slice(raw.indexOf('{'))) as Omit<ToolCallResponse, 'status'>
@@ -150,6 +189,18 @@ async function callTool(
return { isError: result.isError, text: result.content?.[0]?.text ?? '' }
}
+async function postBatch(
+ calls: Array<{ name: string; arguments: Record<string, unknown> }>,
+ options: CallOptions
+): Promise<Array<Omit<ToolCallResponse, 'status'>>> {
+ const response = await app.request(`/mcp${options.query ?? ''}`, {
+ method: 'POST',
+ headers: requestHeaders(options),
+ body: JSON.stringify(calls.map((params, id) => ({ jsonrpc: '2.0', id, method: 'tools/call', params }))),
+ })
+ return (await response.json()) as Array<Omit<ToolCallResponse, 'status'>>
+}
+
// 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
@@ -164,6 +215,14 @@ async function targets(options: CallOptions): Promise<{ project: string | null;
const tokenCache = (token: string): RedisCache<State> => new RedisCache<State>(hash(token), redis, 'token')
+const CONVERSATION_A = '0199c6f0-0000-7000-8000-00000000000a'
+const CONVERSATION_B = '0199c6f0-0000-7000-8000-00000000000b'
+
+function mintedConversationId(response: ToolCallResponse): string | undefined {
+ const prompt = response.result?.content?.find((item) => item.text?.startsWith('{"conversation_id"'))
+ return prompt ? (JSON.parse(prompt.text!) as { conversation_id: string }).conversation_id : undefined
+}
+
// 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')
@@ -187,13 +246,9 @@ 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))
+ await tokenCache(token).setMany({ projectId: OTHER_PROJECT, orgId: OTHER_ORG })
}
describe('pinned project with switch-project (Hono)', () => {
@@ -221,15 +276,6 @@ describe('pinned project with switch-project (Hono)', () => {
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}`],
@@ -240,14 +286,19 @@ describe('pinned project with switch-project (Hono)', () => {
const sessionId = await initialize({ token, query: pinQuery })
expect(await targets({ token, sessionId, query: '' })).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+ expect(
+ (await callTool('switch-project', { projectId: Number(OTHER_PROJECT) }, { token, sessionId, query: '' }))
+ .isError
+ ).toBeFalsy()
// 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,
+ project: PINNED_PROJECT,
+ org: PINNED_ORG,
})
+ expect(await targets({ token, 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 () => {
@@ -260,31 +311,491 @@ describe('pinned project with switch-project (Hono)', () => {
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) })
+ it.each([
+ ['unpinned conversation', ''],
+ ['pinned conversation', `?project_id=${PINNED_PROJECT}`],
+ ])('isolates each %s without changing credential defaults', async (label, query) => {
+ const token = `phx_${label.replaceAll(' ', '_')}`
+ const first = { token, query, conversationId: CONVERSATION_A }
+ const second = { token, query, conversationId: CONVERSATION_B }
+ expect((await callTool('switch-project', { projectId: Number(OTHER_PROJECT) }, first)).isError).toBeFalsy()
+ expect((await callTool('switch-project', { projectId: Number(PINNED_PROJECT) }, second)).isError).toBeFalsy()
+
+ expect(await targets(first)).toEqual({ project: OTHER_PROJECT, org: OTHER_ORG })
+ expect(await targets(second)).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+ expect(await tokenCache(token).get('projectId')).toBeUndefined()
+ })
- 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.each(
+ [
+ {
+ tool: 'switch-project',
+ args: { projectId: Number(OTHER_PROJECT) },
+ expected: { project: OTHER_PROJECT, org: OTHER_ORG },
+ },
+ {
+ tool: 'switch-organization',
+ args: { orgId: OTHER_ORG },
+ expected: { project: null, org: OTHER_ORG },
+ },
+ ].flatMap((testCase) =>
+ ['', `?project_id=${PINNED_PROJECT}`, '?sessionId=wrapper-context'].flatMap((query) =>
+ ['direct', 'exec'].map((mode) => ({ ...testCase, query, mode }))
+ )
+ )
+ )(
+ 'requires a carried handle before $mode $tool with pin "$query"',
+ async ({ tool, args, expected, query, mode }) => {
+ const token = `phx_require_handle_${tool}_${mode}_${query}`
+ const toolName = mode === 'exec' ? 'exec' : tool
+ const toolArgs = mode === 'exec' ? { command: `call ${tool} ${JSON.stringify(args)}` } : args
+ const first = await postToolCall(toolName, toolArgs, { token, query })
+ expect(first.result?.isError).toBe(true)
+ expect(first.result?.content?.[0]?.text).toContain('Retry with the returned `conversation_id`')
+ const conversationId = mintedConversationId(first)
+ expect(conversationId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7/)
+ const defaults = { project: PINNED_PROJECT, org: PINNED_ORG }
+ expect(await targets({ token, query, conversationId })).toEqual(defaults)
+ expect(await targets({ token, query })).toEqual(defaults)
+
+ const retry = await postToolCall(toolName, toolArgs, { token, query, conversationId })
+ expect(retry.result?.isError).toBeFalsy()
+ expect(await targets({ token, query, conversationId })).toEqual(expected)
+ expect(await targets({ token, query })).toEqual(defaults)
+ }
+ )
+
+ it.each([undefined, 'conv-1'])(
+ 'rejects batch handles %s and accepts retries with minted handles',
+ async (supplied) => {
+ const token = `phx_batch_requires_handle_${supplied}`
+ const calls = [
+ { name: 'switch-project', arguments: { projectId: Number(OTHER_PROJECT) } },
+ { name: 'switch-organization', arguments: { orgId: OTHER_ORG } },
+ ]
+ const results = await postBatch(
+ calls.map((call) => ({ ...call, arguments: { ...call.arguments, conversation_id: supplied } })),
+ { token }
+ )
+ expect(results.map(({ result }) => result?.isError)).toEqual([true, true])
+ const handles = results.map((result) => mintedConversationId({ status: 200, ...result }))
+ expect(handles).toEqual([
+ expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-7/),
+ expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-7/),
+ ])
+ expect(new Set(handles).size).toBe(2)
+ expect(await targets({ token, query: '' })).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+
+ const retries = await postBatch(
+ calls.map((call, index) => ({
+ ...call,
+ arguments: { ...call.arguments, conversation_id: handles[index] },
+ })),
+ { token }
+ )
+ expect(retries.map(({ result }) => Boolean(result?.isError))).toEqual([false, false])
+ expect(await targets({ token, query: '', conversationId: handles[0] })).toEqual({
+ project: OTHER_PROJECT,
+ org: OTHER_ORG,
+ })
+ expect(await targets({ token, query: '', conversationId: handles[1] })).toEqual({
+ project: null,
+ org: OTHER_ORG,
+ })
+ expect(await targets({ token, query: '' })).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+ }
+ )
+
+ it.each(['direct', 'exec'])('validates each handle independently in a mixed %s batch', async (mode) => {
+ const token = `phx_mixed_batch_${mode}`
+ const results = await postBatch(
+ [CONVERSATION_A, 'conv-1'].map((conversation_id) => ({
+ name: mode === 'exec' ? 'exec' : 'switch-project',
+ arguments: {
+ ...(mode === 'exec'
+ ? { command: `call switch-project {"projectId":${OTHER_PROJECT}}` }
+ : { projectId: Number(OTHER_PROJECT) }),
+ conversation_id,
+ },
+ })),
+ { token }
+ )
+ expect(results.map(({ result }) => Boolean(result?.isError))).toEqual([false, true])
+ expect(await targets({ token, query: '', conversationId: CONVERSATION_A })).toEqual({
+ project: OTHER_PROJECT,
+ org: OTHER_ORG,
+ })
+ })
+
+ it.each(
+ [
+ {
+ operation: 'read',
+ name: 'execute-sql',
+ args: { query: 'SELECT 1' },
+ route: (project: string) => `/api/environments/${project}/mcp_tools/execute_sql/`,
+ },
+ {
+ operation: 'write through exec',
+ name: 'exec',
+ args: { command: 'call create-feature-flag {"key":"batch-routing","filters":{"groups":[]}}' },
+ route: (project: string) => `/api/projects/${project}/feature_flags/`,
+ },
+ ].flatMap((operation) => [false, true].map((differentHandles) => ({ ...operation, differentHandles })))
+ )(
+ 'isolates batch $operation with different handles=$differentHandles',
+ async ({ name, args, route, operation, differentHandles }) => {
+ const token = `phx_batch_routing_${operation.replaceAll(' ', '_')}_${differentHandles}`
+ const conversations = [CONVERSATION_A, differentHandles ? CONVERSATION_B : CONVERSATION_A]
+ const projects = [OTHER_PROJECT, differentHandles ? '3' : OTHER_PROJECT]
+ for (const [conversationId, projectId] of new Map(
+ conversations.map((conversationId, index) => [conversationId, projects[index]!])
+ )) {
+ expect(
+ (
+ await callTool(
+ 'switch-project',
+ { projectId: Number(projectId) },
+ { token, query: '', conversationId }
+ )
+ ).isError
+ ).toBeFalsy()
+ }
+ apiPathsByIntent.clear()
+ const results = await postBatch(
+ conversations.map((conversation_id, index) => ({
+ name,
+ arguments: { ...args, conversation_id, context: `batch-item-${index}` },
+ })),
+ { token }
+ )
+ expect(results.map(({ result }) => Boolean(result?.isError))).toEqual([false, false])
+ expect(projects.map((_, index) => apiPathsByIntent.get(`batch-item-${index}`))).toEqual(
+ projects.map((project) => [route(project)])
+ )
+ }
+ )
+
+ it('returns an individual error when one batch context lookup fails', async () => {
+ const originalResolve = RequestStateResolver.prototype.resolve
+ const resolve = vi
+ .spyOn(RequestStateResolver.prototype, 'resolve')
+ .mockImplementation(function (this: RequestStateResolver, props) {
+ return props.mcpConversationId === CONVERSATION_A
+ ? Promise.reject(new Error('Synthetic batch context failure'))
+ : originalResolve.call(this, props)
+ })
+ apiPaths.length = 0
+ try {
+ const results = await postBatch(
+ [CONVERSATION_A, CONVERSATION_B].map((conversation_id) => ({
+ name: 'execute-sql',
+ arguments: { query: 'SELECT 1', conversation_id },
+ })),
+ { token: 'phx_batch_context_failure' }
+ )
+ expect({
+ responses: results.map(({ error, result }) => error?.code ?? Boolean(result?.isError)),
+ paths: apiPaths,
+ }).toEqual({
+ responses: [-32603, false],
+ paths: [`/api/environments/${PINNED_PROJECT}/mcp_tools/execute_sql/`],
+ })
+ } finally {
+ resolve.mockRestore()
+ }
})
- 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: '' }
+
+ it.each([
+ {
+ handles: 'repeated',
+ conversations: [CONVERSATION_A, CONVERSATION_A],
+ projects: [OTHER_PROJECT, OTHER_PROJECT],
+ scopedOrg: false,
+ },
+ {
+ handles: 'different',
+ conversations: [CONVERSATION_A, CONVERSATION_B],
+ projects: [OTHER_PROJECT, PINNED_PROJECT],
+ scopedOrg: false,
+ },
+ { handles: 'missing', conversations: [], projects: [PINNED_PROJECT, PINNED_PROJECT], scopedOrg: false },
+ { handles: 'org-default', conversations: [], projects: [OTHER_PROJECT, OTHER_PROJECT], scopedOrg: true },
+ ])(
+ 'shares cold batch lookups with $handles conversation handles while preserving routing',
+ async ({ handles, conversations, projects, scopedOrg }) => {
+ const token = `phx_cold_batch_${handles}`
+ if (scopedOrg) {
+ mswServer.use(
+ http.get('*/api/personal_api_keys/@current', () =>
+ HttpResponse.json({ scopes: ['*'], scoped_teams: [], scoped_organizations: [OTHER_ORG] })
+ ),
+ http.get(`*/api/organizations/${OTHER_ORG}/projects/`, () =>
+ HttpResponse.json({ results: [{ id: Number(OTHER_PROJECT), organization: OTHER_ORG }] })
+ )
+ )
+ }
+ for (const [conversationId, projectId] of new Map(
+ conversations.map((id, index) => [id, projects[index]!])
+ )) {
+ expect(
+ (
+ await callTool(
+ 'switch-project',
+ { projectId: Number(projectId) },
+ { token, query: '', conversationId }
+ )
+ ).isError
+ ).toBeFalsy()
+ }
+ await tokenCache(token).clear()
+ apiPathsByIntent.clear()
+ const counts = new Map<string, number>()
+ const record = ({ request }: { request: Request }): void => {
+ const path = new URL(request.url).pathname
+ counts.set(path, (counts.get(path) ?? 0) + 1)
+ }
+ mswServer.events.on('request:start', record)
+ const localApi = vi.spyOn(constants, 'isLocalApi').mockReturnValue(false)
+ const flags = vi
+ .spyOn(getPostHogClient(), 'getAllFlagsAndPayloads')
+ .mockImplementation(async (_distinctId, options) => ({
+ featureFlags: Object.fromEntries(
+ (options?.flagKeys ?? []).map((key) => [
+ key,
+ key !== MCP_INTERVIEW_RECRUITMENT_FLAG && key !== MCP_INTENT_PROMPT_FLAG,
+ ])
+ ),
+ featureFlagPayloads: {},
+ }))
+ try {
+ const results = await postBatch(
+ Array.from({ length: 100 }, (_, index) => ({
+ name: 'execute-sql',
+ arguments: {
+ query: 'SELECT 1',
+ conversation_id: conversations[index % 2],
+ context: `cold-item-${index}`,
+ },
+ })),
+ { token }
+ )
+ expect(results.map(({ result }) => Boolean(result?.isError))).toEqual(Array(100).fill(false))
+ expect(counts.get('/api/personal_api_keys/@current')).toBe(1)
+ expect(counts.get('/api/users/@me/')).toBe(1)
+ expect(flags).toHaveBeenCalledTimes(new Set(projects).size)
+ expect(counts.get(`/api/organizations/${OTHER_ORG}/projects/`) ?? 0).toBe(scopedOrg ? 1 : 0)
+ for (const project of new Set(projects)) {
+ const org = project === OTHER_PROJECT ? OTHER_ORG : PINNED_ORG
+ expect(counts.get(`/api/projects/${project}/`)).toBe(1)
+ expect(counts.get(`/api/organizations/${org}/`)).toBe(1)
+ }
+ expect(Array.from({ length: 100 }, (_, index) => apiPathsByIntent.get(`cold-item-${index}`))).toEqual(
+ Array.from({ length: 100 }, (_, index) => [
+ `/api/environments/${projects[index % 2]}/mcp_tools/execute_sql/`,
+ ])
+ )
+ } finally {
+ mswServer.events.removeListener('request:start', record)
+ flags.mockRestore()
+ localApi.mockRestore()
+ }
+ }
+ )
+
+ it('keeps a conversation bound to its credential and separate from a transport session with the same id', async () => {
+ const token = 'phx_conversation_namespace'
+ const conversation = { token, query: '', conversationId: CONVERSATION_A }
+ await callTool('switch-project', { projectId: Number(OTHER_PROJECT) }, conversation)
+
+ expect(
+ await targets({ token: 'phx_other_conversation_namespace', query: '', conversationId: CONVERSATION_A })
+ ).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+ expect(await targets({ token, query: '', sessionId: CONVERSATION_A })).toEqual({
+ project: PINNED_PROJECT,
+ org: PINNED_ORG,
+ })
+ expect(await targets({ token, query: '', sessionId: CONVERSATION_A, conversationId: CONVERSATION_A })).toEqual({
+ project: PINNED_PROJECT,
+ org: PINNED_ORG,
+ })
+ expect(await targets(conversation)).toEqual({ project: OTHER_PROJECT, org: OTHER_ORG })
+ })
+
+ it.each(['conv-1', CONVERSATION_A.toUpperCase()])(
+ 'uses the SDK-normalized conversation identity for %s',
+ async (supplied) => {
+ const token = `phx_normalize_${supplied}`
+ const first = await postToolCall(
+ 'switch-project',
+ { projectId: Number(OTHER_PROJECT) },
+ { token, query: '', conversationId: supplied }
+ )
+ expect(Boolean(first.result?.isError)).toBe(supplied === 'conv-1')
+ const conversationId = supplied === 'conv-1' ? mintedConversationId(first) : CONVERSATION_A
+ expect(conversationId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-7/)
+ const retry = await callTool(
+ 'switch-project',
+ { projectId: Number(OTHER_PROJECT) },
+ { token, query: '', conversationId }
+ )
+ expect(retry.isError).toBeFalsy()
+
+ expect(await targets({ token, query: '', conversationId })).toEqual({
+ project: OTHER_PROJECT,
+ org: OTHER_ORG,
+ })
+ expect(await targets({ token, query: '', conversationId: supplied })).toEqual(
+ supplied === 'conv-1'
+ ? { project: PINNED_PROJECT, org: PINNED_ORG }
+ : { project: OTHER_PROJECT, org: OTHER_ORG }
+ )
+ }
+ )
+
+ it.each([
+ ['pinned across organizations', `?project_id=${PINNED_PROJECT}`, OTHER_PROJECT, OTHER_ORG],
+ ['unpinned across organizations', '', OTHER_PROJECT, OTHER_ORG],
+ ['unpinned within an organization', '', '3', PINNED_ORG],
+ ])('isolates %s across repeated switches', async (label, query, switchedProject, switchedOrg) => {
+ const token = `phx_${label.replaceAll(' ', '_')}_switches`
+ const session = { token, sessionId: await initialize({ token, query }), query }
+ const otherSession = { token, sessionId: await initialize({ token, query }), query }
for (const [projectId, orgId] of [
- [OTHER_PROJECT, OTHER_ORG],
+ [switchedProject, switchedOrg],
[PINNED_PROJECT, PINNED_ORG],
- [OTHER_PROJECT, OTHER_ORG],
+ [switchedProject, switchedOrg],
]) {
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 })
+ expect(await targets(otherSession)).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+ }
+ })
+
+ it('starts an unpinned session from the user default instead of another connection’s token selection', async () => {
+ const token = 'phx_unpinned_default'
+ await cacheOtherProjectOnToken(token)
+ const sessionId = await initialize({ token, query: '' })
+
+ expect(await targets({ token, sessionId, query: '' })).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+ })
+
+ it.each([
+ ['unpinned session', '', undefined],
+ ['organization-pinned session', `?organization_id=${PINNED_ORG}`, undefined],
+ ['unpinned conversation', '', CONVERSATION_A],
+ ['organization-pinned conversation', `?organization_id=${PINNED_ORG}`, CONVERSATION_A],
+ ])('keeps a %s on its project when the website selection changes', async (label, query, conversationId) => {
+ const token = `phx_website_selection_${label}`
+ const sessionId = conversationId ? undefined : await initialize({ token, query })
+ const connection = { token, sessionId, conversationId, query }
+ await targets(connection)
+ const user = {
+ distinct_id: 'website-selection-test',
+ email: '[email protected]',
+ team: { id: Number(OTHER_PROJECT), name: 'Other project', organization: OTHER_ORG },
+ organization: { id: OTHER_ORG, name: 'Other organization' },
}
+ mswServer.use(http.get('*/api/users/@me/', () => HttpResponse.json(user)))
+ const newSessionId = await initialize({ token, query: '' })
+
+ expect(await targets(connection)).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
+ expect(await targets({ token, sessionId: newSessionId, query: '' })).toEqual({
+ project: OTHER_PROJECT,
+ org: OTHER_ORG,
+ })
+ })
+
+ it.each(['session', 'conversation'])(
+ 'routes overlapping calls from each %s to its own organization and project',
+ async (kind) => {
+ const token = `phx_concurrent_${kind}`
+ const sessions = await Promise.all(
+ [PINNED_PROJECT, OTHER_PROJECT].map(async (projectId) => {
+ const session = {
+ token,
+ ...(kind === 'session'
+ ? { sessionId: await initialize({ token, query: '' }) }
+ : { conversationId: projectId === PINNED_PROJECT ? CONVERSATION_A : CONVERSATION_B }),
+ query: '',
+ }
+ const result = await callTool('switch-project', { projectId: Number(projectId) }, session)
+ expect(result.isError).toBeFalsy()
+ return session
+ })
+ )
+ apiPaths.length = 0
+ apiPathsByIntent.clear()
+
+ const pathsBySession = await Promise.all(
+ sessions.map(async (session, index) => {
+ const context = `concurrent-session-${index}`
+ await Promise.all([
+ callTool('execute-sql', { query: 'SELECT 1', context }, session),
+ callTool('billing-subscription-get', { context }, session),
+ ])
+ return [...(apiPathsByIntent.get(context) ?? [])].sort()
+ })
+ )
+
+ expect(pathsBySession).toEqual([
+ pathsFor(PINNED_PROJECT, PINNED_ORG).sort(),
+ pathsFor(OTHER_PROJECT, OTHER_ORG).sort(),
+ ])
+ }
+ )
+
+ it.each([
+ ['pinned', `?project_id=${PINNED_PROJECT}`],
+ ['unpinned', ''],
+ ])('clears the previous project when a %s session switches organizations', async (label, query) => {
+ const token = `phx_${label}_org_switch`
+ const session = { token, sessionId: await initialize({ token, query }), query }
+ expect((await callTool('switch-organization', { orgId: OTHER_ORG }, session)).isError).toBeFalsy()
+
+ expect(await targets(session)).toEqual({ project: null, org: OTHER_ORG })
+ expect((await callTool('switch-project', { projectId: Number(OTHER_PROJECT) }, session)).isError).toBeFalsy()
+ expect(await targets(session)).toEqual({ project: OTHER_PROJECT, org: OTHER_ORG })
+ })
+
+ it.each([
+ ['same organization', PINNED_ORG, PINNED_PROJECT],
+ ['different organization', OTHER_ORG, null],
+ ])('keeps project ownership consistent for a %s switch without project:read', async (label, orgId, project) => {
+ const token = `phx_no_project_read_${label.replaceAll(' ', '_')}`
+ mswServer.use(
+ http.get('*/api/projects/:projectId/', () =>
+ HttpResponse.json({ detail: 'Missing project:read' }, { status: 403 })
+ ),
+ http.get('*/api/organizations/:orgId/', ({ params }) =>
+ HttpResponse.json({
+ id: params.orgId,
+ name: 'Organization',
+ teams: [{ id: params.orgId === PINNED_ORG ? Number(PINNED_PROJECT) : Number(OTHER_PROJECT) }],
+ })
+ )
+ )
+ const query = `?project_id=${PINNED_PROJECT}`
+ const session = { token, sessionId: await initialize({ token, query }), query }
+ expect((await callTool('switch-organization', { orgId }, session)).isError).toBeFalsy()
+
+ expect(await targets(session)).toEqual({ project, org: orgId })
+ })
+
+ it('preserves the session selection when the destination organization is inaccessible', async () => {
+ const token = 'phx_inaccessible_organization'
+ const session = { token, sessionId: await initialize({ token, query: '' }), query: '' }
+ mswServer.use(
+ http.get(`*/api/organizations/${OTHER_ORG}/`, () =>
+ HttpResponse.json({ detail: 'Not found.' }, { status: 404 })
+ )
+ )
+
+ const result = await callTool('switch-organization', { orgId: OTHER_ORG }, session)
+
+ expect(result.isError).toBe(true)
+ expect(await targets(session)).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
})
it.each([
@@ -293,7 +804,7 @@ describe('pinned project with switch-project (Hono)', () => {
initPin: `?project_id=${PINNED_PROJECT}`,
switchTo: undefined,
replacementPin: `?organization_id=${OTHER_ORG}`,
- expected: { project: OTHER_PROJECT, org: OTHER_ORG },
+ expected: { project: null, org: OTHER_ORG },
},
{
label: 'an organization pin replaced by a project pin',
@@ -360,7 +871,7 @@ describe('pinned project with switch-project (Hono)', () => {
label: 'a cached project in the pinned organization',
seed: cacheOtherProjectOnToken,
pinnedOrg: OTHER_ORG,
- expected: { project: OTHER_PROJECT, org: OTHER_ORG },
+ expected: { project: null, org: OTHER_ORG },
},
{
label: 'no cached project and a default in the pinned organization',
@@ -436,6 +947,6 @@ describe('pinned project with switch-project (Hono)', () => {
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 })
+ expect(await targets({ token, sessionId, query: '' })).toEqual({ project: PINNED_PROJECT, org: PINNED_ORG })
})
})
diff --git a/services/mcp/tests/hono/redis-cache.test.ts b/services/mcp/tests/hono/redis-cache.test.ts
index 63d28f44c999..e2af1f503c47 100644
--- a/services/mcp/tests/hono/redis-cache.test.ts
+++ b/services/mcp/tests/hono/redis-cache.test.ts
@@ -22,7 +22,10 @@ function createMockRedis(): MockRedis {
const store = new Map<string, string>()
return {
get: vi.fn(async (key: string) => store.get(key) ?? null),
- set: vi.fn(async (key: string, value: string) => {
+ set: vi.fn(async (key: string, value: string, ...args: (string | number)[]) => {
+ if (args.includes('NX') && store.has(key)) {
+ return null
+ }
store.set(key, value)
return 'OK'
}),
@@ -82,6 +85,17 @@ describe('RedisCache', () => {
})
describe('set', () => {
+ it('keeps the first value when competing requests initialize the same key', async () => {
+ const first = await cache.setIfAbsent('projectId', '123')
+ const second = await cache.setIfAbsent('projectId', '456')
+
+ expect({ first, second, projectId: await cache.get('projectId') }).toEqual({
+ first: true,
+ second: false,
+ projectId: '123',
+ })
+ })
+
it('should store JSON-serialized values with scoped key', async () => {
await cache.set('region', 'eu')
expect(mockRedis.set).toHaveBeenCalledWith(
diff --git a/services/mcp/tests/hono/request-state-resolver.test.ts b/services/mcp/tests/hono/request-state-resolver.test.ts
index e9334dd4b911..5d4a9d80ef78 100644
--- a/services/mcp/tests/hono/request-state-resolver.test.ts
+++ b/services/mcp/tests/hono/request-state-resolver.test.ts
@@ -10,9 +10,11 @@ const {
mockPinned,
mockGetApiKey,
mockAnalyticsContext,
+ mockDistinctId,
} = vi.hoisted(() => ({
mockGetApiKey: vi.fn(),
- mockAnalyticsContext: { current: undefined as { projectHasData?: boolean } | undefined },
+ mockAnalyticsContext: { current: undefined as MCPAnalyticsContext | undefined },
+ mockDistinctId: { current: 'distinct-id' },
mockSessionStore: new Map<string, unknown>(),
mockTokenStore: new Map<string, unknown>(),
mockApiKey: {
@@ -58,7 +60,8 @@ vi.mock('@/hono/cache/McpSessionRedisStore', () => ({
},
}))
-vi.mock('@/hono/request-context', () => {
+vi.mock('@/hono/request-context', async () => {
+ const { StateLookupCache } = await import('@/lib/cache/StateLookupCache')
type MockCache = {
get: (key: string) => Promise<unknown>
set: (key: string, value: unknown) => Promise<void>
@@ -105,9 +108,10 @@ vi.mock('@/hono/request-context', () => {
return {
RequestContext: vi.fn().mockImplementation(function (...args: unknown[]) {
- const props = args[2] as { mcpSessionId?: string }
+ const props = args[2] as RequestProperties
return {
- tokenCache: makeCache(mockTokenStore),
+ tokenCache: { ...makeCache(mockTokenStore), scope: props.userHash },
+ lookups: args[4] ?? new StateLookupCache(),
sessionScopedCache: props.mcpSessionId ? makeCache(sessionScopedStore(props.mcpSessionId)) : undefined,
legacySessionScopedCache: props.mcpSessionId
? {
@@ -134,7 +138,7 @@ vi.mock('@/hono/request-context', () => {
}
}),
safelyGetAnalyticsContext: vi.fn(async () => mockAnalyticsContext.current),
- getDistinctId: vi.fn(async () => 'distinct-id'),
+ getDistinctId: vi.fn(async () => mockDistinctId.current),
setMcpContexts: vi.fn(),
setPinnedContext: vi.fn((pinned: typeof mockPinned.last) => {
mockPinned.last = pinned
@@ -150,10 +154,13 @@ import { MCP_INTENT_PROMPT_FLAG } from '@/hono/intent-prompt'
import { MCP_INTERVIEW_RECRUITMENT_FLAG } from '@/hono/interview-recruitment'
import { RequestStateResolver } from '@/hono/request-state-resolver'
import { ToolCatalog } from '@/hono/tool-catalog'
+import { StateLookupCache } from '@/lib/cache/StateLookupCache'
import { MCP_NO_DATA_INSTALL_NOTICE_FLAG } from '@/lib/no-data-guard'
+import type { MCPAnalyticsContext } from '@/lib/posthog/analytics'
import { evaluateFeatureFlags, resolveFeatureFlagOverrides } from '@/lib/posthog/flags'
import { parseRequestProperties, type RequestProperties } from '@/lib/request-properties'
import { TASKS_CONTEXT_TOOL_NAMES } from '@/tools/tasksContext'
+import * as toolDefinitions from '@/tools/toolDefinitions'
import type { Env } from '@/tools/types'
function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {
@@ -201,6 +208,7 @@ describe('RequestStateResolver MCP client contexts', () => {
mockRedisFailures.contextReads = 0
mockPinned.last = undefined
mockAnalyticsContext.current = undefined
+ mockDistinctId.current = 'distinct-id'
mockGetApiKey.mockReset().mockImplementation(async () => mockApiKey)
mockApiKey.scopes = ['*']
mockApiKey.is_impersonated = undefined
@@ -208,6 +216,91 @@ describe('RequestStateResolver MCP client contexts', () => {
mockApiKey.mcp_allowed_tools = undefined
})
+ it.each([
+ { change: 'none', shared: true },
+ { change: 'credential', shared: false },
+ { change: 'distinct ID', shared: false },
+ { change: 'project group', shared: false },
+ { change: 'organization group', shared: false },
+ { change: 'flag keys', shared: false },
+ { change: 'flag order', shared: true },
+ { change: 'next request', shared: false },
+ ])('shares flag values and payloads only for matching inputs: $change', async ({ change, shared }) => {
+ const requiredFlags = vi.spyOn(toolDefinitions, 'getRequiredFeatureFlags').mockReturnValue(['flag-a', 'flag-b'])
+ const evaluate = vi
+ .mocked(evaluateFeatureFlags)
+ .mockClear()
+ .mockResolvedValueOnce({
+ flags: { [MCP_INTENT_PROMPT_FLAG]: 'first-variant' },
+ payloads: { [MCP_INTENT_PROMPT_FLAG]: { prompt: 'First context prompt' } },
+ })
+ .mockResolvedValue({
+ flags: { [MCP_INTENT_PROMPT_FLAG]: 'second-variant' },
+ payloads: { [MCP_INTENT_PROMPT_FLAG]: { prompt: 'Second context prompt' } },
+ })
+ try {
+ const lookups = new StateLookupCache()
+ const resolver = makeResolver()
+ mockAnalyticsContext.current = { organizationId: 'org-a', projectUuid: 'project-a' }
+ const first = await resolver.resolve(makeProps(), lookups)
+ if (change === 'distinct ID') {
+ mockDistinctId.current = 'other-distinct-id'
+ }
+ if (change === 'project group') {
+ mockAnalyticsContext.current.projectUuid = 'project-b'
+ }
+ if (change === 'organization group') {
+ mockAnalyticsContext.current.organizationId = 'org-b'
+ }
+ if (change === 'flag keys') {
+ requiredFlags.mockReturnValue(['other-flag'])
+ }
+ if (change === 'flag order') {
+ requiredFlags.mockReturnValue(['flag-b', 'flag-a'])
+ }
+ const second = await resolver.resolve(
+ makeProps(change === 'credential' ? { userHash: 'other-user', apiToken: 'phx_other' } : {}),
+ change === 'next request' ? undefined : lookups
+ )
+ expect({
+ calls: evaluate.mock.calls.length,
+ first: { flag: first.toolFeatureFlags?.[MCP_INTENT_PROMPT_FLAG], prompt: first.intentPrompt },
+ second: { flag: second.toolFeatureFlags?.[MCP_INTENT_PROMPT_FLAG], prompt: second.intentPrompt },
+ }).toEqual({
+ calls: shared ? 1 : 2,
+ first: { flag: 'first-variant', prompt: 'First context prompt' },
+ second: shared
+ ? { flag: 'first-variant', prompt: 'First context prompt' }
+ : { flag: 'second-variant', prompt: 'Second context prompt' },
+ })
+ } finally {
+ requiredFlags.mockRestore()
+ evaluate.mockReset().mockResolvedValue({ flags: {}, payloads: {} })
+ }
+ })
+
+ it('retries a failed flag evaluation within the request', async () => {
+ const evaluate = vi
+ .mocked(evaluateFeatureFlags)
+ .mockClear()
+ .mockRejectedValueOnce(new Error('Synthetic flag failure'))
+ .mockResolvedValue({
+ flags: { [MCP_INTENT_PROMPT_FLAG]: true },
+ payloads: { [MCP_INTENT_PROMPT_FLAG]: { prompt: 'Recovered prompt' } },
+ })
+ try {
+ const lookups = new StateLookupCache()
+ const resolver = makeResolver()
+ const first = await resolver.resolve(makeProps(), lookups)
+ const retry = await resolver.resolve(makeProps(), lookups)
+ expect({ calls: evaluate.mock.calls.length, first: first.intentPrompt, retry: retry.intentPrompt }).toEqual(
+ { calls: 2, first: undefined, retry: 'Recovered prompt' }
+ )
+ } finally {
+ evaluate.mockReset().mockResolvedValue({ flags: {}, payloads: {} })
+ }
+ })
+
it.each([true, false, undefined])(
'passes token capture policy=%s to analytics despite caller headers',
async (impersonated) => {
@@ -661,13 +754,19 @@ describe('RequestStateResolver MCP client contexts', () => {
})
it('honors a dev/test flag override even when evaluation returns nothing', async () => {
- // Evaluation stays empty (analytics client disabled, as in local dev/evals);
- // the override seam is what flips a tool flag on so it reaches the tool layer.
- vi.mocked(resolveFeatureFlagOverrides).mockReturnValueOnce({ 'dev-forced-flag': true })
- const props = makeProps({ mcpClientName: 'Claude Desktop', mcpVendorClient: 'ClaudeAI' })
- const result = await makeResolver().resolve(props)
+ const evaluate = vi.mocked(evaluateFeatureFlags).mockClear()
+ vi.mocked(resolveFeatureFlagOverrides)
+ .mockReturnValueOnce({ 'dev-forced-flag': false })
+ .mockReturnValueOnce({ 'dev-forced-flag': true })
+ const lookups = new StateLookupCache()
+ const resolver = makeResolver()
+ const first = await resolver.resolve(makeProps(), lookups)
+ const second = await resolver.resolve(makeProps(), lookups)
- expect(result.toolFeatureFlags?.['dev-forced-flag']).toBe(true)
+ expect({
+ calls: evaluate.mock.calls.length,
+ overrides: [first.toolFeatureFlags?.['dev-forced-flag'], second.toolFeatureFlags?.['dev-forced-flag']],
+ }).toEqual({ calls: 1, overrides: [false, true] })
})
it.each([
@@ -710,7 +809,6 @@ describe('RequestStateResolver MCP client contexts', () => {
})
describe('pinned project/org context', () => {
- // 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)
@@ -785,14 +883,24 @@ describe('RequestStateResolver MCP client contexts', () => {
expect(mockPinned.last?.projectId).toBe('1')
})
- it('renews the session-scoped keys TTL on every pinned request', async () => {
+ it.each([
+ ['pinned', '1'],
+ ['unpinned', undefined],
+ ])('renews the session-scoped keys TTL on every %s request', async (_label, projectId) => {
// 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' }))
+ await makeResolver().resolve(makeProps({ projectId }))
expect(mockRefreshTtlCalls).toContainEqual(
- expect.arrayContaining(['appliedPinOrgId', 'appliedPinProjectId', 'activeOrgId', 'activeProjectId'])
+ expect.arrayContaining([
+ 'appliedPinOrgId',
+ 'appliedPinProjectId',
+ 'activeOrgId',
+ 'activeProjectId',
+ 'defaultContext',
+ 'defaultProjectId',
+ ])
)
})
})
diff --git a/services/mcp/tests/hono/tool-executor-intent.test.ts b/services/mcp/tests/hono/tool-executor-intent.test.ts
index 97030b78c395..5e5a2b87741d 100644
--- a/services/mcp/tests/hono/tool-executor-intent.test.ts
+++ b/services/mcp/tests/hono/tool-executor-intent.test.ts
@@ -543,19 +543,26 @@ describe('ToolExecutor analytics capture', () => {
captureSpy.mockRestore()
})
- it('leaves a client that already has a session untouched', async () => {
+ it.each([
+ { requestContext: { mcpSessionId: 'sess-1' }, expectedHandle: undefined },
+ {
+ requestContext: { sessionId: 'wrapper-1' },
+ expectedHandle: expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-7/),
+ },
+ ])('returns handle $expectedHandle for $requestContext', async ({ requestContext, expectedHandle }) => {
const captureSpy = vi.spyOn(getPostHogClient(), 'captureToolCall').mockImplementation(() => {})
- // `makeToolExecutorState` carries `sessionId: 'sess-1'`, the wrapper-app id.
- const state = makeToolExecutorState([], { useSingleExec: true })
+ const state = makeToolExecutorState([], {
+ useSingleExec: true,
+ requestContext: { authMethod: 'personal_api_key', ...requestContext },
+ })
await executor.handleToolsList(state)
const result = await executor.handleToolCall({ name: 'exec', arguments: { command: 'tools' } }, state)
- // Minting here would split the session these clients already group by, and append a
- // block to every first result, for the majority of today's traffic.
- expect(readConversationHandle(result)).toBeUndefined()
+ const handle = readConversationHandle(result)
+ expect(handle).toEqual(expectedHandle)
await vi.waitFor(() => expect(captureSpy).toHaveBeenCalledTimes(1))
- expect(captureSpy.mock.calls[0]![0].conversationId).toBeUndefined()
+ expect(captureSpy.mock.calls[0]![0].conversationId).toBe(handle)
captureSpy.mockRestore()
})
diff --git a/services/mcp/tests/shared/test-utils.ts b/services/mcp/tests/shared/test-utils.ts
index cf9d24be119d..7d08d278d249 100644
--- a/services/mcp/tests/shared/test-utils.ts
+++ b/services/mcp/tests/shared/test-utils.ts
@@ -693,7 +693,7 @@ export function makeToolExecutorState(
} as any,
requestContext: {
authMethod: 'personal_api_key',
- sessionId: 'sess-1',
+ mcpSessionId: 'sess-1',
mcpClientName: 'test',
mcpClientVersion: '1.0',
mcpProtocolVersion: '2025-03-26',
diff --git a/services/mcp/tests/unit/StateManager.test.ts b/services/mcp/tests/unit/StateManager.test.ts
index b00e0e00c9be..ad060487396d 100644
--- a/services/mcp/tests/unit/StateManager.test.ts
+++ b/services/mcp/tests/unit/StateManager.test.ts
@@ -2,11 +2,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ApiClient } from '@/api/client'
import { MemoryCache } from '@/lib/cache/MemoryCache'
+import { StateLookupCache } from '@/lib/cache/StateLookupCache'
import { PostHogApiError } from '@/lib/errors'
import { getPostHogClient } from '@/lib/posthog'
import { StateManager } from '@/lib/StateManager'
import type { ApiRedactedPersonalApiKey, ApiUser } from '@/schema/api'
-import type { State } from '@/tools/types'
+import type { PinnedActiveContext, SessionScopedState, State } from '@/tools/types'
describe('StateManager', () => {
let stateManager: StateManager
@@ -34,6 +35,112 @@ describe('StateManager', () => {
stateManager = new StateManager(cache, {} as ApiClient)
})
+ it.each([
+ {
+ lookup: 'organization',
+ context: { pin: { projectId: '456' }, projectId: '456' },
+ resolve: (manager: StateManager) => manager.getOrgID(),
+ expected: 'org-1',
+ },
+ {
+ lookup: 'project',
+ context: { pin: { organizationId: 'org-1' }, orgId: 'org-1' },
+ resolve: (manager: StateManager) => manager.getProjectId(),
+ expected: '456',
+ },
+ {
+ lookup: 'default',
+ context: { pin: {} },
+ resolve: (manager: StateManager) => manager.setDefaultOrganizationAndProject(),
+ expected: { organizationId: 'org-1', projectId: 456 },
+ },
+ {
+ lookup: 'initialization',
+ context: { pin: {} },
+ resolve: (manager: StateManager) => manager.setDefaultOrganizationAndProject(),
+ expected: { organizationId: 'org-2', projectId: 789 },
+ },
+ ])(
+ 'preserves a newer selection when an older $lookup lookup finishes',
+ async ({ lookup, context, resolve, expected }) => {
+ const sessionCache = new MemoryCache<SessionScopedState>(`stale-${lookup}`)
+ await sessionCache.clear()
+ await cache.setMany({
+ apiKey: lookup === 'project' ? { ...mockApiKey, scoped_teams: [456] } : mockApiKey,
+ apiKeyFetchedAt: Date.now(),
+ })
+ let finishLookup!: () => void
+ let lookupRequested!: () => void
+ const requested = new Promise<void>((resolve) => {
+ lookupRequested = resolve
+ })
+ const gate = new Promise<void>((resolve) => {
+ finishLookup = resolve
+ })
+ const api = {
+ config: { apiToken: 'phx_test' },
+ users: () => ({
+ me: async () => {
+ if (lookup === 'default' || lookup === 'initialization') {
+ lookupRequested()
+ await gate
+ }
+ return { success: true, data: mockUser }
+ },
+ }),
+ projects: () => ({
+ get: async () => {
+ lookupRequested()
+ await gate
+ return { success: true, data: { id: 456, organization: 'org-1' } }
+ },
+ }),
+ } as unknown as ApiClient
+ const snapshot = (): PinnedActiveContext => ({
+ ...context,
+ sessionScoped: true,
+ })
+ const older = new StateManager(cache, api, snapshot(), sessionCache)
+ const currentApi = {
+ ...api,
+ users: () => ({
+ me: async () => ({
+ success: true,
+ data: {
+ ...mockUser,
+ organization: { id: 'org-2', name: 'Other organization' },
+ team: { id: 789, name: 'Other project', organization: 'org-2' },
+ },
+ }),
+ }),
+ } as unknown as ApiClient
+ const newer = new StateManager(cache, currentApi, snapshot(), sessionCache)
+ const pending = resolve(older)
+ await requested
+ try {
+ if (lookup === 'initialization') {
+ await newer.setDefaultOrganizationAndProject()
+ } else {
+ await newer.setActiveContext({ orgId: 'org-2', projectId: '789' })
+ }
+ } finally {
+ finishLookup()
+ }
+
+ const resolved = await pending
+ const defaults = await sessionCache.get('defaultContext')
+ expect({
+ resolved,
+ orgId: (await sessionCache.get('activeOrgId')) ?? defaults?.organizationId,
+ projectId: (await sessionCache.get('activeProjectId')) ?? defaults?.projectId?.toString(),
+ }).toEqual({
+ resolved: expected,
+ orgId: 'org-2',
+ projectId: '789',
+ })
+ }
+ )
+
it.each([true, false, undefined])('reports lookup errors with cached suppression=%s', async (suppressed) => {
const capture = vi.spyOn(getPostHogClient(), 'captureException').mockImplementation(() => {})
const error = new Error('Synthetic project lookup failure')
@@ -58,6 +165,45 @@ describe('StateManager', () => {
})
describe('getUser', () => {
+ it.each(['user', 'credential'] as const)(
+ 'shares a failed %s lookup and permits a later retry',
+ async (kind) => {
+ const load = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('Synthetic lookup failure'))
+ .mockResolvedValue({ success: true, data: kind === 'user' ? mockUser : mockApiKey })
+ const api = {
+ config: { apiToken: 'phx_test' },
+ users: () => ({ me: load }),
+ apiKeys: () => ({ current: load }),
+ } as unknown as ApiClient
+ const lookups = new StateLookupCache()
+ const first = new StateManager(cache, api, undefined, undefined, lookups)
+ const second = new StateManager(cache, api, undefined, undefined, lookups)
+ const get = (manager: StateManager): Promise<unknown> =>
+ kind === 'user' ? manager.getUser() : manager.getApiKey()
+ const failed = await Promise.allSettled([get(first), get(second)])
+ expect(failed.map(({ status }) => status)).toEqual(['rejected', 'rejected'])
+ expect(load).toHaveBeenCalledTimes(1)
+ expect(await get(second)).toMatchObject(kind === 'user' ? mockUser : mockApiKey)
+ expect(load).toHaveBeenCalledTimes(2)
+ }
+ )
+
+ it('keeps shared lookup results bound to their credential cache scope', async () => {
+ const lookups = new StateLookupCache()
+ const managers = ['first-credential', 'second-credential'].map((scope) => {
+ const scopedCache = new MemoryCache<State>(scope)
+ const api = {
+ users: () => ({ me: async () => ({ success: true, data: { ...mockUser, distinct_id: scope } }) }),
+ } as unknown as ApiClient
+ return new StateManager(scopedCache, api, undefined, undefined, lookups)
+ })
+ expect(
+ (await Promise.all(managers.map((manager) => manager.getUser()))).map((user) => user.distinct_id)
+ ).toEqual(['first-credential', 'second-credential'])
+ })
+
it('should fetch and cache user on first call', async () => {
const fetchUserSpy = vi.spyOn(stateManager as any, '_fetchUser').mockResolvedValue(mockUser)
@@ -188,14 +334,15 @@ describe('StateManager', () => {
data: { ...mockApiKey, scopes: ['user:read', 'cdp:read'] },
})
const api = { config: { apiToken }, apiKeys: () => ({ current }) } as unknown as ApiClient
+ const manager = new StateManager(cache, api)
- expect((await new StateManager(cache, api).getApiKey()).scopes).toEqual(mockApiKey.scopes)
+ expect((await manager.getApiKey()).scopes).toEqual(mockApiKey.scopes)
vi.advanceTimersByTime(60 * 1000)
- expect((await new StateManager(cache, api).getApiKey()).scopes).toEqual(mockApiKey.scopes)
+ expect((await manager.getApiKey()).scopes).toEqual(mockApiKey.scopes)
vi.advanceTimersByTime(2 * 60 * 1000)
- expect((await new StateManager(cache, api).getApiKey()).scopes).toEqual(expectedScopes)
+ expect((await manager.getApiKey()).scopes).toEqual(expectedScopes)
} finally {
vi.useRealTimers()
}
@@ -268,11 +415,15 @@ describe('StateManager', () => {
{ label: 'no OAuth app name', clientName: null, expected: undefined },
])('stamps $label onto the live client so the same request forwards it', async ({ clientName, expected }) => {
const api = oauthApi(clientName)
- stateManager = new StateManager(cache, api)
+ const secondApi = oauthApi(clientName)
+ const lookups = new StateLookupCache()
+ stateManager = new StateManager(cache, api, undefined, undefined, lookups)
+ const second = new StateManager(cache, secondApi, undefined, undefined, lookups)
- await stateManager.getApiKey()
+ await Promise.all([stateManager.getApiKey(), second.getApiKey()])
expect(api.config.oauthClientName).toBe(expected)
+ expect(secondApi.config.oauthClientName).toBe(expected)
expect(await cache.get('clientName')).toBe(expected)
})
})
@@ -501,6 +652,95 @@ describe('StateManager', () => {
expect(reportSpy).toHaveBeenCalledOnce()
})
+ it.each(['503', 'timeout', 'empty'])('recovers a session default after a project-list %s', async (failure) => {
+ const sessionCache = new MemoryCache<SessionScopedState>(`default-recovery-${failure}`)
+ await sessionCache.clear()
+ await cache.setMany({
+ apiKey: { ...mockApiKey, scoped_organizations: ['org-3', 'org-2'] },
+ apiKeyFetchedAt: Date.now(),
+ })
+ const list = vi.fn()
+ if (failure === 'timeout') {
+ list.mockRejectedValueOnce(new Error('Synthetic project-list timeout'))
+ } else {
+ list.mockResolvedValueOnce(
+ failure === 'empty'
+ ? { success: true, data: [] }
+ : { success: false, error: new Error('Synthetic project-list 503') }
+ )
+ }
+ list.mockResolvedValue({ success: true, data: [{ id: 789 }] })
+ let currentUser = mockUser
+ const api = {
+ config: { apiToken: 'phx_test' },
+ users: () => ({ me: async () => ({ success: true, data: currentUser }) }),
+ organizations: () => ({ projects: () => ({ list }) }),
+ projects: () => ({
+ get: async () => ({
+ success: false,
+ error: new Error('Project metadata is outside the active org scope'),
+ }),
+ }),
+ } as unknown as ApiClient
+ const first = new StateManager(cache, api, { pin: {}, sessionScoped: true }, sessionCache)
+ await first.setDefaultOrganizationAndProject()
+ currentUser = {
+ ...mockUser,
+ organization: { id: 'org-2', name: 'Org 2' },
+ team: { id: 999, name: 'Other project', organization: 'org-2', timezone: 'UTC' },
+ }
+ const next = new StateManager(cache, api, { pin: {}, sessionScoped: true, orgId: 'org-3' }, sessionCache)
+
+ expect(await next.getProjectId()).toBe('789')
+ })
+
+ it('keeps the first recovered default and a newer switch when a delayed recovery finishes', async () => {
+ const sessionCache = new MemoryCache<SessionScopedState>('default-recovery-race')
+ await sessionCache.clear()
+ await sessionCache.set('defaultContext', { organizationId: 'org-3' })
+ let requested!: () => void
+ let finish!: () => void
+ const started = new Promise<void>((resolve) => {
+ requested = resolve
+ })
+ const gate = new Promise<void>((resolve) => {
+ finish = resolve
+ })
+ const list = vi
+ .fn()
+ .mockImplementationOnce(async () => {
+ requested()
+ await gate
+ return { success: true, data: [{ id: 789 }] }
+ })
+ .mockResolvedValue({ success: true, data: [{ id: 999 }] })
+ const api = {
+ config: { apiToken: 'phx_test' },
+ organizations: () => ({ projects: () => ({ list }) }),
+ } as unknown as ApiClient
+ const snapshot = (): PinnedActiveContext => ({ pin: {}, sessionScoped: true, orgId: 'org-3' })
+ const older = new StateManager(cache, api, snapshot(), sessionCache)
+ const newer = new StateManager(cache, api, snapshot(), sessionCache)
+ const pending = older.setDefaultOrganizationAndProject()
+ await started
+ try {
+ await newer.setDefaultOrganizationAndProject()
+ await newer.setActiveContext({ orgId: 'org-2', projectId: '222' })
+ } finally {
+ finish()
+ }
+
+ expect({
+ resolved: await pending,
+ orgId: await sessionCache.get('activeOrgId'),
+ projectId: await sessionCache.get('activeProjectId'),
+ }).toEqual({
+ resolved: { organizationId: 'org-3', projectId: 999 },
+ orgId: 'org-2',
+ projectId: '222',
+ })
+ })
+
it('does not capture a 404 from the scoped-org projects lookup', async () => {
// A misconfigured key pointed at a deleted or inaccessible org makes
// the org-nested projects endpoint return 404 on every retry. This
diff --git a/services/mcp/tests/unit/cli-config.test.ts b/services/mcp/tests/unit/cli-config.test.ts
new file mode 100644
index 000000000000..47a87010e6ae
--- /dev/null
+++ b/services/mcp/tests/unit/cli-config.test.ts
@@ -0,0 +1,34 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { resolveCliConfig } from '@/cli/config'
+
+describe('CLI target configuration', () => {
+ afterEach(() => vi.unstubAllEnvs())
+
+ it.each([
+ { flags: ['--project-id', '22'], expected: { projectId: '22' } },
+ { flags: ['--organization-id', 'org-b'], expected: { organizationId: 'org-b' } },
+ {
+ flags: ['--organization-id', 'org-b', '--project-id', '22'],
+ expected: { organizationId: 'org-b', projectId: '22' },
+ },
+ { flags: [], expected: { organizationId: 'org-a', projectId: '11' } },
+ ])('resolves $flags without mixing explicit and inherited targets', ({ flags, expected }) => {
+ vi.stubEnv('POSTHOG_API_KEY', 'phx_example')
+ vi.stubEnv('POSTHOG_ORGANIZATION_ID', 'org-a')
+ vi.stubEnv('POSTHOG_PROJECT_ID', '11')
+ const args = [...flags, 'feature-flag-get-all', '{}']
+
+ expect(resolveCliConfig(args)).toEqual({
+ apiKey: 'phx_example',
+ host: 'https://us.posthog.com',
+ version: 2,
+ ...expected,
+ })
+ expect(args).toEqual(['feature-flag-get-all', '{}'])
+ })
+
+ it.each(['--project-id', '--organization-id'])('rejects a missing value for %s', (flag) => {
+ expect(() => resolveCliConfig([flag])).toThrow(`Missing value for ${flag}`)
+ })
+})
diff --git a/services/mcp/tests/unit/cli-target.test.ts b/services/mcp/tests/unit/cli-target.test.ts
new file mode 100644
index 000000000000..cd1131cf0424
--- /dev/null
+++ b/services/mcp/tests/unit/cli-target.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { buildCliContext } from '@/cli/context'
+import { MissingProjectContextError } from '@/lib/errors'
+
+vi.mock('@/lib/posthog', () => ({ getPostHogClient: () => ({ capture: vi.fn(), captureException: vi.fn() }) }))
+
+describe('CLI invocation targets', () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it('keeps overlapping invocations on their own project and organization with the same credential', async () => {
+ const [first, second] = await Promise.all([
+ buildCliContext({
+ apiKey: 'phx_example',
+ host: 'https://example.com',
+ version: 2,
+ projectId: '11',
+ organizationId: 'org-a',
+ }),
+ buildCliContext({
+ apiKey: 'phx_example',
+ host: 'https://example.com',
+ version: 2,
+ projectId: '22',
+ organizationId: 'org-b',
+ }),
+ ])
+
+ expect(
+ await Promise.all([
+ first.stateManager.getProjectId(),
+ first.stateManager.getOrgID(),
+ second.stateManager.getProjectId(),
+ second.stateManager.getOrgID(),
+ ])
+ ).toEqual(['11', 'org-a', '22', 'org-b'])
+ })
+
+ it('derives a project-only target organization from the project rather than the website default', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => Response.json({ id: 22, organization: 'org-b' }))
+ )
+ const context = await buildCliContext({
+ apiKey: 'phx_project',
+ host: 'https://example.com',
+ version: 2,
+ projectId: '22',
+ })
+ await context.cache.set('orgId', 'org-a')
+
+ expect(await context.stateManager.getOrgID()).toBe('org-b')
+ })
+
+ it('refuses to fall back to another organization when an org-only target needs a project', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string) =>
+ Response.json(
+ url.includes('/projects/')
+ ? { id: 11, organization: 'org-a' }
+ : { organization: { id: 'org-a' }, team: { id: 11 } }
+ )
+ )
+ )
+ const context = await buildCliContext({
+ apiKey: 'phx_org',
+ host: 'https://example.com',
+ version: 2,
+ organizationId: 'org-b',
+ })
+ await context.cache.setMany({
+ projectId: '11',
+ apiKey: { scopes: [], scoped_teams: [], scoped_organizations: [] },
+ apiKeyFetchedAt: Date.now(),
+ })
+
+ await expect(context.stateManager.getProjectId()).rejects.toBeInstanceOf(MissingProjectContextError)
+ })
+})
diff --git a/services/mcp/tests/unit/switch-project.test.ts b/services/mcp/tests/unit/switch-project.test.ts
index c0dda18cf6c7..bd6bc463dd76 100644
--- a/services/mcp/tests/unit/switch-project.test.ts
+++ b/services/mcp/tests/unit/switch-project.test.ts
@@ -15,11 +15,9 @@ function createMockContext(overrides: {
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',
@@ -49,9 +47,8 @@ function createMockContext(overrides: {
sessionManager: {},
getDistinctId: async () => 'test-distinct-id',
trackEvent: async () => {},
- setSessionActiveContext,
} as unknown as Context
- return { context, cache, getCachedOrFetchOrg, setSessionActiveContext }
+ return { context, cache, getCachedOrFetchOrg }
}
describe('switch-project', () => {
@@ -84,7 +81,7 @@ describe('switch-project', () => {
success: true,
data: { id: 42, name: 'My project', organization: ACTIVE_ORG },
})
- const { context, cache, getCachedOrFetchOrg, setSessionActiveContext } = createMockContext({ projectGet })
+ const { context, cache, getCachedOrFetchOrg } = createMockContext({ projectGet })
const result = await tool.handler(context, { projectId: 42 })
@@ -92,9 +89,6 @@ 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('never exposes the project API token in the switch response', async () => {