Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): keep SSH tool policy stable for running sessions (#384)
qsoyq8c810c9cf526
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 5b0d5b6cfa..ab4b482b2d 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -206,11 +206,8 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcgetPool: async () => (await import('../remote-ssh/index.js')).getRemoteSshPoolHydrated(),ensureReady: async (id: string) =>(await import('../remote-ssh/index.js')).ensureRemoteHostReady(id),- // 运行时门控(tool-call 时刻):Codex 共享 bridge 构建期 workingDir 为空,- // 下方 provider isEnabled wrap 的构建期检查覆盖不到项目级禁用,ssh_exec- // 这种远端执行工具必须在调用时刻按真实会话 workdir 再查一次 registry;- // workingDir undefined = 无会话上下文,回落全局开关判定。- isEnabledForWorkdir: (workingDir) => pluginRegistry.isEnabled('ssh', workingDir),+ // 普通工具策略在 Claude runtime / Codex thread 创建时冻结。不要在 tool-call+ // 时重新读取 registry,否则运行中的工具清单与执行权限会随 Settings 分叉。logger: createLogger('mcp/cindy_ssh'),},memory: {diff --git a/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.tsindex d2d4029c1b..ddc676ca82 100644--- a/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/cindy_sshMcpServer.test.ts@@ -7,7 +7,7 @@* 2. e2e smoke:真 McpServer + InMemoryTransport,走通 list_tools → call_tool。*/-import { describe, it, expect, beforeEach } from 'vitest';+import { describe, it, expect, beforeEach, vi } from 'vitest';import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';@@ -408,14 +408,13 @@ describe('registry semantics', () => {});});-// ── runtime plugin gate (tool-call 时刻,PR #874 review:Codex bridge 空 ctx) ──+// ── session-stable plugin policy ───────────────────────────────────────────-describe('runtime plugin gate via isEnabledForWorkdir', () => {+describe('session-stable plugin policy', () => {async function makeServerClient(deps: SshMcpDeps,- sessionCtx?: { agentKind: 'claude-code' | 'codex'; workingDir: string },): Promise<{ client: Client; cleanup: () => Promise<void> }> {- const server = createSshMcpServer(deps, sessionCtx);+ const server = createSshMcpServer(deps);const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();const client = new Client({ name: 'gate-test-client', version: '0.0.0' });await Promise.all([server.connect(serverTx), client.connect(clientTx)]);@@ -428,51 +427,18 @@ describe('runtime plugin gate via isEnabledForWorkdir', () => {};}- it('disabled workdir → call_tool returns PLUGIN_DISABLED without touching registry', async () => {- const { pool, execCalls } = makeFakePool([snapshot({ id: 'web-1' })]);- const { deps } = makeDeps(pool, { isEnabledForWorkdir: () => false });- const { client, cleanup } = await makeServerClient(deps, {- agentKind: 'claude-code',- workingDir: 'E:/proj',- });-- const result = await client.callTool({- name: 'call_tool',- arguments: { name: 'ssh_exec', args: { host: 'web-1', command: 'true' } },- });- const payload = JSON.parse(- (result.content as Array<{ type: string; text: string }>)[0].text,- ) as Record<string, unknown>;- expect(payload.errorCode).toBe('PLUGIN_DISABLED');- expect(execCalls).toHaveLength(0);- await cleanup();- });-- it('passes the closure workingDir to the gate; empty workingDir maps to undefined', async () => {- const seen: Array<string | undefined> = [];- const { pool } = makeFakePool([snapshot({ id: 'web-1' })]);- const { deps } = makeDeps(pool, {- isEnabledForWorkdir: (wd) => {- seen.push(wd);- return true;- },- });-- const bound = await makeServerClient(deps, { agentKind: 'claude-code', workingDir: 'E:/proj' });- await bound.client.callTool({ name: 'call_tool', arguments: { name: 'ssh_list_hosts', args: {} } });- await bound.cleanup();-- const unbound = await makeServerClient(deps); // 无 sessionCtx = Codex bridge 构建期形态- await unbound.client.callTool({ name: 'call_tool', arguments: { name: 'ssh_list_hosts', args: {} } });- await unbound.cleanup();-- expect(seen).toEqual(['E:/proj', undefined]);- });-- it('gate absent (deps 未注入) keeps legacy pass-through', async () => {+ it('does not re-read host plugin settings after the server is created', async () => {const { pool } = makeFakePool([snapshot({ id: 'web-1' })]);const { deps } = makeDeps(pool);- const { client, cleanup } = await makeServerClient(deps);+ const liveGate = vi.fn(() => false);+ // Simulate the legacy host dependency without adding it back to SshMcpDeps.+ // A running server must rely on the policy frozen by its host runtime.+ const legacyDeps = {+ ...deps,+ isEnabledForWorkdir: liveGate,+ };+ const { client, cleanup } = await makeServerClient(legacyDeps);+const result = await client.callTool({name: 'call_tool',arguments: { name: 'ssh_list_hosts', args: {} },@@ -481,6 +447,7 @@ describe('runtime plugin gate via isEnabledForWorkdir', () => {(result.content as Array<{ type: string; text: string }>)[0].text,) as { ok: boolean };expect(payload.ok).toBe(true);+ expect(liveGate).not.toHaveBeenCalled();await cleanup();});});diff --git a/packages/lizi-mcps/src/cindy_sshMcpServer.ts b/packages/lizi-mcps/src/cindy_sshMcpServer.tsindex ceac1215c3..173ecca254 100644--- a/packages/lizi-mcps/src/cindy_sshMcpServer.ts+++ b/packages/lizi-mcps/src/cindy_sshMcpServer.ts@@ -31,16 +31,7 @@ import {registerSshHostStatusTool,registerSshListHostsTool,} from './ssh/index.js';-import { resolveLiziMcpSessionContext } from './session-context.js';-import type { LiziMcpSessionContext, SshMcpDeps } from './types.js';--/** Per-session 上下文(与 SchedulerMcpSessionCtx 同形,当前仅用于日志归因)。 */-export interface SshMcpSessionCtx {- agentKind: 'claude-code' | 'codex';- workingDir: string;- sessionId?: string;- vendorOptions?: Record<string, unknown>;-}+import type { SshMcpDeps } from './types.js';const D_LIST_TOOLS ='探索 cindy_ssh 可用工具(渐进式发现入口)。不传 category → 返回所有类目+每个类目工具数量。' +@@ -57,7 +48,6 @@ const D_CALL_TOOL ='`SSH_CONNECT_FAILED` = 连接/执行失败;' +'`EXEC_TIMEOUT` = 命令超时(长任务改 nohup 后台跑再轮询);' +'`INVALID_ARGS` = zod schema 校验失败(返回 schema 自纠);' +- '`PLUGIN_DISABLED` = 当前项目已关闭 SSH Remote 插件,不要重试,转告用户去设置开启;' +'`INTERNAL` = 工具内部错误(如连接池不可用),不宜盲目重试,把 hint 转告用户。';const CATEGORY_ENUM = ['ssh'] as const;@@ -115,8 +105,6 @@ function registerListToolsEntry(server: McpServer, registry: SshToolRegistry): vfunction registerCallToolEntry(server: McpServer,registry: SshToolRegistry,- deps: SshMcpDeps,- getSessionContext: () => LiziMcpSessionContext,): void {server.tool('call_tool',@@ -128,20 +116,6 @@ function registerCallToolEntry(args: jsonObjectArg('工具参数(JSON 对象)。不确定 schema 时可先传 {} 触发错误反馈。'),},async ({ name, args }) => {- // 运行时插件门控:必须在 tool-call 时刻按真实会话 workingDir 判定,不能只- // 靠 host 层构建期检查——Codex 共享 bridge 以空 workingDir 构建 server,- // AsyncLocalStorage 在此刻才恢复真实 ctx,构建期检查会漏掉项目级禁用。- // 空 workingDir 时 host 回落全局开关判定(见 SshMcpDeps.isEnabledForWorkdir)。- if (deps.isEnabledForWorkdir) {- const ctx = getSessionContext();- const workingDir = ctx.workingDir.trim() !== '' ? ctx.workingDir : undefined;- if (!deps.isEnabledForWorkdir(workingDir)) {- return errorPayload(- 'PLUGIN_DISABLED',- '当前项目已关闭 SSH Remote 插件(可在主界面侧边栏「插件」中开启,或在项目 .claude/settings.json 的 xdtMaker.builtinTools.ssh 中开启)。不要重试,转告用户如需使用请先开启。',- );- }- }return registry.call(name, args);},);@@ -149,10 +123,7 @@ function registerCallToolEntry(// ── Factory ────────────────────────────────────────────────────────────────-export function createSshMcpServer(- deps: SshMcpDeps,- sessionCtx?: SshMcpSessionCtx,-): McpServer {+export function createSshMcpServer(deps: SshMcpDeps): McpServer {const server = new McpServer({name: 'cindy_ssh',version: '1.0.0',@@ -160,22 +131,13 @@ export function createSshMcpServer(const registry = new SshToolRegistry();- // cc 路径取闭包 ctx;codex 路径由 AsyncLocalStorage 在工具调用时补回当前- // thread 的真实 ctx(共享 bridge 构建期 ctx 是空的)。- const fallbackCtx: LiziMcpSessionContext = sessionCtx ?? {- agentKind: 'claude-code',- workingDir: '',- };- const getSessionContext = (): LiziMcpSessionContext =>- resolveLiziMcpSessionContext(fallbackCtx);-// 注册顺序 = list_tools 里的位次。读优先 → 写在后。registerSshListHostsTool(registry, deps);registerSshHostStatusTool(registry, deps);registerSshExecTool(registry, deps);registerListToolsEntry(server, registry);- registerCallToolEntry(server, registry, deps, getSessionContext);+ registerCallToolEntry(server, registry);return server;}diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.tsindex a2920d043d..2da177944b 100644--- a/packages/lizi-mcps/src/providers.ts+++ b/packages/lizi-mcps/src/providers.ts@@ -289,17 +289,12 @@ export function createLiziMcpProviders(name: 'cindy_ssh',// 无 isEnabled 门控:plugin 系统已在 host 层(mcp-providers.ts wrap)按// plugin id 'ssh' 包了 isEnabled 检查,这里再加就是双重门(同 cindy_orca)。- // ctx 当前仅日志归因用;工具本身不依赖 workingDir,Codex bridge 空 ctx- // 也能正常工作。- toClaudeSdkConfig: (ctx) => ({+ // 启用策略由 host 在 Agent runtime / Codex thread 创建时冻结;SSH server+ // 本身不读取 workingDir 或实时设置。+ toClaudeSdkConfig: () => ({type: 'sdk',name: 'cindy_ssh',- instance: createSshMcpServer(opts.ssh!, {- agentKind: ctx.agentKind === 'codex' ? 'codex' : 'claude-code',- workingDir: ctx.workingDir,- sessionId: ctx.sessionId,- vendorOptions: ctx.vendorOptions,- }),+ instance: createSshMcpServer(opts.ssh!),}),});}diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.tsindex c126c7ed24..813770934a 100644--- a/packages/lizi-mcps/src/types.ts+++ b/packages/lizi-mcps/src/types.ts@@ -337,19 +337,12 @@ export interface SshPoolLike {* - ensureReady(id):不存在 / 连接失败时抛错;错误 message 以 `[CODE] ...`* 前缀编码(desktop throwIpcError 协议),tool 层用 classifySshError* best-effort 提取。+ * - 插件启用策略由 host 在 Agent runtime / Codex thread 创建时冻结;这里不得+ * 注入调用时读取设置的门控,否则工具暴露状态与执行权限会在运行中分叉。*/export interface SshMcpDeps {getPool(): Promise<SshPoolLike>;ensureReady(id: string): Promise<void>;- /**- * 运行时插件门控(tool-call 时刻,按当前会话 workingDir 判定)。- * 为什么不能只靠 host 层构建期的 provider isEnabled wrap:Codex 共享 bridge- * 用空 workingDir 构建 server,真实会话 ctx 由 AsyncLocalStorage 在工具调用- * 时才恢复——构建期检查会跳过项目级禁用,导致关掉 ssh 插件的项目在 Codex- * 会话里仍能调 ssh_exec(PR #874 review)。workingDir 为 undefined 时 host- * 应回落到全局开关判定。缺省 = 不做运行时门控(仅依赖构建期检查)。- */- isEnabledForWorkdir?: (workingDir: string | undefined) => boolean;logger?: LiziMcpLogger;}