Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/tools/execution_tools.py: 0%

127 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import json 

2import typing as t 

3 

4from crackerjack.mcp.context import get_context 

5 

6from .error_analyzer import analyze_errors_with_caching 

7from .workflow_executor import execute_crackerjack_workflow 

8 

9 

10def register_execution_tools(mcp_app: t.Any) -> None: 

11 _register_execute_crackerjack_tool(mcp_app) 

12 _register_smart_error_analysis_tool(mcp_app) 

13 _register_init_crackerjack_tool(mcp_app) 

14 _register_agent_suggestions_tool(mcp_app) 

15 

16 

17def _register_execute_crackerjack_tool(mcp_app: t.Any) -> None: 

18 @mcp_app.tool() 

19 async def execute_crackerjack(args: str, kwargs: str) -> str: 

20 context = get_context() 

21 

22 validation_error = await _validate_context_and_rate_limit(context) 

23 if validation_error: 

24 return validation_error 

25 

26 kwargs_result = _parse_kwargs(kwargs) 

27 if "error" in kwargs_result: 

28 return json.dumps(kwargs_result) 

29 

30 extra_kwargs = kwargs_result["kwargs"] 

31 

32 try: 

33 result = await execute_crackerjack_workflow(args, extra_kwargs) 

34 return json.dumps(result, indent=2) 

35 except Exception as e: 

36 return json.dumps( 

37 { 

38 "status": "failed", 

39 "error": f"Execution failed: {e}", 

40 "timestamp": context.get_current_time() 

41 if hasattr(context, "get_current_time") 

42 else None, 

43 } 

44 ) 

45 

46 

47def _register_smart_error_analysis_tool(mcp_app: t.Any) -> None: 

48 @mcp_app.tool() 

49 async def smart_error_analysis(use_cache: bool = True) -> str: 

50 context = get_context() 

51 

52 try: 

53 analysis = analyze_errors_with_caching(context, use_cache) 

54 return json.dumps(analysis, indent=2) 

55 except Exception as e: 

56 return json.dumps( 

57 { 

58 "status": "error", 

59 "message": f"Error analysis failed: {e}", 

60 "recommendations": [], 

61 } 

62 ) 

63 

64 

65def _register_init_crackerjack_tool(mcp_app: t.Any) -> None: 

66 @mcp_app.tool() 

67 def init_crackerjack(args: str = "", kwargs: str = "{}") -> str: 

68 try: 

69 target_path, force, error = _parse_init_arguments(args, kwargs) 

70 if error: 

71 return _create_init_error_response(error) 

72 

73 result = _execute_initialization(target_path, force) 

74 return _create_init_success_response(result) 

75 

76 except Exception as e: 

77 return _create_init_exception_response(e, args) 

78 

79 

80def _register_agent_suggestions_tool(mcp_app: t.Any) -> None: 

81 @mcp_app.tool() 

82 def suggest_agents( 

83 task_description: str = "", 

84 project_type: str = "python", 

85 current_context: str = "", 

86 ) -> str: 

87 try: 

88 recommendations = _generate_agent_recommendations( 

89 task_description, project_type, current_context 

90 ) 

91 return json.dumps(recommendations, indent=2) 

92 except Exception as e: 

93 return json.dumps( 

94 { 

95 "status": "error", 

96 "message": f"Agent suggestion failed: {e}", 

97 "recommendations": {}, 

98 } 

99 ) 

100 

101 

102async def _validate_context_and_rate_limit(context: t.Any) -> str | None: 

103 if not context: 

104 return json.dumps({"status": "error", "message": "MCP context not available"}) 

105 

106 if hasattr(context, "rate_limiter"): 

107 from contextlib import suppress 

108 

109 with suppress(Exception): 

110 allowed, details = await context.rate_limiter.check_request_allowed( 

111 "execute_crackerjack" 

112 ) 

113 if not allowed: 

114 return json.dumps( 

115 { 

116 "status": "error", 

117 "message": f"Rate limit exceeded: {details}. Please wait before retrying.", 

118 } 

119 ) 

120 

121 return None 

122 

123 

124def _parse_kwargs(kwargs: str) -> dict[str, t.Any]: 

125 try: 

126 return {"kwargs": json.loads(kwargs) if kwargs.strip() else {}} 

127 except json.JSONDecodeError as e: 

128 return {"error": f"Invalid JSON in kwargs: {e}"} 

129 

130 

131def _parse_init_arguments(args: str, kwargs: str) -> tuple[t.Any, bool, str | None]: 

132 try: 

133 target_path = args.strip() or "." 

134 kwargs_dict = json.loads(kwargs) if kwargs.strip() else {} 

135 force = kwargs_dict.get("force") or False 

136 

137 from pathlib import Path 

138 

139 path_obj = Path(target_path) 

140 

141 return path_obj, force, None 

142 

143 except json.JSONDecodeError: 

144 return None, False, "Invalid JSON in kwargs parameter" 

145 except Exception as e: 

146 return None, False, f"Invalid arguments: {e}" 

147 

148 

