fix(agent): register MCP tools after server initialization

Critical bug fix:
- MCP tools were never registered because servers loaded in Run()
  but tool registration happened in NewAgentLoop() with empty manager
- Move MCP tool registration from createToolRegistry to Run()
- Register MCP tools for both main agent and subag after successful server loading
- Add subagentManager field to AgentLoop for dynamic registration
- Add tool_count logging for better observability

This ensures MCP tools are properly available to both agent and subagents.
This commit is contained in:
yuchou87 2026-02-16 20:00:37 +08:00
parent 4f4a559583
commit 40087cc949

View file

@ -45,6 +45,7 @@ type AgentLoop struct {
mcpManager *mcp.Manager // MCP server manager for resource cleanup
mcpConfig *config.Config // Config for lazy MCP initialization
mcpInitOnce sync.Once // Ensures MCP is initialized only once
subagentManager *tools.SubagentManager // Subagent manager for MCP tool registration
running atomic.Bool
summarizing sync.Map // Tracks which sessions are currently being summarized
channelManager *channels.Manager
@ -105,22 +106,8 @@ func createToolRegistry(workspace string, restrict bool, cfg *config.Config, msg
})
registry.Register(messageTool)
// Register MCP tools from all connected servers
if mcpManager != nil {
servers := mcpManager.GetServers()
for serverName, conn := range servers {
for _, tool := range conn.Tools {
mcpTool := tools.NewMCPTool(mcpManager, serverName, tool)
registry.Register(mcpTool)
logger.DebugCF("agent", "Registered MCP tool",
map[string]interface{}{
"server": serverName,
"tool": tool.Name,
"name": mcpTool.Name(),
})
}
}
}
// Note: MCP tools are registered dynamically in Run() after servers are loaded
// This ensures we use the agent's lifecycle context for MCP connections
return registry
}
@ -174,6 +161,7 @@ func NewAgentLoop(cfg *config.Config, msgBus *bus.MessageBus, provider providers
tools: toolsRegistry,
mcpManager: mcpManager,
mcpConfig: cfg, // Store config for lazy initialization in Run()
subagentManager: subagentManager,
summarizing: sync.Map{},
}
}
@ -189,6 +177,34 @@ func (al *AgentLoop) Run(ctx context.Context) error {
map[string]interface{}{
"error": err.Error(),
})
} else {
// Register for both main agent and subagents
servers := al.mcpManager.GetServers()
toolCount := 0
for serverName, conn := range servers {
for _, tool := range conn.Tools {
mcpTool := tools.NewMCPTool(al.mcpManager, serverName, tool)
al.tools.Register(mcpTool)
// Also register for subagent
if al.subagentManager != nil {
al.subagentManager.RegisterTool(tools.NewMCPTool(al.mcpManager, serverName, tool))
}
toolCount++
logger.DebugCF("agent", "Registered MCP tool",
map[string]interface{}{
"server": serverName,
"tool": tool.Name,
"name": mcpTool.Name(),
})
}
}
logger.InfoCF("agent", "MCP tools registered successfully",
map[string]interface{}{
"server_count": len(servers),
"tool_count": toolCount,
})
}
})