@@ -0,0 +1,246 @@
1+package mcptools
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "fmt"
7+ "strings"
8+ "time"
9+
10+ "github.com/xonecas/symb/internal/delta"
11+ "github.com/xonecas/symb/internal/llm"
12+ "github.com/xonecas/symb/internal/lsp"
13+ "github.com/xonecas/symb/internal/mcp"
14+ "github.com/xonecas/symb/internal/provider"
15+ "github.com/xonecas/symb/internal/shell"
16+ "github.com/xonecas/symb/internal/store"
17+)
18+
19+const (
20+ // MaxSubAgentDepth is the maximum recursion depth for sub-agents.
21+ // Depth 0 = root agent, depth 1 = sub-agent spawned by root.
22+ MaxSubAgentDepth = 1
23+
24+ // MaxSubAgentIterations is the default max tool rounds for sub-agents.
25+ MaxSubAgentIterations = 5
26+
27+ // MaxAllowedIterations is the upper bound for user-specified max_iterations.
28+ MaxAllowedIterations = 20
29+)
30+
31+// SubAgentArgs represents arguments for the SubAgent tool.
32+type SubAgentArgs struct {
33+ Prompt string `json:"prompt"`
34+ MaxIterations int `json:"max_iterations,omitempty"`
35+}
36+
37+// NewSubAgentTool creates the SubAgent tool definition.
38+func NewSubAgentTool() mcp.Tool {
39+ return mcp.Tool{
40+ Name: "SubAgent",
41+ Description: `Spawn a sub-agent to handle a focused task. The sub-agent runs with the same tools but cannot spawn further sub-agents. Use this to decompose complex tasks into smaller, manageable pieces. The sub-agent's work is returned as a summary.`,
42+ InputSchema: json.RawMessage(`{
43+ "type": "object",
44+ "properties": {
45+ "prompt": {"type": "string", "description": "Task description for the sub-agent. Be specific about what needs to be accomplished and the expected output format."},
46+ "max_iterations": {"type": "integer", "description": "Maximum tool rounds for the sub-agent (default: 5)"}
47+ },
48+ "required": ["prompt"]
49+ }`),
50+ }
51+}
52+
53+// SubAgentHandler handles SubAgent tool calls.
54+type SubAgentHandler struct {
55+ provider provider.Provider
56+ lspManager *lsp.Manager
57+ deltaTracker *delta.Tracker
58+ sh *shell.Shell
59+ webCache *store.Cache
60+ exaKey string
61+ allTools []mcp.Tool
62+}
63+
64+// NewSubAgentHandler creates a handler for the SubAgent tool.
65+func NewSubAgentHandler(
66+ prov provider.Provider,
67+ lspManager *lsp.Manager,
68+ deltaTracker *delta.Tracker,
69+ sh *shell.Shell,
70+ webCache *store.Cache,
71+ exaKey string,
72+ allTools []mcp.Tool,
73+) *SubAgentHandler {
74+ // Validate required dependencies
75+ if prov == nil {
76+ panic("SubAgentHandler: provider cannot be nil")
77+ }
78+ if sh == nil {
79+ panic("SubAgentHandler: shell cannot be nil")
80+ }
81+ // lspManager, deltaTracker, webCache can be nil (handlers check internally)
82+
83+ return &SubAgentHandler{
84+ provider: prov,
85+ lspManager: lspManager,
86+ deltaTracker: deltaTracker,
87+ sh: sh,
88+ webCache: webCache,
89+ exaKey: exaKey,
90+ allTools: allTools,
91+ }
92+}
93+
94+// Handle implements the mcp.ToolHandler interface.
95+func (h *SubAgentHandler) Handle(ctx context.Context, arguments json.RawMessage) (*mcp.ToolResult, error) {
96+ // Check if context is already cancelled
97+ if err := ctx.Err(); err != nil {
98+ return toolError("Sub-agent cancelled: %v", err), nil
99+ }
100+
101+ var args SubAgentArgs
102+ if err := json.Unmarshal(arguments, &args); err != nil {
103+ return toolError("Invalid arguments: %v", err), nil
104+ }
105+ if args.Prompt == "" {
106+ return toolError("prompt is required"), nil
107+ }
108+
109+ maxIter := MaxSubAgentIterations
110+ if args.MaxIterations > 0 {
111+ if args.MaxIterations > MaxAllowedIterations {
112+ return toolError("max_iterations too large (max: %d)", MaxAllowedIterations), nil
113+ }
114+ maxIter = args.MaxIterations
115+ }
116+
117+ // Create isolated FileReadTracker for sub-agent
118+ subTracker := NewFileReadTracker()
119+
120+ // Create fresh handlers with isolated tracker
121+ subReadHandler := NewReadHandler(subTracker, h.lspManager)
122+ subEditHandler := NewEditHandler(subTracker, h.lspManager, h.deltaTracker)
123+ subShellHandler := NewShellHandler(h.sh)
124+
125+ // Create proxy with sub-agent tools (filtered - no nested SubAgent)
126+ subProxy := mcp.NewProxy(nil)
127+ filteredTools := filterSubAgentTool(h.allTools)
128+
129+ // Register tools with sub-agent proxy
130+ for _, tool := range filteredTools {
131+ switch tool.Name {
132+ case "Read":
133+ subProxy.RegisterTool(tool, subReadHandler.Handle)
134+ case "Edit":
135+ subProxy.RegisterTool(tool, subEditHandler.Handle)
136+ case "Shell":
137+ subProxy.RegisterTool(tool, subShellHandler.Handle)
138+ case "Grep":
139+ subProxy.RegisterTool(tool, MakeGrepHandler())
140+ case "TodoWrite":
141+ // Sub-agents get their own scratchpad
142+ subPad := &Scratchpad{}
143+ subProxy.RegisterTool(tool, MakeTodoWriteHandler(subPad))
144+ case "WebFetch":
145+ subProxy.RegisterTool(tool, MakeWebFetchHandler(h.webCache))
146+ case "WebSearch":
147+ subProxy.RegisterTool(tool, MakeWebSearchHandler(h.webCache, h.exaKey, ""))
148+ }
149+ }
150+
151+ // Build sub-agent history: system prompt + user task
152+ subHistory := []provider.Message{
153+ {
154+ Role: "system",
155+ Content: buildSubAgentSystemPrompt(),
156+ CreatedAt: time.Now(),
157+ },
158+ {
159+ Role: "user",
160+ Content: args.Prompt,
161+ CreatedAt: time.Now(),
162+ },
163+ }
164+
165+ // Track sub-agent's token usage
166+ var totalIn, totalOut int
167+
168+ // Collect sub-agent's messages for the result
169+ var subMessages []provider.Message
170+
171+ // Run sub-agent turn
172+ err := llm.ProcessTurn(ctx, llm.ProcessTurnOptions{
173+ Provider: h.provider,
174+ Proxy: subProxy,
175+ Tools: filteredTools,
176+ History: subHistory,
177+ OnMessage: func(msg provider.Message) {
178+ subMessages = append(subMessages, msg)
179+ },
180+ OnUsage: func(in, out int) {
181+ totalIn += in
182+ totalOut += out
183+ },
184+ MaxToolRounds: maxIter,
185+ Depth: 1, // Sub-agent is at depth 1
186+ })
187+
188+ if err != nil {
189+ return toolError("Sub-agent failed: %v", err), nil
190+ }
191+
192+ // Check if sub-agent produced a final response
193+ if len(subMessages) == 0 {
194+ return toolError("Sub-agent produced no output"), nil
195+ }
196+
197+ // Extract final assistant message
198+ var finalContent string
199+ for i := len(subMessages) - 1; i >= 0; i-- {
200+ if subMessages[i].Role == "assistant" && subMessages[i].Content != "" {
201+ finalContent = subMessages[i].Content
202+ break
203+ }
204+ }
205+
206+ if finalContent == "" {
207+ return toolError("Sub-agent produced no final response"), nil
208+ }
209+
210+ // Build result with usage metadata
211+ result := fmt.Sprintf("Sub-agent completed.\n\n%s\n\n---\nToken usage: %d in, %d out",
212+ finalContent, totalIn, totalOut)
213+
214+ return toolText(result), nil
215+}
216+
217+// filterSubAgentTool removes the SubAgent tool from a tool list.
218+func filterSubAgentTool(tools []mcp.Tool) []mcp.Tool {
219+ filtered := make([]mcp.Tool, 0, len(tools))
220+ for _, t := range tools {
221+ if t.Name != "SubAgent" {
222+ filtered = append(filtered, t)
223+ }
224+ }
225+ return filtered
226+}
227+
228+// buildSubAgentSystemPrompt returns the system prompt for sub-agents.
229+func buildSubAgentSystemPrompt() string {
230+ return strings.TrimSpace(`
231+You are a focused sub-agent working on a specific task assigned by a parent agent.
232+
233+Your role:
234+- Complete the assigned task efficiently
235+- Use tools as needed (Read, Edit, Grep, Shell, etc.)
236+- Provide a clear, concise final response summarizing what you accomplished
237+- You cannot spawn further sub-agents
238+
239+Output format:
240+- Use tools to gather information and make changes
241+- When done, respond with a summary of what was accomplished
242+- Be specific about any files modified, tests run, or issues found
243+
244+You have a limited number of tool rounds - work efficiently.
245+`)
246+}