Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mcps): 隔离并发 session 上下文 (#2186)
Chris Zhangecf7cbb41b52
diff --git a/packages/lizi-mcps/src/__tests__/sessionContext.test.ts b/packages/lizi-mcps/src/__tests__/sessionContext.test.tsindex 724b610caf..72ee1326a9 100644--- a/packages/lizi-mcps/src/__tests__/sessionContext.test.ts+++ b/packages/lizi-mcps/src/__tests__/sessionContext.test.ts@@ -5,8 +5,13 @@ import { describe, expect, it, vi } from 'vitest';import { createOrcaMcpServer } from '../orca/server.js';import { createLiziMcpProviders } from '../providers.js';import { createXdtHelperMcpServer } from '../lizi_xdtHelperMcpServer.js';-import { runWithLiziMcpSessionContext } from '../session-context.js';+import {+ getLiziMcpSessionContext,+ resolveLiziMcpSessionContext,+ runWithLiziMcpSessionContext,+} from '../session-context.js';import type { OrcaMcpDeps } from '../orca/server.js';+import type { LiziMcpSessionContext } from '../types.js';import type { RenameSessionsDeps } from '../xdt-helper/rename_sessions.js';import type { SetCurrentSessionTitleDeps } from '../xdt-helper/set_current_session_title.js';@@ -330,6 +335,154 @@ describe('dynamic lizi MCP session context', () => {});});+ it('fails closed when the authoritative accessor cannot resolve a session', async () => {+ const provider = createLiziMcpProviders({ xdtHelper: {} }).find(+ (candidate) => candidate.name === 'cindy_helper',+ );+ if (!provider) throw new Error('cindy_helper provider missing');++ const cfg = provider.toClaudeSdkConfig({+ agentKind: 'codex',+ workingDir: '/captured-other-workdir',+ sessionId: 'captured-other-session',+ vendorOptions: { source: 'captured-other-source' },+ getSessionContext: () => undefined,+ }) as { type: 'sdk'; instance: unknown };++ const result = await tools(cfg.instance).call_tool.handler({+ name: 'get_current_session_id',+ args: {},+ });++ expect(parse(result as never)).toMatchObject({+ ok: false,+ errorCode: 'NO_SESSION_CONTEXT',+ });+ });++ it('keeps a sessionInstanceId-only captured context isolated from ambient ALS', () => {+ const capturedContext: LiziMcpSessionContext = {+ agentKind: 'claude-code',+ workingDir: '',+ sessionInstanceId: 'cc-instance',+ };++ const resolved = runWithLiziMcpSessionContext(+ {+ agentKind: 'codex',+ workingDir: '/codex-repo',+ sessionId: 'codex-session',+ sessionInstanceId: 'codex-instance',+ },+ () => resolveLiziMcpSessionContext(capturedContext),+ );++ expect(resolved).toBe(capturedContext);+ expect(resolved).toMatchObject({+ agentKind: 'claude-code',+ sessionInstanceId: 'cc-instance',+ });+ expect(resolved.sessionId).toBeUndefined();+ });++ it('keeps concurrent Claude Code and Codex helper calls on their own session ids', async () => {+ const provider = createLiziMcpProviders({ xdtHelper: {} }).find(+ (candidate) => candidate.name === 'cindy_helper',+ );+ if (!provider) throw new Error('cindy_helper provider missing');++ const claudeContext: LiziMcpSessionContext = {+ agentKind: 'claude-code' as const,+ workingDir: '/cc-repo',+ sessionId: 'cc-session',+ vendorOptions: {},+ getSessionContext: () => claudeContext,+ };+ const codexFactoryContext = {+ agentKind: 'codex' as const,+ workingDir: '',+ vendorOptions: {},+ getSessionContext: getLiziMcpSessionContext,+ };+ const claudeServer = (+ provider.toClaudeSdkConfig(claudeContext) as {+ type: 'sdk';+ instance: unknown;+ }+ ).instance;+ const codexServer = (+ provider.toClaudeSdkConfig(codexFactoryContext) as {+ type: 'sdk';+ instance: unknown;+ }+ ).instance;++ const codexRequestContext = {+ agentKind: 'codex' as const,+ workingDir: '/codex-repo',+ sessionId: 'codex-session',+ vendorOptions: {},+ };+ const [claudeResult, codexResult] = await runWithLiziMcpSessionContext(+ codexRequestContext,+ async () =>+ Promise.all([+ tools(claudeServer).call_tool.handler({+ name: 'get_current_session_id',+ args: {},+ }),+ tools(codexServer).call_tool.handler({+ name: 'get_current_session_id',+ args: {},+ }),+ ]),+ );++ expect(parse(claudeResult as never)).toMatchObject({+ ok: true,+ session_id: 'cc-session',+ agent_kind: 'claude-code',+ working_dir: '/cc-repo',+ });+ expect(parse(codexResult as never)).toMatchObject({+ ok: true,+ session_id: 'codex-session',+ agent_kind: 'codex',+ working_dir: '/codex-repo',+ });+ });++ it('keeps scheduler caller ownership fail-closed when dynamic context is absent', async () => {+ const resolveInflightRunForSession = vi.fn(() => 'wrong-run');+ const silenceRun = vi.fn(() => true);+ const provider = createLiziMcpProviders({+ scheduler: {+ getScheduler: () =>+ ({ resolveInflightRunForSession, silenceRun }) as never,+ },+ }).find((candidate) => candidate.name === 'cindy_scheduler');+ if (!provider) throw new Error('cindy_scheduler provider missing');++ const cfg = provider.toClaudeSdkConfig({+ agentKind: 'codex',+ workingDir: '/captured-other-workdir',+ sessionId: 'captured-other-session',+ vendorOptions: {},+ getSessionContext: () => undefined,+ }) as { type: 'sdk'; instance: unknown };+ const result = await tools(cfg.instance).call_tool.handler({+ name: 'schedule_silence_current_run',+ args: { runId: 'explicit-run' },+ });++ expect(parse(result as never)).toMatchObject({+ ok: true,+ data: { silenced: true, runId: 'explicit-run' },+ });+ expect(resolveInflightRunForSession).not.toHaveBeenCalled();+ expect(silenceRun).toHaveBeenCalledWith('explicit-run');+ });+it('lets cindy_helper update the current session title dynamically', async () => {const setCurrentSessionTitle: SetCurrentSessionTitleDeps['setCurrentSessionTitle'] = vi.fn(async ({ sessionId, title }) => ({diff --git a/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts b/packages/lizi-mcps/src/cindy_schedulerMcpServer.tsindex 1f731d53ce..164521677f 100644--- a/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts+++ b/packages/lizi-mcps/src/cindy_schedulerMcpServer.ts@@ -53,6 +53,7 @@ import type { LiziMcpSessionContext, SchedulerMcpDeps } from './types.js';export interface SchedulerMcpSessionCtx {agentKind: 'claude-code' | 'codex' | 'pi';workingDir: string;+ getSessionContext?: () => LiziMcpSessionContext | undefined;sessionId?: string;vendorOptions?: Record<string, unknown>;}diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex e865b85c00..460c1a867d 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -255,6 +255,7 @@ export interface XdtHelperMcpDeps {export interface XdtHelperMcpSessionCtx {agentKind: 'claude-code' | 'codex' | 'pi';workingDir: string;+ getSessionContext?: () => import('./types.js').LiziMcpSessionContext | undefined;sessionId?: string;vendorOptions?: Record<string, unknown>;}diff --git a/packages/lizi-mcps/src/orca/server.ts b/packages/lizi-mcps/src/orca/server.tsindex 88bc0511ac..b3d3d5e27b 100644--- a/packages/lizi-mcps/src/orca/server.ts+++ b/packages/lizi-mcps/src/orca/server.ts@@ -238,6 +238,7 @@ export interface OrcaWorkerDiagnosticOutput extends OrcaWorkerDiagnosticStatus {export interface OrcaMcpSessionCtx {agentKind: ControlWorkerAgent;workingDir: string;+ getSessionContext?: () => import('../types.js').LiziMcpSessionContext | undefined;sessionId?: string;/** start_team / end_team 读 vendorOptions.orcaRole 决定是否允许调用* (worker session 不能再开 team)。 */diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.tsindex d244094ead..652cfa3ed4 100644--- a/packages/lizi-mcps/src/providers.ts+++ b/packages/lizi-mcps/src/providers.ts@@ -314,6 +314,7 @@ export function createLiziMcpProviders(instance: createSchedulerMcpServer(opts.scheduler!, {agentKind: ctx.agentKind === 'codex' ? 'codex' : ctx.agentKind === 'pi' ? 'pi' : 'claude-code',workingDir: ctx.workingDir,+ ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}),sessionId: ctx.sessionId,vendorOptions: ctx.vendorOptions,}),@@ -353,6 +354,7 @@ export function createLiziMcpProviders(instance: createXdtHelperMcpServer(opts.xdtHelper!, {agentKind: ctx.agentKind === 'codex' ? 'codex' : ctx.agentKind === 'pi' ? 'pi' : 'claude-code',workingDir: ctx.workingDir,+ ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}),sessionId: ctx.sessionId,vendorOptions: ctx.vendorOptions,}),@@ -375,6 +377,7 @@ export function createLiziMcpProviders(instance: createOrcaMcpServer(opts.orca!, {agentKind: ctx.agentKind === 'codex' ? 'codex' : ctx.agentKind === 'pi' ? 'pi' : 'claude-code',workingDir: ctx.workingDir,+ ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}),sessionId: ctx.sessionId,vendorOptions: ctx.vendorOptions,}),diff --git a/packages/lizi-mcps/src/session-context.ts b/packages/lizi-mcps/src/session-context.tsindex 31a4d80f7f..07df091213 100644--- a/packages/lizi-mcps/src/session-context.ts+++ b/packages/lizi-mcps/src/session-context.ts@@ -15,8 +15,41 @@ export function getLiziMcpSessionContext(): LiziMcpSessionContext | undefined {return storage.getStore();}+function withoutSessionAttribution<T extends LiziMcpSessionContext>(fallback: T): T {+ return {+ ...fallback,+ workingDir: '',+ sessionId: undefined,+ sessionInstanceId: undefined,+ remoteHostId: undefined,+ vendorOptions: undefined,+ };+}+export function resolveLiziMcpSessionContext<T extends LiziMcpSessionContext>(fallback: T,): T {+ // Host-provided accessors carry the provenance of this MCP server. Claude+ // returns its per-session closure; Codex / Pi resolve the current request.+ // An accessor that cannot resolve a context is authoritative too: returning+ // the captured fallback (or an unrelated ambient ALS store) would silently+ // impersonate another session, so strip all session attribution instead.+ if (fallback.getSessionContext) {+ return (fallback.getSessionContext() as T | undefined) ?? withoutSessionAttribution(fallback);+ }++ // Backward compatibility for direct package consumers that construct bridge+ // servers without the newer explicit accessor. A concrete captured context+ // is still authoritative; only an unmistakably empty bridge placeholder may+ // consult the ambient ALS store.+ if (+ fallback.sessionId ||+ fallback.sessionInstanceId ||+ fallback.workingDir ||+ fallback.remoteHostId ||+ (fallback.vendorOptions && Object.keys(fallback.vendorOptions).length > 0)+ ) {+ return fallback;+ }return (storage.getStore() as T | undefined) ?? fallback;}diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.tsindex 5e2066bac9..231eced6f3 100644--- a/packages/lizi-mcps/src/types.ts+++ b/packages/lizi-mcps/src/types.ts@@ -732,6 +732,15 @@ export interface AndroidMcpDeps {export interface LiziMcpSessionContext {agentKind: string;workingDir: string;+ /**+ * 当前 tool-call 的权威 session ctx accessor。+ *+ * Claude in-process 路径返回闭包绑定的当前 session;Codex / Pi bridge+ * 路径从请求作用域恢复当前 session。只要提供了本 accessor,它就是唯一可信+ * 来源:返回 undefined 表示本次调用无法确认归属,调用方必须 fail closed,+ * 不能再回落到构建 server 时捕获的 ctx 或环境中的其它 AsyncLocalStorage store。+ */+ getSessionContext?: () => LiziMcpSessionContext | undefined;/*** SSH remote 会话的 host id (本地会话缺省)。workingDir 此时是远端机器上的* 路径字符串 — cindy_memory 等按 workdir 分区的工具必须用