hanzo-mcp 0.8.11__py3-none-any.whl → 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of hanzo-mcp might be problematic. Click here for more details.

Files changed (166) hide show
  1. hanzo_mcp/__init__.py +1 -3
  2. hanzo_mcp/analytics/posthog_analytics.py +3 -9
  3. hanzo_mcp/bridge.py +9 -25
  4. hanzo_mcp/cli.py +6 -15
  5. hanzo_mcp/cli_enhanced.py +5 -14
  6. hanzo_mcp/cli_plugin.py +3 -9
  7. hanzo_mcp/config/settings.py +6 -20
  8. hanzo_mcp/config/tool_config.py +1 -3
  9. hanzo_mcp/core/base_agent.py +88 -88
  10. hanzo_mcp/core/model_registry.py +238 -210
  11. hanzo_mcp/dev_server.py +5 -15
  12. hanzo_mcp/prompts/__init__.py +2 -6
  13. hanzo_mcp/prompts/project_todo_reminder.py +3 -9
  14. hanzo_mcp/prompts/tool_explorer.py +1 -3
  15. hanzo_mcp/prompts/utils.py +7 -21
  16. hanzo_mcp/server.py +2 -6
  17. hanzo_mcp/tools/__init__.py +26 -27
  18. hanzo_mcp/tools/agent/__init__.py +2 -1
  19. hanzo_mcp/tools/agent/agent.py +10 -30
  20. hanzo_mcp/tools/agent/agent_tool.py +22 -15
  21. hanzo_mcp/tools/agent/claude_desktop_auth.py +3 -9
  22. hanzo_mcp/tools/agent/cli_agent_base.py +7 -24
  23. hanzo_mcp/tools/agent/cli_tools.py +75 -74
  24. hanzo_mcp/tools/agent/code_auth.py +1 -3
  25. hanzo_mcp/tools/agent/code_auth_tool.py +2 -6
  26. hanzo_mcp/tools/agent/critic_tool.py +8 -24
  27. hanzo_mcp/tools/agent/iching_tool.py +12 -36
  28. hanzo_mcp/tools/agent/network_tool.py +7 -18
  29. hanzo_mcp/tools/agent/prompt.py +1 -5
  30. hanzo_mcp/tools/agent/review_tool.py +10 -25
  31. hanzo_mcp/tools/agent/swarm_alias.py +1 -3
  32. hanzo_mcp/tools/agent/unified_cli_tools.py +38 -38
  33. hanzo_mcp/tools/common/batch_tool.py +15 -45
  34. hanzo_mcp/tools/common/config_tool.py +9 -28
  35. hanzo_mcp/tools/common/context.py +1 -3
  36. hanzo_mcp/tools/common/critic_tool.py +1 -3
  37. hanzo_mcp/tools/common/decorators.py +2 -6
  38. hanzo_mcp/tools/common/enhanced_base.py +2 -6
  39. hanzo_mcp/tools/common/fastmcp_pagination.py +4 -12
  40. hanzo_mcp/tools/common/forgiving_edit.py +9 -28
  41. hanzo_mcp/tools/common/mode.py +1 -5
  42. hanzo_mcp/tools/common/paginated_base.py +3 -11
  43. hanzo_mcp/tools/common/paginated_response.py +10 -30
  44. hanzo_mcp/tools/common/pagination.py +3 -9
  45. hanzo_mcp/tools/common/path_utils.py +34 -0
  46. hanzo_mcp/tools/common/permissions.py +14 -13
  47. hanzo_mcp/tools/common/personality.py +983 -701
  48. hanzo_mcp/tools/common/plugin_loader.py +3 -15
  49. hanzo_mcp/tools/common/stats.py +6 -18
  50. hanzo_mcp/tools/common/thinking_tool.py +1 -3
  51. hanzo_mcp/tools/common/tool_disable.py +2 -6
  52. hanzo_mcp/tools/common/tool_list.py +2 -6
  53. hanzo_mcp/tools/common/validation.py +1 -3
  54. hanzo_mcp/tools/compiler/__init__.py +8 -0
  55. hanzo_mcp/tools/compiler/sandboxed_compiler.py +681 -0
  56. hanzo_mcp/tools/config/config_tool.py +7 -13
  57. hanzo_mcp/tools/config/index_config.py +1 -3
  58. hanzo_mcp/tools/config/mode_tool.py +5 -15
  59. hanzo_mcp/tools/database/database_manager.py +3 -9
  60. hanzo_mcp/tools/database/graph.py +1 -3
  61. hanzo_mcp/tools/database/graph_add.py +3 -9
  62. hanzo_mcp/tools/database/graph_query.py +11 -34
  63. hanzo_mcp/tools/database/graph_remove.py +3 -9
  64. hanzo_mcp/tools/database/graph_search.py +6 -20
  65. hanzo_mcp/tools/database/graph_stats.py +11 -33
  66. hanzo_mcp/tools/database/sql.py +4 -12
  67. hanzo_mcp/tools/database/sql_query.py +6 -10
  68. hanzo_mcp/tools/database/sql_search.py +2 -6
  69. hanzo_mcp/tools/database/sql_stats.py +5 -15
  70. hanzo_mcp/tools/editor/neovim_command.py +1 -3
  71. hanzo_mcp/tools/editor/neovim_session.py +7 -13
  72. hanzo_mcp/tools/environment/__init__.py +8 -0
  73. hanzo_mcp/tools/environment/environment_detector.py +594 -0
  74. hanzo_mcp/tools/filesystem/__init__.py +28 -26
  75. hanzo_mcp/tools/filesystem/ast_multi_edit.py +14 -43
  76. hanzo_mcp/tools/filesystem/ast_tool.py +3 -0
  77. hanzo_mcp/tools/filesystem/base.py +20 -12
  78. hanzo_mcp/tools/filesystem/content_replace.py +7 -12
  79. hanzo_mcp/tools/filesystem/diff.py +2 -10
  80. hanzo_mcp/tools/filesystem/directory_tree.py +285 -51
  81. hanzo_mcp/tools/filesystem/edit.py +10 -18
  82. hanzo_mcp/tools/filesystem/find.py +312 -179
  83. hanzo_mcp/tools/filesystem/git_search.py +12 -24
  84. hanzo_mcp/tools/filesystem/multi_edit.py +10 -18
  85. hanzo_mcp/tools/filesystem/read.py +14 -30
  86. hanzo_mcp/tools/filesystem/rules_tool.py +9 -17
  87. hanzo_mcp/tools/filesystem/search.py +1160 -0
  88. hanzo_mcp/tools/filesystem/watch.py +2 -4
  89. hanzo_mcp/tools/filesystem/write.py +7 -10
  90. hanzo_mcp/tools/framework/__init__.py +8 -0
  91. hanzo_mcp/tools/framework/framework_modes.py +714 -0
  92. hanzo_mcp/tools/jupyter/base.py +6 -20
  93. hanzo_mcp/tools/jupyter/jupyter.py +4 -12
  94. hanzo_mcp/tools/llm/consensus_tool.py +8 -24
  95. hanzo_mcp/tools/llm/llm_manage.py +2 -6
  96. hanzo_mcp/tools/llm/llm_tool.py +17 -58
  97. hanzo_mcp/tools/llm/llm_unified.py +18 -59
  98. hanzo_mcp/tools/llm/provider_tools.py +1 -3
  99. hanzo_mcp/tools/lsp/lsp_tool.py +621 -481
  100. hanzo_mcp/tools/mcp/mcp_add.py +1 -3
  101. hanzo_mcp/tools/mcp/mcp_stats.py +1 -3
  102. hanzo_mcp/tools/mcp/mcp_tool.py +9 -23
  103. hanzo_mcp/tools/memory/__init__.py +10 -27
  104. hanzo_mcp/tools/memory/conversation_memory.py +636 -0
  105. hanzo_mcp/tools/memory/knowledge_tools.py +7 -25
  106. hanzo_mcp/tools/memory/memory_tools.py +6 -18
  107. hanzo_mcp/tools/search/find_tool.py +12 -34
  108. hanzo_mcp/tools/search/unified_search.py +24 -78
  109. hanzo_mcp/tools/shell/__init__.py +16 -4
  110. hanzo_mcp/tools/shell/auto_background.py +2 -6
  111. hanzo_mcp/tools/shell/base.py +1 -5
  112. hanzo_mcp/tools/shell/base_process.py +5 -7
  113. hanzo_mcp/tools/shell/bash_session.py +7 -24
  114. hanzo_mcp/tools/shell/bash_session_executor.py +5 -15
  115. hanzo_mcp/tools/shell/bash_tool.py +3 -7
  116. hanzo_mcp/tools/shell/command_executor.py +26 -79
  117. hanzo_mcp/tools/shell/logs.py +4 -16
  118. hanzo_mcp/tools/shell/npx.py +2 -8
  119. hanzo_mcp/tools/shell/npx_tool.py +1 -3
  120. hanzo_mcp/tools/shell/pkill.py +4 -12
  121. hanzo_mcp/tools/shell/process_tool.py +2 -8
  122. hanzo_mcp/tools/shell/processes.py +5 -17
  123. hanzo_mcp/tools/shell/run_background.py +1 -3
  124. hanzo_mcp/tools/shell/run_command.py +1 -3
  125. hanzo_mcp/tools/shell/run_command_windows.py +1 -3
  126. hanzo_mcp/tools/shell/run_tool.py +56 -0
  127. hanzo_mcp/tools/shell/session_manager.py +2 -6
  128. hanzo_mcp/tools/shell/session_storage.py +2 -6
  129. hanzo_mcp/tools/shell/streaming_command.py +7 -23
  130. hanzo_mcp/tools/shell/uvx.py +4 -14
  131. hanzo_mcp/tools/shell/uvx_background.py +2 -6
  132. hanzo_mcp/tools/shell/uvx_tool.py +1 -3
  133. hanzo_mcp/tools/shell/zsh_tool.py +12 -20
  134. hanzo_mcp/tools/todo/todo.py +1 -3
  135. hanzo_mcp/tools/vector/__init__.py +97 -50
  136. hanzo_mcp/tools/vector/ast_analyzer.py +6 -20
  137. hanzo_mcp/tools/vector/git_ingester.py +10 -30
  138. hanzo_mcp/tools/vector/index_tool.py +3 -9
  139. hanzo_mcp/tools/vector/infinity_store.py +7 -27
  140. hanzo_mcp/tools/vector/mock_infinity.py +1 -3
  141. hanzo_mcp/tools/vector/node_tool.py +538 -0
  142. hanzo_mcp/tools/vector/project_manager.py +4 -12
  143. hanzo_mcp/tools/vector/unified_vector.py +384 -0
  144. hanzo_mcp/tools/vector/vector.py +2 -6
  145. hanzo_mcp/tools/vector/vector_index.py +8 -8
  146. hanzo_mcp/tools/vector/vector_search.py +7 -21
  147. {hanzo_mcp-0.8.11.dist-info → hanzo_mcp-0.9.0.dist-info}/METADATA +2 -2
  148. hanzo_mcp-0.9.0.dist-info/RECORD +191 -0
  149. hanzo_mcp/tools/agent/agent_tool_v1_deprecated.py +0 -645
  150. hanzo_mcp/tools/agent/swarm_tool.py +0 -718
  151. hanzo_mcp/tools/agent/swarm_tool_v1_deprecated.py +0 -577
  152. hanzo_mcp/tools/filesystem/batch_search.py +0 -900
  153. hanzo_mcp/tools/filesystem/directory_tree_paginated.py +0 -350
  154. hanzo_mcp/tools/filesystem/find_files.py +0 -369
  155. hanzo_mcp/tools/filesystem/grep.py +0 -467
  156. hanzo_mcp/tools/filesystem/search_tool.py +0 -767
  157. hanzo_mcp/tools/filesystem/symbols_tool.py +0 -515
  158. hanzo_mcp/tools/filesystem/tree.py +0 -270
  159. hanzo_mcp/tools/jupyter/notebook_edit.py +0 -317
  160. hanzo_mcp/tools/jupyter/notebook_read.py +0 -147
  161. hanzo_mcp/tools/todo/todo_read.py +0 -143
  162. hanzo_mcp/tools/todo/todo_write.py +0 -374
  163. hanzo_mcp-0.8.11.dist-info/RECORD +0 -193
  164. {hanzo_mcp-0.8.11.dist-info → hanzo_mcp-0.9.0.dist-info}/WHEEL +0 -0
  165. {hanzo_mcp-0.8.11.dist-info → hanzo_mcp-0.9.0.dist-info}/entry_points.txt +0 -0
  166. {hanzo_mcp-0.8.11.dist-info → hanzo_mcp-0.9.0.dist-info}/top_level.txt +0 -0
