cherry-studio/src/renderer/src/hooks/useMCPServers.ts
kangfenmao 8bfbbd497c refactor: streamline MCP service handling and improve IPC registration
* Refactored MCPService to implement a singleton pattern for better instance management.
* Updated IPC registration to utilize the new getMcpInstance method for handling MCP-related requests.
* Removed redundant IPC handlers from the main index file and centralized them in the ipc module.
* Added background throttling option in WindowService configuration to enhance performance.
* Introduced delays in MCPToolsButton to optimize resource and prompt fetching after initial load.
2025-05-18 22:04:56 +08:00

50 lines
2.0 KiB
TypeScript

import { createSelector } from '@reduxjs/toolkit'
import store, { useAppDispatch, useAppSelector } from '@renderer/store'
import { addMCPServer, deleteMCPServer, setMCPServers, updateMCPServer } from '@renderer/store/mcp'
import { MCPServer } from '@renderer/types'
import { IpcChannel } from '@shared/IpcChannel'
const ipcRenderer = window.electron.ipcRenderer
// Listen for server changes from main process
ipcRenderer.on(IpcChannel.Mcp_ServersChanged, (_event, servers) => {
store.dispatch(setMCPServers(servers))
})
ipcRenderer.on(IpcChannel.Mcp_AddServer, (_event, server: MCPServer) => {
store.dispatch(addMCPServer(server))
})
const selectMcpServers = (state) => state.mcp.servers
const selectActiveMcpServers = createSelector([selectMcpServers], (servers) =>
servers.filter((server) => server.isActive)
)
export const useMCPServers = () => {
const mcpServers = useAppSelector(selectMcpServers)
const activedMcpServers = useAppSelector(selectActiveMcpServers)
const dispatch = useAppDispatch()
return {
mcpServers,
activedMcpServers,
addMCPServer: (server: MCPServer) => dispatch(addMCPServer(server)),
updateMCPServer: (server: MCPServer) => dispatch(updateMCPServer(server)),
deleteMCPServer: (id: string) => dispatch(deleteMCPServer(id)),
setMCPServerActive: (server: MCPServer, isActive: boolean) => dispatch(updateMCPServer({ ...server, isActive })),
getActiveMCPServers: () => mcpServers.filter((server) => server.isActive),
updateMcpServers: (servers: MCPServer[]) => dispatch(setMCPServers(servers))
}
}
export const useMCPServer = (id: string) => {
const server = useAppSelector((state) => (state.mcp.servers || []).find((server) => server.id === id))
const dispatch = useAppDispatch()
return {
server,
updateMCPServer: (server: MCPServer) => dispatch(updateMCPServer(server)),
setMCPServerActive: (server: MCPServer, isActive: boolean) => dispatch(updateMCPServer({ ...server, isActive })),
deleteMCPServer: (id: string) => dispatch(deleteMCPServer(id))
}
}