/** * IPC MCP Handlers — MCP 服务管理域(P2-9 从 handlers.ts 拆分) */ import { ipcMain } from 'electron'; import type { IPCContext } from './context'; import log from 'electron-log'; export function registerMCPHandlers(ctx: IPCContext): void { const { mcpManager } = ctx; ipcMain.handle('mcp:listServers', async () => { return mcpManager.getServerStates(); }); ipcMain.handle( 'mcp:addServer', async ( _event, config: { name: string; transport: string; command?: string; args?: string[]; url?: string }, ) => { // M-38 修复: 完整参数校验,防止字段缺失或类型不符导致异常行为 if (!config || typeof config !== 'object') { return { success: false, error: 'Invalid config' }; } if (typeof config.name !== 'string' || !config.name.trim()) { return { success: false, error: 'Server name is required' }; } // M-5 修复: transport 运行时校验(替代 as 断言) // v0.4.1: 新增 'streamable-http' 传输方式 if ( config.transport !== 'stdio' && config.transport !== 'sse' && config.transport !== 'streamable-http' ) { return { success: false, error: `Invalid transport: ${config.transport}. Must be 'stdio', 'sse', or 'streamable-http'`, }; } // stdio 类型必须有 command if ( config.transport === 'stdio' && (typeof config.command !== 'string' || !config.command.trim()) ) { return { success: false, error: 'command is required for stdio transport' }; } // sse / streamable-http 类型必须有合法 url if (config.transport === 'sse' || config.transport === 'streamable-http') { if (typeof config.url !== 'string' || !config.url.trim()) { return { success: false, error: `url is required for ${config.transport} transport` }; } try { new URL(config.url); } catch { return { success: false, error: 'Invalid url format' }; } } try { await mcpManager.addServer({ name: config.name, transport: config.transport, // 已校验,无需断言 command: config.command, args: config.args, url: config.url, enabled: true, }); log.info(`MCP server added: ${config.name}`); return { success: true }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : String(error) }; } }, ); ipcMain.handle('mcp:removeServer', async (_event, name: string) => { // M-38 修复: name 校验 if (typeof name !== 'string' || !name.trim()) { return { success: false, error: 'Invalid server name' }; } try { await mcpManager.removeServer(name); return { success: true }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : String(error) }; } }); ipcMain.handle('mcp:toggleServer', async (_event, name: string, enabled: boolean) => { // M-38 修复: name 和 enabled 校验 if (typeof name !== 'string' || !name.trim()) { return { success: false, error: 'Invalid server name' }; } if (typeof enabled !== 'boolean') { return { success: false, error: 'Invalid enabled flag' }; } try { await mcpManager.toggleServer(name, enabled); return { success: true }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : String(error) }; } }); }