@@ -1,645 +0,0 @@
1
- """Agent tool implementation for Hanzo AI.
2
-
3
- This module implements the AgentTool that allows Claude to delegate tasks to sub-agents,
4
- enabling concurrent execution of multiple operations and specialized processing.
5
- """
6
-
7
- import re
8
- import json
9
- import time
10
- import asyncio
11
-
12
- # Import litellm with warnings suppressed
13
- import warnings
14
- from typing import Unpack, Annotated, TypedDict, final, override
15
- from collections.abc import Iterable
16
-
17
- with warnings.catch_warnings():
18
- warnings.simplefilter("ignore", DeprecationWarning)
19
- import litellm
20
- from pydantic import Field
21
- from mcp.server import FastMCP
22
- from openai.types.chat import ChatCompletionToolParam, ChatCompletionMessageParam
23
- from mcp.server.fastmcp import Context as MCPContext
24
-
25
- from hanzo_mcp.tools.jupyter import get_read_only_jupyter_tools
26
- from hanzo_mcp.tools.filesystem import Edit, MultiEdit, get_read_only_filesystem_tools
27
- from hanzo_mcp.tools.common.base import BaseTool
28
- from hanzo_mcp.tools.agent.prompt import (
29
- get_default_model,
30
- get_system_prompt,
31
- get_model_parameters,
32
- get_allowed_agent_tools,
33
- )
34
- from hanzo_mcp.tools.common.context import (
35
- ToolContext,
36
- create_tool_context,
37
- )
38
- from hanzo_mcp.tools.agent.critic_tool import CriticTool, CriticProtocol
39
- from hanzo_mcp.tools.agent.iching_tool import IChingTool
40
- from hanzo_mcp.tools.agent.review_tool import ReviewTool, ReviewProtocol
41
- from hanzo_mcp.tools.common.batch_tool import BatchTool
42
- from hanzo_mcp.tools.agent.tool_adapter import (
43
- convert_tools_to_openai_functions,
44
- )
45
- from hanzo_mcp.tools.common.permissions import PermissionManager
46
- from hanzo_mcp.tools.agent.clarification_tool import ClarificationTool
47
- from hanzo_mcp.tools.agent.clarification_protocol import (
48
- ClarificationType,
49
- AgentClarificationMixin,
50
- )
51
-
52
- Prompt = Annotated[
53
- str,
54
- Field(
55
- description="Task for the agent to perform (must include absolute paths starting with /)",
56
- min_length=1,
57
- ),
58
- ]
59
-
60
-
61
- class AgentToolParams(TypedDict, total=False):
62
- """Parameters for the AgentTool.
63
-
64
- Attributes:
65
- prompts: Task(s) for the agent to perform (must include absolute paths starting with /)
66
- """
67
-
68
- prompts: str | list[str]
69
-
70
-
71
- @final
72
- class AgentTool(AgentClarificationMixin, BaseTool):
73
- """Tool for delegating tasks to sub-agents.
74
-
75
- The AgentTool allows Claude to create and manage sub-agents for performing
76
- specialized tasks concurrently, such as code search, analysis, and more.
77
-
78
- Agents can request clarification from the main loop up to once per task.
79
- """
80
-
81
- @property
82
- @override
83
- def name(self) -> str:
84
- """Get the tool name.
85
-
86
- Returns:
87
- Tool name
88
- """
89
- return "agent"
90
-
91
- @property
92
- @override
93
- def description(self) -> str:
94
- """Get the tool description.
95
-
96
- Returns:
97
- Tool description
98
- """
99
- # TODO: Add glob when it is implemented
100
- at = [t.name for t in self.available_tools]
101
-
102
- return f"""Launch a new agent that has access to the following tools: {at}. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries, use the Agent tool to perform the search for you.
103
-
104
- When to use the Agent tool:
105
- - If you are searching for a keyword like \"config\" or \"logger\", or for questions like \"which file does X?\", the Agent tool is strongly recommended
106
- - When you need to perform edits across multiple files based on search results
107
- - When you need to delegate complex file modification tasks
108
-
109
- When NOT to use the Agent tool:
110
- - If you want to read a specific file path, use the read or glob tool instead of the Agent tool, to find the match more quickly
111
- - If you are searching for a specific class definition like \"class Foo\", use the glob tool instead, to find the match more quickly
112
- - If you are searching for code within a specific file or set of 2-3 files, use the read tool instead of the Agent tool, to find the match more quickly
113
- - Writing code and running bash commands (use other tools for that)
114
- - Other tasks that are not related to searching for a keyword or file
115
-
116
- Usage notes:
117
- 1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
118
- 2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
119
- 3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.
120
- 4. The agent's outputs should generally be trusted
121
- 5. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent"""
122
-
123
- def __init__(
124
- self,
125
- permission_manager: PermissionManager,
126
- model: str | None = None,
127
- api_key: str | None = None,
128
- base_url: str | None = None,
129
- max_tokens: int | None = None,
130
- max_iterations: int = 10,
131
- max_tool_uses: int = 30,
132
- ) -> None:
133
- """Initialize the agent tool.
134
-
135
- Args:
136
-
137
- permission_manager: Permission manager for access control
138
- model: Optional model name override in LiteLLM format (e.g., "openai/gpt-4o")
139
- api_key: Optional API key for the model provider
140
- base_url: Optional base URL for the model provider API endpoint
141
- max_tokens: Optional maximum tokens for model responses
142
- max_iterations: Maximum number of iterations for agent (default: 10)
143
- max_tool_uses: Maximum number of total tool uses for agent (default: 30)
144
- """
145
-
146
- self.permission_manager = permission_manager
147
- self.model_override = model
148
- self.api_key_override = api_key
149
- self.base_url_override = base_url
150
- self.max_tokens_override = max_tokens
151
- self.max_iterations = max_iterations
152
- self.max_tool_uses = max_tool_uses
153
- self.available_tools: list[BaseTool] = []
154
- self.available_tools.extend(
155
- get_read_only_filesystem_tools(self.permission_manager)
156
- )
157
- self.available_tools.extend(
158
- get_read_only_jupyter_tools(self.permission_manager)
159
- )
160
-
161
- # Always add edit tools - agents should have edit access
162
- self.available_tools.append(Edit(self.permission_manager))
163
- self.available_tools.append(MultiEdit(self.permission_manager))
164
-
165
- # Add clarification tool for agents
166
- self.available_tools.append(ClarificationTool())
167
-
168
- # Add critic tool for agents (devil's advocate)
169
- self.available_tools.append(CriticTool())
170
-
171
- # Add review tool for agents (balanced review)
172
- self.available_tools.append(ReviewTool())
173
-
174
- # Add I Ching tool for creative guidance
175
- self.available_tools.append(IChingTool())
176
-
177
- self.available_tools.append(
178
- BatchTool({t.name: t for t in self.available_tools})
179
- )
180
-
181
- # Initialize protocols
182
- self.critic_protocol = CriticProtocol()
183
- self.review_protocol = ReviewProtocol()
184
-
185
- @override
186
- async def call(
187
- self,
188
- ctx: MCPContext,
189
- **params: Unpack[AgentToolParams],
190
- ) -> str:
191
- """Execute the tool with the given parameters.
192
-
193
- Args:
194
- ctx: MCP context
195
- **params: Tool parameters
196
-
197
- Returns:
198
- Tool execution result
199
- """
200
- start_time = time.time()
201
-
202
- # Create tool context
203
- tool_ctx = create_tool_context(ctx)
204
- await tool_ctx.set_tool_info(self.name)
205
-
206
- # Extract and validate parameters
207
- prompts = params.get("prompts")
208
-
209
- if prompts is None:
210
- await tool_ctx.error("No prompts provided")
211
- return """Error: At least one prompt must be provided.
212
-
213
- IMPORTANT REMINDER FOR CLAUDE:
214
- The dispatch_agent tool requires prompts parameter. Please provide either:
215
- - A single prompt as a string
216
- - Multiple prompts as an array of strings
217
-
218
- Each prompt must contain absolute paths starting with /.
219
- Example of correct usage:
220
- - prompts: "Search for all instances of the 'config' variable in /Users/bytedance/project/hanzo-mcp"
221
- - prompts: ["Find files in /path/to/project", "Search code in /path/to/src"]"""
222
-
223
- # Handle both string and list inputs
224
- if isinstance(prompts, str):
225
- prompt_list = [prompts]
226
- elif isinstance(prompts, list):
227
- if not prompts:
228
- await tool_ctx.error("Empty prompts list provided")
229
- return "Error: At least one prompt must be provided when using a list."
230
- if not all(isinstance(p, str) for p in prompts):
231
- await tool_ctx.error("All prompts must be strings")
232
- return "Error: All prompts in the list must be strings."
233
- prompt_list = prompts
234
- else:
235
- await tool_ctx.error("Invalid prompts parameter type")
236
- return "Error: Parameter 'prompts' must be a string or an array of strings."
237
-
238
- # Validate absolute paths in all prompts
239
- absolute_path_pattern = r"/(?:[^/\s]+/)*[^/\s]+"
240
- for prompt in prompt_list:
241
- if not re.search(absolute_path_pattern, prompt):
242
- await tool_ctx.error(
243
- f"Prompt does not contain absolute path: {prompt[:50]}..."
244
- )
245
- return """Error: All prompts must contain at least one absolute path.
246
-
247
- IMPORTANT REMINDER FOR CLAUDE:
248
- When using the dispatch_agent tool, always include absolute paths in your prompts.
249
- Example of correct usage:
250
- - "Search for all instances of the 'config' variable in /Users/bytedance/project/hanzo-mcp"
251
- - "Find files that import the database module in /Users/bytedance/project/hanzo-mcp/src"
252
-
253
- The agent cannot access files without knowing their absolute locations."""
254
-
255
- # Execute agent(s) - always use _execute_multiple_agents for list inputs
256
- if len(prompt_list) == 1:
257
- await tool_ctx.info("Launching agent")
258
- result = await self._execute_multiple_agents(prompt_list, tool_ctx)
259
- execution_time = time.time() - start_time
260
- formatted_result = f"""Agent execution completed in {execution_time:.2f} seconds.
261
-
262
- AGENT RESPONSE:
263
- {result}"""
264
- await tool_ctx.info(f"Agent execution completed in {execution_time:.2f}s")
265
- return formatted_result
266
- else:
267
- await tool_ctx.info(f"Launching {len(prompt_list)} agents in parallel")
268
- result = await self._execute_multiple_agents(prompt_list, tool_ctx)
269
- execution_time = time.time() - start_time
270
- formatted_result = f"""Multi-agent execution completed in {execution_time:.2f} seconds ({len(prompt_list)} agents).
271
-
272
- AGENT RESPONSES:
273
- {result}"""
274
- await tool_ctx.info(
275
- f"Multi-agent execution completed in {execution_time:.2f}s"
276
- )
277
- return formatted_result
278
-
279
- async def _execute_agent(self, prompt: str, tool_ctx: ToolContext) -> str:
280
- """Execute a single agent with the given prompt.
281
-
282
- Args:
283
- prompt: The task prompt for the agent
284
- tool_ctx: Tool context for logging
285
-
286
- Returns:
287
- Agent execution result
288
- """
289
- # Get available tools for the agent
290
- agent_tools = get_allowed_agent_tools(
291
- self.available_tools,
292
- self.permission_manager,
293
- )
294
-
295
- # Convert tools to OpenAI format
296
- openai_tools = convert_tools_to_openai_functions(agent_tools)
297
-
298
- # Log execution start
299
- await tool_ctx.info("Starting agent execution")
300
-
301
- # Create a result container
302
- result = ""
303
-
304
- try:
305
- # Create system prompt for this agent
306
- system_prompt = get_system_prompt(
307
- agent_tools,
308
- self.permission_manager,
309
- )
310
-
311
- # Execute agent
312
- await tool_ctx.info(f"Executing agent task: {prompt[:50]}...")
313
- result = await self._execute_agent_with_tools(
314
- system_prompt, prompt, agent_tools, openai_tools, tool_ctx
315
- )
316
- except Exception as e:
317
- # Log and return error result
318
- error_message = f"Error executing agent: {str(e)}"
319
- await tool_ctx.error(error_message)
320
- return f"Error: {error_message}"
321
-
322
- return result if result else "No results returned from agent"
323
-
324
- async def _execute_multiple_agents(
325
- self, prompts: list[str], tool_ctx: ToolContext
326
- ) -> str:
327
- """Execute multiple agents concurrently.
328
-
329
- Args:
330
- prompts: List of prompts for the agents
331
- tool_ctx: Tool context for logging
332
-
333
- Returns:
334
- Combined results from all agents
335
- """
336
- # Get available tools for the agents
337
- agent_tools = get_allowed_agent_tools(
338
- self.available_tools,
339
- self.permission_manager,
340
- )
341
-
342
- # Convert tools to OpenAI format
343
- openai_tools = convert_tools_to_openai_functions(agent_tools)
344
-
345
- # Create system prompt for the agents
346
- system_prompt = get_system_prompt(
347
- agent_tools,
348
- self.permission_manager,
349
- )
350
-
351
- # Create tasks for parallel execution
352
- tasks = []
353
- for i, prompt in enumerate(prompts):
354
- await tool_ctx.info(f"Creating agent task {i + 1}: {prompt[:50]}...")
355
- task = self._execute_agent_with_tools(
356
- system_prompt, prompt, agent_tools, openai_tools, tool_ctx
357
- )
358
- tasks.append(task)
359
-
360
- # Execute all agents concurrently
361
- await tool_ctx.info(f"Executing {len(tasks)} agents in parallel")
362
- results = await asyncio.gather(*tasks, return_exceptions=True)
363
-
364
- # Handle single agent case
365
- if len(results) == 1:
366
- if isinstance(results[0], Exception):
367
- await tool_ctx.error(f"Agent execution failed: {str(results[0])}")
368
- return f"Error: {str(results[0])}"
369
- return results[0]
370
-
371
- # Format results for multiple agents
372
- formatted_results = []
373
- for i, result in enumerate(results):
374
- if isinstance(result, Exception):
375
- formatted_results.append(f"Agent {i + 1} Error:\n{str(result)}")
376
- await tool_ctx.error(f"Agent {i + 1} failed: {str(result)}")
377
- else:
378
- formatted_results.append(f"Agent {i + 1} Result:\n{result}")
379
-
380
- return "\n\n---\n\n".join(formatted_results)
381
-
382
- async def _execute_agent_with_tools(
383
- self,
384
- system_prompt: str,
385
- user_prompt: str,
386
- available_tools: list[BaseTool],
387
- openai_tools: list[ChatCompletionToolParam],
388
- tool_ctx: ToolContext,
389
- ) -> str:
390
- """Execute agent with tool handling.
391
-
392
- Args:
393
- system_prompt: System prompt for the agent
394
- user_prompt: User prompt for the agent
395
- available_tools: List of available tools
396
- openai_tools: List of tools in OpenAI format
397
- tool_ctx: Tool context for logging
398
-
399
- Returns:
400
- Agent execution result
401
- """
402
- # Get model parameters and name
403
- model = get_default_model(self.model_override)
404
- params = get_model_parameters(max_tokens=self.max_tokens_override)
405
-
406
- # Initialize messages
407
- messages: Iterable[ChatCompletionMessageParam] = []
408
- messages.append({"role": "system", "content": system_prompt})
409
- messages.append({"role": "user", "content": user_prompt})
410
-
411
- # Track tool usage for metrics
412
- tool_usage = {}
413
- total_tool_use_count = 0
414
- iteration_count = 0
415
- max_tool_uses = self.max_tool_uses # Safety limit to prevent infinite loops
416
- max_iterations = (
417
- self.max_iterations
418
- ) # Add a maximum number of iterations for safety
419
-
420
- # Execute until the agent completes or reaches the limit
421
- while total_tool_use_count < max_tool_uses and iteration_count < max_iterations:
422
- iteration_count += 1
423
- await tool_ctx.info(f"Calling model (iteration {iteration_count})...")
424
-
425
- try:
426
- # Configure model parameters based on capabilities
427
- completion_params = {
428
- "model": model,
429
- "messages": messages,
430
- "tools": openai_tools,
431
- "tool_choice": "auto",
432
- "temperature": params["temperature"],
433
- "timeout": params["timeout"],
434
- }
435
-
436
- if self.api_key_override:
437
- completion_params["api_key"] = self.api_key_override
438
-
439
- # Add max_tokens if provided
440
- if params.get("max_tokens"):
441
- completion_params["max_tokens"] = params.get("max_tokens")
442
-
443
- # Add base_url if provided
444
- if self.base_url_override:
445
- completion_params["base_url"] = self.base_url_override
446
-
447
- # Make the model call
448
- response = litellm.completion(**completion_params) # pyright: ignore
449
-
450
- if len(response.choices) == 0: # pyright: ignore
451
- raise ValueError("No response choices returned")
452
-
453
- message = response.choices[0].message # pyright: ignore
454
-
455
- # Add message to conversation history
456
- messages.append(message) # pyright: ignore
457
-
458
- # If no tool calls, we're done
459
- if not message.tool_calls:
460
- return message.content or "Agent completed with no response."
461
-
462
- # Process tool calls
463
- tool_call_count = len(message.tool_calls)
464
- await tool_ctx.info(f"Processing {tool_call_count} tool calls")
465
-
466
- for tool_call in message.tool_calls:
467
- total_tool_use_count += 1
468
- function_name = tool_call.function.name
469
-
470
- # Track usage
471
- tool_usage[function_name] = tool_usage.get(function_name, 0) + 1
472
-
473
- # Log tool usage
474
- await tool_ctx.info(f"Agent using tool: {function_name}")
475
-
476
- # Parse the arguments
477
- try:
478
- function_args = json.loads(tool_call.function.arguments)
479
- except json.JSONDecodeError:
480
- function_args = {}
481
-
482
- # Find the matching tool
483
- tool = next(
484
- (t for t in available_tools if t.name == function_name), None
485
- )
486
- if not tool:
487
- tool_result = f"Error: Tool '{function_name}' not found"
488
- # Special handling for clarification requests
489
- elif function_name == "request_clarification":
490
- try:
491
- # Extract clarification parameters
492
- request_type = function_args.get("type", "ADDITIONAL_INFO")
493
- question = function_args.get("question", "")
494
- context = function_args.get("context", {})
495
- options = function_args.get("options")
496
-
497
- # Convert string type to enum
498
- clarification_type = ClarificationType[request_type]
499
-
500
- # Request clarification
501
- answer = await self.request_clarification(
502
- request_type=clarification_type,
503
- question=question,
504
- context=context,
505
- options=options,
506
- )
507
-
508
- tool_result = self.format_clarification_in_output(
509
- question, answer
510
- )
511
- except Exception as e:
512
- tool_result = f"Error processing clarification: {str(e)}"
513
- # Special handling for critic requests
514
- elif function_name == "critic":
515
- try:
516
- # Extract critic parameters
517
- review_type = function_args.get("review_type", "GENERAL")
518
- work_description = function_args.get("work_description", "")
519
- code_snippets = function_args.get("code_snippets")
520
- file_paths = function_args.get("file_paths")
521
- specific_concerns = function_args.get("specific_concerns")
522
-
523
- # Request critical review
524
- tool_result = self.critic_protocol.request_review(
525
- review_type=review_type,
526
- work_description=work_description,
527
- code_snippets=code_snippets,
528
- file_paths=file_paths,
529
- specific_concerns=specific_concerns,
530
- )
531
- except Exception as e:
532
- tool_result = f"Error processing critic review: {str(e)}"
533
- # Special handling for review requests
534
- elif function_name == "review":
535
- try:
536
- # Extract review parameters
537
- focus = function_args.get("focus", "GENERAL")
538
- work_description = function_args.get("work_description", "")
539
- code_snippets = function_args.get("code_snippets")
540
- file_paths = function_args.get("file_paths")
541
- context = function_args.get("context")
542
-
543
- # Request balanced review
544
- tool_result = self.review_protocol.request_review(
545
- focus=focus,
546
- work_description=work_description,
547
- code_snippets=code_snippets,
548
- file_paths=file_paths,
549
- context=context,
550
- )
551
- except Exception as e:
552
- tool_result = f"Error processing review: {str(e)}"
553
- else:
554
- try:
555
- tool_result = await tool.call(
556
- ctx=tool_ctx.mcp_context, **function_args
557
- )
558
- except Exception as e:
559
- tool_result = f"Error executing {function_name}: {str(e)}"
560
-
561
- await tool_ctx.info(
562
- f"tool {function_name} run with args {function_args} and return {tool_result[: min(100, len(tool_result))]}"
563
- )
564
- # Add the tool result to messages
565
- messages.append(
566
- {
567
- "role": "tool",
568
- "tool_call_id": tool_call.id,
569
- "name": function_name,
570
- "content": tool_result,
571
- }
572
- )
573
-
574
- # Log progress
575
- await tool_ctx.info(
576
- f"Processed {len(message.tool_calls)} tool calls. Total: {total_tool_use_count}"
577
- )
578
-
579
- except Exception as e:
580
- await tool_ctx.error(f"Error in model call: {str(e)}")
581
- # Avoid trying to JSON serialize message objects
582
- await tool_ctx.error(f"Message count: {len(messages)}")
583
- return f"Error in agent execution: {str(e)}"
584
-
585
- # If we've reached the limit, add a warning and get final response
586
- if total_tool_use_count >= max_tool_uses or iteration_count >= max_iterations:
587
- messages.append(
588
- {
589
- "role": "system",
590
- "content": "You have reached the maximum iteration. Please provide your final response.",
591
- }
592
- )
593
-
594
- try:
595
- # Make a final call to get the result
596
- final_response = litellm.completion(
597
- model=model,
598
- messages=messages,
599
- temperature=params["temperature"],
600
- timeout=params["timeout"],
601
- max_tokens=params.get("max_tokens"),
602
- )
603
-
604
- return (
605
- final_response.choices[0].message.content
606
- or "Agent reached max iteration limit without a response."
607
- ) # pyright: ignore
608
- except Exception as e:
609
- await tool_ctx.error(f"Error in final model call: {str(e)}")
610
- return f"Error in final response: {str(e)}"
611
-
612
- # Should not reach here but just in case
613
- return "Agent execution completed after maximum iterations."
614
-
615
- def _format_result(self, result: str, execution_time: float) -> str:
616
- """Format agent result with metrics.
617
-
618
- Args:
619
- result: Raw result from agent
620
- execution_time: Execution time in seconds
621
-
622
- Returns:
623
- Formatted result with metrics
624
- """
625
- return f"""Agent execution completed in {execution_time:.2f} seconds.
626
-
627
- AGENT RESPONSE:
628
- {result}
629
- """
630
-
631
- @override
632
- def register(self, mcp_server: FastMCP) -> None:
633
- """Register this agent tool with the MCP server.
634
-
635
- Creates a wrapper function with explicitly defined parameters that match
636
- the tool's parameter schema and registers it with the MCP server.
637
-
638
- Args:
639
- mcp_server: The FastMCP server instance
640
- """
641
- tool_self = self # Create a reference to self for use in the closure
642
-
643
- @mcp_server.tool(name=self.name, description=self.description)
644
- async def dispatch_agent(prompts: str | list[str], ctx: MCPContext) -> str:
645
- return await tool_self.call(ctx, prompts=prompts)