fix(ApiService): improve error handling when fetching tools from MCP servers (#7340)

- Added error handling for tool fetching to log errors and return an empty array if a server fails to respond.
- Changed from Promise.all to Promise.allSettled to ensure all tool fetching attempts are accounted for, filtering out any rejected promises.
This commit is contained in:
SuYao 2025-06-19 12:02:03 +08:00 committed by GitHub
parent 11a93b932a
commit f42054ed03

View File

@ -254,12 +254,20 @@ async function fetchExternalTool(
const enabledMCPs = assistant.mcpServers
if (enabledMCPs && enabledMCPs.length > 0) {
try {
const toolPromises = enabledMCPs.map(async (mcpServer) => {
const tools = await window.api.mcp.listTools(mcpServer)
return tools.filter((tool: any) => !mcpServer.disabledTools?.includes(tool.name))
const toolPromises = enabledMCPs.map<Promise<MCPTool[]>>(async (mcpServer) => {
try {
const tools = await window.api.mcp.listTools(mcpServer)
return tools.filter((tool: any) => !mcpServer.disabledTools?.includes(tool.name))
} catch (error) {
console.error(`Error fetching tools from MCP server ${mcpServer.name}:`, error)
return []
}
})
const results = await Promise.all(toolPromises)
mcpTools = results.flat() // Flatten the array of arrays
const results = await Promise.allSettled(toolPromises)
mcpTools = results
.filter((result): result is PromiseFulfilledResult<MCPTool[]> => result.status === 'fulfilled')
.map((result) => result.value)
.flat()
} catch (toolError) {
console.error('Error fetching MCP tools:', toolError)
}