fix(agent): scope MCP manager cleanup to successful initialization

Move defer cleanup inside else block to only clean up when MCP servers
are successfully initialized. This prevents unnecessary cleanup attempts
when LoadFromMCPConfig fails.

Addresses Copilot code review feedback.
This commit is contained in:
yuchou87
2026-02-19 19:26:02 +08:00
parent a5d2e109bf
commit ffa01986ce
+10 -10
View File
@@ -150,6 +150,16 @@ func (al *AgentLoop) Run(ctx context.Context) error {
"error": err.Error(),
})
} else {
// Ensure MCP connections are cleaned up on exit, only if initialization succeeded
defer func() {
if err := mcpManager.Close(); err != nil {
logger.ErrorCF("agent", "Failed to close MCP manager",
map[string]interface{}{
"error": err.Error(),
})
}
}()
// Register MCP tools for all agents
servers := mcpManager.GetServers()
toolCount := 0
@@ -179,16 +189,6 @@ func (al *AgentLoop) Run(ctx context.Context) error {
"tool_count": toolCount,
})
}
// Ensure MCP connections are cleaned up on exit
defer func() {
if err := mcpManager.Close(); err != nil {
logger.ErrorCF("agent", "Failed to close MCP manager",
map[string]interface{}{
"error": err.Error(),
})
}
}()
}
for al.running.Load() {