Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): inject host dependencies and use registered MCP catalog
zqchris91c874ea19c5
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex c6564ea8a7..6de45f8f92 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -6,9 +6,13 @@ import { rmSync } from 'node:fs';import { drizzle } from 'drizzle-orm/better-sqlite3';import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';import { BOT_TEMPLATE_PRESET_IDENTITIES } from '../../../../shared/botTemplatePreset';-import { findBotCapabilities, selectBotCapability } from '../../../maker-ipc/botCapabilityService';+import { createBotCapabilityService } from '../../../maker-ipc/botCapabilityService';import { buildBotMcpCatalog } from '../../../maker-host/botMcpCatalog';import { CustomMcpProvider } from '../../../mcp-integrations/custom-mcp-provider';+import type { McpProvider } from '@cindy/maker-core';+import type { CustomMcpConfig } from '../../../../shared/customMcp';+import { getMaker, getPluginRegistry, isBotToolsetAvailable } from '../../../maker-host/index';+import { getBuiltinMcpServerNames, refreshCustomMcpProviders, registerCustomMcpArrays, resetCustomMcpRegistry } from '../../../mcp-integrations/custom-mcp-registry';import {botDelegations,@@ -58,6 +62,8 @@ const h = await vi.hoisted(async () => {requestRuntimeRefresh: vi.fn(),seedTemplateSkills: vi.fn(async () => ({ completedNow: true, skills: [] })),toolsetsAvailable: false,+ customMcpConfigs: [] as CustomMcpConfig[],+ mcpProviders: [] as McpProvider[],ownerScopeKey: 'owner-a:1',ownerBoundaryPending: false,});@@ -96,8 +102,9 @@ vi.mock('../../../git-snapshot/projectGitBootstrap.js', () => ({vi.mock('../../../maker-host/git-safety-settings-store.js', () => ({readGitSafetySettings: () => ({ autoSnapshotEnabled: true }),}));-vi.mock('../../../maker-host/custom-mcp-store.js', () => ({- listCustomMcpServers: async () => [{ id: 'shared-docs', name: 'Shared Docs', transport: 'http', url: 'https://example.invalid/private', headers: { Authorization: 'FAKE_SECRET' } }],+vi.mock('../../../maker-host/custom-mcp-store.js', async (importOriginal) => ({+ ...await importOriginal<typeof import('../../../maker-host/custom-mcp-store.js')>(),+ listCustomMcpServers: async () => h.customMcpConfigs,}));vi.mock('../../../maker-host/index.js', () => ({getMaker: () => ({ getSession: h.getSession, listAgentSkills: async () => ({ skills: [{ name: 'release-check', description: 'Release checklist', enabled: true }] }) }),@@ -400,8 +407,23 @@ async function invoke(channel: string, body: unknown): Promise<any> {if (!handler) throw new Error(`${channel} handler not registered`);return handler({}, body);}+const { list: findBotCapabilities, select: selectBotCapability } = createBotCapabilityService({+ getMaker, getPluginRegistry, isBotToolsetAvailable,+ listMcpServers: async ({ agentKind }) => buildBotMcpCatalog({+ agentKind, providers: h.mcpProviders, builtinNames: getBuiltinMcpServerNames(),+ customServers: h.customMcpConfigs.map((config) => ({ ...config, updatedAt: 1 })),+ }),+});+beforeEach(async () => {h.toolsetsAvailable = false;+ h.customMcpConfigs = [{ id: 'shared-docs', name: 'Shared Docs', transport: 'http', url: 'https://example.invalid/private', headers: { Authorization: 'FAKE_SECRET' } }];+ h.mcpProviders = [+ { name: 'cindy_helper', toClaudeSdkConfig: () => ({ type: 'sdk' }) },+ new CustomMcpProvider(h.customMcpConfigs[0]!, () => null),+ ];+ resetCustomMcpRegistry();+ registerCustomMcpArrays(h.mcpProviders);vi.clearAllMocks();h.handlers.clear();h.nextSession = 0;@@ -1616,6 +1638,34 @@ describe('Bot canonical Session lifecycle', () => {await expect(findBotCapabilities({ callerSessionId, kind: 'skill' })).resolves.toMatchObject({ capabilities: [{ id: 'release-check', joined: true }] });});+ it.each(['cindy_helper', '__proto__', 'constructor', 'bad_header'])('rejects MCP %s quarantined by the actual registry while keeping its saved reference removable', async (id) => {+ h.customMcpConfigs.push({+ id, name: 'Legacy MCP', transport: 'http', url: 'https://example.invalid/legacy',+ headers: id === 'bad_header' ? { 'X-Name': '中文' } : {},+ });+ await refreshCustomMcpProviders();+ expect(h.mcpProviders.filter((provider) => provider instanceof CustomMcpProvider).map((provider) => provider.name)).toEqual(['shared-docs']);+ await invoke('local-db:bots:update', {+ id: 'bot-1', capabilities: { mcpServers: [id], mcpMode: 'allowlist' },+ });+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 2,+ });+ const input = { callerSessionId: created.session.id, kind: 'mcp' as const };+ const discovered = await findBotCapabilities(input);+ expect(discovered).toMatchObject({+ ok: true, capabilities: expect.arrayContaining([+ { id, name: 'Legacy MCP', description: 'http', available: false, joined: true },+ { id: 'shared-docs', name: 'Shared Docs', description: 'http', available: true, joined: false },+ ]),+ });+ expect(JSON.stringify(discovered)).not.toMatch(/FAKE_SECRET|example.invalid|Authorization/);+ await expect(selectBotCapability({ ...input, id, joined: true })).resolves.toMatchObject({ ok: false, errorCode: 'CAPABILITY_UNAVAILABLE' });+ expect(h.sqlite!.prepare('SELECT current_version FROM bot_profiles WHERE id = ?').pluck().get('bot-1')).toBe(2);+ await expect(selectBotCapability({ ...input, id, joined: false })).resolves.toMatchObject({ ok: true, joined: false });+ await expect(selectBotCapability({ ...input, id: 'shared-docs', joined: true })).resolves.toMatchObject({ ok: true, joined: true });+ });+it('revalidates saved MCP transports on fallback and restores them when switching back', async () => {const configs = (['http', 'sse'] as const).map((transport) => ({id: transport, name: transport, transport, url: `https://example.invalid/${transport}`,@@ -3723,6 +3773,7 @@ describe('Bot Session task end-to-end runtime', () => {});afterAll(() => {+ resetCustomMcpRegistry();h.sqlite?.close();rmSync(h.userDataDir, { recursive: true, force: true });});diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 05bb88a324..e073b11f81 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -56,6 +56,7 @@ import {} from '../maker-ipc/botProfileRuntime.js';import { collectBotOwnSkillMounts } from '../maker-ipc/botSkillService.js';import { buildBotMcpCatalog } from './botMcpCatalog.js';+import { createBotCapabilityService } from '../maker-ipc/botCapabilityService.js';import {botProfileDir,ensureBotContentDirs,@@ -839,7 +840,22 @@ export function getMaker(): Maker {return getIOSSimulatorPluginAccessDecision(workingDir);};+ // These callbacks run after all three runtime provider arrays are registered.+ const listBotRuntimeMcpServers: NonNullable<BotProfileRuntimeDeps['listMcpServers']> = async ({ agentKind }) => {+ const providers = agentKind === 'claude-code' ? claudeMcpProviders+ : agentKind === 'codex' ? codexMcpProviders : piMcpProviders;+ return buildBotMcpCatalog({+ agentKind,+ providers,+ builtinNames: getBuiltinMcpServerNames(),+ customServers: await listCustomMcpRuntimeGenerations(),+ });+ };const makerMemoryProviderDeps = {+ botCapabilities: createBotCapabilityService({+ getMaker, getPluginRegistry, isBotToolsetAvailable,+ listMcpServers: listBotRuntimeMcpServers,+ }),createMediaDownloadContext: (sessionId: string, sessionInstanceId: string) => {const session = _maker?.getSession(sessionId);if (!session || session.instanceId !== sessionInstanceId) return undefined;@@ -2293,20 +2309,7 @@ export function getMaker(): Maker {});return result.skills;},- listMcpServers: async ({ agentKind }) => {- const providers =- agentKind === 'claude-code'- ? claudeMcpProviders- : agentKind === 'codex'- ? codexMcpProviders- : piMcpProviders;- return buildBotMcpCatalog({- agentKind,- providers,- builtinNames: getBuiltinMcpServerNames(),- customServers: await listCustomMcpRuntimeGenerations(),- });- },+ listMcpServers: listBotRuntimeMcpServers,listToolsets: async ({ botId, agentKind, workingDir, remoteHostId }) => {const registry = getPluginRegistry();return Promise.all(diff --git a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts b/apps/desktop/src/main/maker-ipc/botCapabilityService.tsindex 11831eb0f0..b47908b67c 100644--- a/apps/desktop/src/main/maker-ipc/botCapabilityService.ts+++ b/apps/desktop/src/main/maker-ipc/botCapabilityService.ts@@ -5,10 +5,20 @@ import { updateBotProfile } from '../localDb/ipc/bots.js';import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';import { listCustomMcpServers } from '../maker-host/custom-mcp-store.js';import { BOT_BASELINE_PLUGIN_IDS } from '../maker-host/plugins/types.js';+import type { Maker } from '@cindy/maker-core';+import type { PluginRegistry } from '../maker-host/plugins/plugin-registry.js';+import type { BotToolsetContext } from '../../shared/botRemoteCapabilities.js';+import type { BotProfileRuntimeDeps } from './botProfileRuntime.js';type Kind = 'skill' | 'mcp' | 'toolset';type Input = { callerSessionId: string; kind: Kind };type Entry = { id: string; name: string; description: string; available: boolean; joined: boolean };+interface BotCapabilityServiceDeps {+ getMaker: () => Pick<Maker, 'getSession' | 'listAgentSkills'>;+ getPluginRegistry: () => Pick<PluginRegistry, 'getPlugins' | 'getEnableState'>;+ isBotToolsetAvailable: (input: BotToolsetContext & { toolsetId: string }) => boolean;+ listMcpServers: NonNullable<BotProfileRuntimeDeps['listMcpServers']>;+}const fields: Record<Kind, { list: string; mode: string }> = {skill: { list: 'skills', mode: 'skillMode' },mcp: { list: 'mcpServers', mode: 'mcpMode' },@@ -73,11 +83,11 @@ async function context(callerSessionId: string) {return { ...row, config, assertOwner };}-async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>): Promise<Entry[]> {+async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>, deps: BotCapabilityServiceDeps): Promise<Entry[]> {const joined = new Set(strings(ctx.config[fields[input.kind].list]).filter((id) => input.kind !== 'toolset' || !BOT_BASELINE_PLUGIN_IDS.has(id),));- const { getMaker, getPluginRegistry, isBotToolsetAvailable } = await import('../maker-host/index.js');+ const { getMaker, getPluginRegistry, isBotToolsetAvailable } = deps;const agentKind =getMaker().getSession(input.callerSessionId)?.agentKind ??(ctx.agentKind === 'cc' ? 'claude-code' : ctx.agentKind === 'pi' ? 'pi' : 'codex');@@ -95,12 +105,18 @@ async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>):available: skill.enabled !== false && skill.runtimeStatus !== 'failed',}));} else if (input.kind === 'mcp') {+ const runtimeCatalog = await deps.listMcpServers({+ agentKind, workingDir, remoteHostId: ctx.remoteHostId ?? undefined,+ });+ const available = new Set(runtimeCatalog+ .filter((entry) => entry.source === 'custom' && entry.available !== false)+ .map((entry) => entry.name));// Project only display metadata. URLs, headers and tokens never enter tool results.items = (await listCustomMcpServers()).map((mcp) => ({id: mcp.id,name: mcp.name,description: mcp.transport,- available: agentKind !== 'codex' || mcp.transport !== 'sse',+ available: available.has(mcp.id),}));} else {const registry = getPluginRegistry();@@ -133,11 +149,11 @@ async function catalog(input: Input, ctx: Awaited<ReturnType<typeof context>>):return result;}-export async function findBotCapabilities(input: Input & { query?: string }) {+async function findBotCapabilities(input: Input & { query?: string }, deps: BotCapabilityServiceDeps) {try {const ctx = await context(input.callerSessionId);const query = input.query?.trim().toLocaleLowerCase() ?? '';- const capabilities = (await catalog(input, ctx)).filter(+ const capabilities = (await catalog(input, ctx, deps)).filter((item) =>!query || `${item.id} ${item.name} ${item.description}`.toLocaleLowerCase().includes(query),);@@ -151,7 +167,7 @@ export async function findBotCapabilities(input: Input & { query?: string }) {}}-export async function selectBotCapability(input: Input & { id: string; joined: boolean }) {+async function selectBotCapability(input: Input & { id: string; joined: boolean }, deps: BotCapabilityServiceDeps) {try {const ctx = await context(input.callerSessionId);if (input.kind === 'toolset' && BOT_BASELINE_PLUGIN_IDS.has(input.id)) {@@ -164,7 +180,7 @@ export async function selectBotCapability(input: Input & { id: string; joined: bconst field = fields[input.kind];const previous = strings(ctx.config[field.list]);if (input.joined) {- const item = (await catalog(input, ctx)).find((entry) => entry.id === input.id);+ const item = (await catalog(input, ctx, deps)).find((entry) => entry.id === input.id);if (!item?.available)return {ok: false as const,@@ -190,3 +206,11 @@ export async function selectBotCapability(input: Input & { id: string; joined: b};}}++/** Host callbacks are bound at initialization, without importing the host singleton. */+export function createBotCapabilityService(deps: BotCapabilityServiceDeps) {+ return {+ list: (input: Input & { query?: string }) => findBotCapabilities(input, deps),+ select: (input: Input & { id: string; joined: boolean }) => selectBotCapability(input, deps),+ };+}diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.tsindex 5ea365f90a..32564ce992 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts@@ -103,6 +103,11 @@ import {} from '../../maker-ipc/collabSendOutcome.js';import { createDesktopMcpProviders } from '../mcp-providers.js';+const botCapabilities = {+ list: vi.fn(async () => ({ ok: true as const, capabilities: [] })),+ select: vi.fn(async () => ({ ok: true as const, joined: true, effective: 'next-turn' as const })),+};+function collabMeta(overrides: Record<string, unknown> = {}) {return {source: 'maker-ipc/collab',@@ -163,6 +168,7 @@ describe('collab send outcome semantics', () => {it('keeps cindy_orca registered when project policy is disabled at session startup', () => {const providers = createDesktopMcpProviders({+ botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,pluginRegistry: { isEnabled: () => false } as never,@@ -170,6 +176,7 @@ describe('collab send outcome semantics', () => {invokeRemote: vi.fn(),});const orcaProvider = providers.find((provider) => provider.name === 'cindy_orca');+ expect(mockState.capturedProvidersConfig?.xdtHelper).toMatchObject({ botCapabilities });const iosSimulatorProvider = providers.find((provider) => provider.name === 'cindy_ios_simulator',);@@ -334,6 +341,7 @@ describe('collab send outcome semantics', () => {});createDesktopMcpProviders({+ botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,pluginRegistry: { isEnabled: () => true } as never,@@ -383,6 +391,7 @@ describe('collab send outcome semantics', () => {});createDesktopMcpProviders({+ botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,pluginRegistry: { isEnabled: () => true } as never,@@ -443,6 +452,7 @@ describe('collab send outcome semantics', () => {});createDesktopMcpProviders({+ botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,pluginRegistry: { isEnabled: () => true } as never,@@ -500,6 +510,7 @@ describe('collab send outcome semantics', () => {});createDesktopMcpProviders({+ botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,pluginRegistry: { isEnabled: () => true } as never,@@ -536,6 +547,7 @@ describe('collab send outcome semantics', () => {});createDesktopMcpProviders({+ botCapabilities,getMakerMemoryManager: vi.fn(),lspPool: {} as never,pluginRegistry: { isEnabled: () => true } as never,diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 3da35a0d52..3d9f3272bb 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -1,4 +1,4 @@-import { findBotCapabilities, selectBotCapability } from '../maker-ipc/botCapabilityService.js';+import type { createBotCapabilityService } from '../maker-ipc/botCapabilityService.js';import { join as pathJoin } from 'node:path';import { and, eq } from 'drizzle-orm';@@ -78,6 +78,7 @@ import {import { botSessionLinks, sessions } from '../localDb/schema.js';export interface DesktopMcpProvidersDeps {+ botCapabilities: ReturnType<typeof createBotCapabilityService>;createMediaDownloadContext?: CindyGhostsHostDeps['createMediaDownloadContext'];/** 当前 Desktop 版本,供 Forge 为具体插件包生成默认 minCindyVersion。 */getAppVersion?: () => string;@@ -602,7 +603,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc},},// 伙伴自己沉淀的真技能。归属同样由 callerSessionId 反查,工具面不收 botId。- botCapabilities: { list: findBotCapabilities, select: selectBotCapability },+ botCapabilities: deps.botCapabilities,botSkills: {save: (params) => saveBotSkillForSession(params),list: (params) => listBotSkillsForSession(params),