fix: 修复MCP服务器测试失败时返回成功的问题

This commit is contained in:
Your Name 2026-03-24 09:38:12 +08:00
parent 97638d035f
commit f8526657f1
2 changed files with 18 additions and 3 deletions

View File

@ -231,13 +231,14 @@ async def test_mcp_server(
await get_server_or_404(db, name)
try:
tools = await get_all_mcp_tools(name)
tools = await get_all_mcp_tools(name, raise_on_error=True)
return {
"success": True,
"message": f"连接成功,共发现 {len(tools)} 个工具",
"tool_count": len(tools),
}
except Exception as test_error:
logger.warning(f"MCP server test failed for '{name}': {test_error}")
raise HTTPException(status_code=500, detail=f"连接失败: {str(test_error)}")
except HTTPException:
raise

View File

@ -210,6 +210,7 @@ async def get_mcp_tools(
disabled_tools: list[str] = None,
cache: bool = True,
force_refresh: bool = False,
raise_on_error: bool = False,
) -> list[Callable[..., Any]]:
"""Get MCP tools for a specific server.
@ -288,11 +289,15 @@ async def get_mcp_tools(
except AssertionError as e:
logger.warning(f"[assert] Failed to load tools from MCP server '{server_name}': {e}")
if raise_on_error:
raise
return []
except Exception as e:
logger.error(
f"Failed to load tools from MCP server '{server_name}': {e}, traceback: {traceback.format_exc()}"
)
if raise_on_error:
raise
return []
# 3. Filtering (Apply to Return Value Only)
@ -602,7 +607,7 @@ async def get_servers_config(names: list[str]) -> dict[str, dict[str, Any]]:
return {name: MCP_SERVERS[name] for name in names if name in MCP_SERVERS}
async def get_all_mcp_tools(server_name: str) -> list:
async def get_all_mcp_tools(server_name: str, raise_on_error: bool = False) -> list:
"""Get all tools of an MCP server (no filtering).
For management UI to display tool list, supports viewing all tools and their enabled status.
@ -610,6 +615,7 @@ async def get_all_mcp_tools(server_name: str) -> list:
Args:
server_name: Server name
raise_on_error: Whether to raise an exception on error instead of returning empty list
Returns:
List of all tools (unfiltered)
@ -617,7 +623,15 @@ async def get_all_mcp_tools(server_name: str) -> list:
config = MCP_SERVERS.get(server_name)
if not config:
logger.warning(f"MCP server '{server_name}' not found in cache")
if raise_on_error:
raise ValueError(f"MCP server '{server_name}' not found in cache")
return []
# Get all tools (no filtering, force refresh, no cache update)
return await get_mcp_tools(server_name, disabled_tools=[], cache=False, force_refresh=True)
return await get_mcp_tools(
server_name,
disabled_tools=[],
cache=False,
force_refresh=True,
raise_on_error=raise_on_error,
)