149def _execute_initialization(target_path: t.Any, force: bool) -> dict[str, t.Any]: 

150 from rich.console import Console 

151 

152 from crackerjack.services.initialization import InitializationService 

153 

154 console = Console() 

155 

156 return InitializationService(console, target_path).initialize_project( 

157 force_update=force 

158 ) 

159 

160 

161def _create_init_error_response(message: str) -> str: 

162 return json.dumps( 

163 { 

164 "status": "error", 

165 "message": message, 

166 "initialized": False, 

167 } 

168 ) 

169 

170 

171def _create_init_success_response(result: dict[str, t.Any]) -> str: 

172 return json.dumps( 

173 { 

174 "status": "success", 

175 "message": "Crackerjack configuration initialized successfully", 

176 "result": result, 

177 "initialized": True, 

178 }, 

179 indent=2, 

180 ) 

181 

182 

183def _create_init_exception_response(error: Exception, target_path: t.Any) -> str: 

184 return json.dumps( 

185 { 

186 "status": "error", 

187 "message": f"Initialization failed: {error}", 

188 "target_path": str(target_path), 

189 "initialized": False, 

190 } 

191 ) 

192 

193 

194def _generate_agent_recommendations( 

195 task_description: str, project_type: str, current_context: str 

196) -> dict[str, t.Any]: 

197 recommendations = { 

198 "status": "success", 

199 "task_analysis": { 

200 "description": task_description, 

201 "project_type": project_type, 

202 "context": current_context, 

203 }, 

204 "suggested_agents": [], 

205 "workflow_recommendations": [], 

206 "reasoning": "", 

207 } 

208 

209 suggestions = _analyze_task_for_agents( 

210 task_description, project_type, current_context 

211 ) 

212 recommendations["suggested_agents"] = suggestions["agents"] 

213 recommendations["workflow_recommendations"] = suggestions["workflows"] 

214 recommendations["reasoning"] = suggestions["reasoning"] 

215 

216 return recommendations 

217 

218 

219def _analyze_task_for_agents( 

220 task_description: str, project_type: str, current_context: str 

221) -> dict[str, t.Any]: 

222 agents = [] 

223 workflows = [] 

224 reasoning_parts = [] 

225 

226 task_lower = task_description.lower() 

227 current_context.lower() 

228 

229 if any(keyword in task_lower for keyword in ("test", "quality", "fix", "error")): 

230 agents.extend( 

231 [ 

232 { 

233 "name": "TestCreationAgent", 

234 "reason": "Task involves testing or quality assurance", 

235 "confidence": 0.8, 

236 }, 

237 { 

238 "name": "RefactoringAgent", 

239 "reason": "Code quality improvements often require refactoring", 

240 "confidence": 0.7, 

241 }, 

242 ] 

243 ) 

244 reasoning_parts.append("Task involves testing or quality improvement") 

245 

246 if any( 

247 keyword in task_lower for keyword in ("security", "vulnerability", "secure") 

248 ): 

249 agents.append( 

250 { 

251 "name": "SecurityAgent", 

252 "reason": "Task involves security considerations", 

253 "confidence": 0.9, 

254 } 

255 ) 

256 reasoning_parts.append("Security concerns detected") 

257 

258 if any( 

259 keyword in task_lower 

260 for keyword in ("performance", "optimize", "speed", "slow") 

261 ): 

262 agents.append( 

263 { 

264 "name": "PerformanceAgent", 

265 "reason": "Task involves performance optimization", 

266 "confidence": 0.8, 

267 } 

268 ) 

269 reasoning_parts.append("Performance optimization required") 

270 

271 if any( 

272 keyword in task_lower for keyword in ("document", "readme", "doc", "explain") 

273 ): 

274 agents.append( 

275 { 

276 "name": "DocumentationAgent", 

277 "reason": "Task involves documentation work", 

278 "confidence": 0.8, 

279 } 

280 ) 

281 reasoning_parts.append("Documentation work identified") 

282 

283 if any( 

284 keyword in task_lower 

285 for keyword in ("import", "dependency", "package", "module") 

286 ): 

287 agents.append( 

288 { 

289 "name": "ImportOptimizationAgent", 

290 "reason": "Task involves import or dependency management", 

291 "confidence": 0.7, 

292 } 

293 ) 

294 reasoning_parts.append("Import / dependency work detected") 

295 

296 if project_type == "python": 

297 workflows.extend( 

298 [ 

299 "Run quality checks with AI agent auto-fixing", 

300 "Use comprehensive testing with coverage tracking", 

301 "Apply refactoring for code clarity", 

302 ] 

303 ) 

304 

305 if not agents: 

306 agents.append( 

307 { 

308 "name": "RefactoringAgent", 

309 "reason": "Default agent for general code improvement tasks", 

310 "confidence": 0.5, 

311 } 

312 ) 

313 reasoning_parts.append("General code improvement task") 

314 

315 reasoning = "; ".join(reasoning_parts) 

316 

317 return {"agents": agents, "workflows": workflows, "reasoning": reasoning}