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

146 statements  

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

1import typing as t 

2 

3from crackerjack.mcp.context import get_context 

4from crackerjack.services.input_validator import ( 

5 get_input_validator, 

6) 

7 

8 

9async def create_task_with_subagent( 

10 description: str, 

11 prompt: str, 

12 subagent_type: str, 

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

14 try: 

15 # Input validation with security checks 

16 validator = get_input_validator() 

17 

18 # Validate description 

19 desc_result = validator.validate_command_args(description) 

20 if not desc_result.valid: 

21 return { 

22 "success": False, 

23 "error": f"Invalid description: {desc_result.error_message}", 

24 "validation_type": desc_result.validation_type, 

25 } 

26 

27 # Validate prompt 

28 prompt_result = validator.validate_command_args(prompt) 

29 if not prompt_result.valid: 

30 return { 

31 "success": False, 

32 "error": f"Invalid prompt: {prompt_result.error_message}", 

33 "validation_type": prompt_result.validation_type, 

34 } 

35 

36 # Validate subagent_type (should be safe identifier) 

37 subagent_result = validator.sanitizer.sanitize_string( 

38 subagent_type, max_length=100, strict_alphanumeric=True 

39 ) 

40 if not subagent_result.valid: 

41 return { 

42 "success": False, 

43 "error": f"Invalid subagent_type: {subagent_result.error_message}", 

44 "validation_type": subagent_result.validation_type, 

45 } 

46 

47 # Use sanitized values 

48 sanitized_description = desc_result.sanitized_value or description 

49 sanitized_prompt = prompt_result.sanitized_value or prompt 

50 sanitized_subagent = subagent_result.sanitized_value 

51 

52 result = { 

53 "success": True, 

54 "description": sanitized_description, 

55 "prompt": sanitized_prompt, 

56 "subagent_type": sanitized_subagent, 

57 "result": f"Task would be executed by {sanitized_subagent}: {sanitized_prompt[:100]}...", 

58 "agent_type": "user" 

59 if sanitized_subagent 

60 not in ("general-purpose", "statusline-setup", "output-style-setup") 

61 else "system", 

62 } 

63 

64 return result 

65 

66 except Exception as e: 

67 return { 

68 "success": False, 

69 "error": f"Task creation failed: {str(e)}", 

70 "description": description, 

71 "subagent_type": subagent_type, 

72 } 

73 

74 

75async def _validate_stage_request(context, rate_limiter) -> str | None: 

76 if not context: 

77 return '{"error": "Server context not available", "success": false}' 

78 

79 if rate_limiter and hasattr(rate_limiter, "check_request_allowed"): 

80 allowed, details = await rate_limiter.check_request_allowed() 

81 if not allowed: 

82 return f'{{"error": "Rate limit exceeded: {details.get("reason", "unknown")}", "success": false}}' 

83 return None 

84 

85 

86def _parse_stage_args(args: str, kwargs: str) -> tuple[str, dict] | str: 

87 try: 

88 # Input validation 

89 validator = get_input_validator() 

90 

91 # Validate stage argument 

92 stage_result = validator.sanitizer.sanitize_string( 

93 args.strip(), max_length=50, strict_alphanumeric=True 

94 ) 

95 if not stage_result.valid: 

96 return f'{{"error": "Invalid stage argument: {stage_result.error_message}", "success": false}}' 

97 

98 stage = stage_result.sanitized_value.lower() 

99 valid_stages = {"fast", "comprehensive", "tests", "cleaning", "init"} 

100 

101 if stage not in valid_stages: 

102 return f'{{"error": "Invalid stage: {stage}. Valid stages: {valid_stages}", "success": false}}' 

103 

104 # Validate and parse JSON kwargs if provided 

105 extra_kwargs = {} 

106 if kwargs.strip(): 

107 kwargs_result = validator.validate_json_payload(kwargs.strip()) 

108 if not kwargs_result.valid: 

109 return f'{{"error": "Invalid JSON in kwargs: {kwargs_result.error_message}", "success": false}}' 

110 

111 extra_kwargs = kwargs_result.sanitized_value 

112 

113 # Additional validation on JSON structure 

114 if not isinstance(extra_kwargs, dict): 

115 return f'{{"error": "kwargs must be a JSON object, got {type(extra_kwargs).__name__}", "success": false}}' 

116 

117 return stage, extra_kwargs 

118 

119 except Exception as e: 

120 return ( 

121 f'{{"error": "Stage argument parsing failed: {str(e)}", "success": false}}' 

122 ) 

123 

124 

125def _configure_stage_options(stage: str) -> "WorkflowOptions": 

126 from crackerjack.models.config import WorkflowOptions 

127 

128 options = WorkflowOptions() 

129 if stage in {"fast", "comprehensive"}: 

130 options.skip_hooks = False 

131 elif stage == "tests": 

132 options.testing.test = True 

133 elif stage == "cleaning": 

134 options.cleaning.clean = True 

135 elif stage == "init": 

136 options.skip_hooks = True 

137 return options 

138 

139 

140def _execute_stage(orchestrator, stage: str, options) -> bool: 

141 if stage == "fast": 

142 return orchestrator.run_fast_hooks_only(options) 

143 if stage == "comprehensive": 

144 return orchestrator.run_comprehensive_hooks_only(options) 

145 if stage == "tests": 

146 return orchestrator.run_testing_phase(options) 

147 if stage == "cleaning": 

148 return orchestrator.run_cleaning_phase(options) 

149 if stage == "init": 

150 return _execute_init_stage(orchestrator) 

151 return False 

152 

153 

154def _execute_init_stage(orchestrator) -> bool: 

155 try: 

156 from pathlib import Path 

157 

158 from crackerjack.services.filesystem import FileSystemService 

159 from crackerjack.services.git import GitService 

160 from crackerjack.services.initialization import InitializationService 

161 

162 console = orchestrator.console 

163 pkg_path = orchestrator.pkg_path 

164 

165 filesystem = FileSystemService() 

166 git_service = GitService(console, pkg_path) 

167 

168 init_service = InitializationService(console, filesystem, git_service, pkg_path) 

169 

170 results = init_service.initialize_project(target_path=Path.cwd()) 

171 

172 return results.get("success", False) 

173 

174 except Exception as e: 

175 if hasattr(orchestrator, "console"): 

176 orchestrator.console.print(f"[red]❌[/ red] Initialization failed: {e}") 

177 return False 

178 

179 

180def register_core_tools(mcp_app: t.Any) -> None: 

181 @mcp_app.tool() 

182 async def run_crackerjack_stage(args: str, kwargs: str) -> str: 

183 context = get_context() 

184 rate_limiter = context.rate_limiter if context else None 

185 

186 validation_error = await _validate_stage_request(context, rate_limiter) 

187 if validation_error: 

188 return validation_error 

189 

190 try: 

191 from crackerjack.core.workflow_orchestrator import WorkflowOrchestrator 

192 

193 parse_result = _parse_stage_args(args, kwargs) 

194 if isinstance(parse_result, str): 

195 return parse_result 

196 

197 stage, extra_kwargs = parse_result 

198 

199 orchestrator = WorkflowOrchestrator( 

200 console=context.console, 

201 pkg_path=context.config.project_path, 

202 dry_run=extra_kwargs.get("dry_run", False), 

203 ) 

204 

205 options = _configure_stage_options(stage) 

206 success = _execute_stage(orchestrator, stage, options) 

207 

208 return f'{{"success": {str(success).lower()}, "stage": "{stage}"}}' 

209 

210 except Exception as e: 

211 context.safe_print(f"Error executing stage {args}: {e}") 

212 return f'{{"error": "Stage execution failed: {e}", "success": false}}' 

213 

214 

215def _get_error_patterns() -> list[tuple[str, str]]: 

216 return [ 

217 ("type_error", r"TypeError: | type object .* has no attribute"), 

218 ("import_error", r"ImportError: | ModuleNotFoundError: "), 

219 ("attribute_error", r"AttributeError: "), 

220 ("syntax_error", r"SyntaxError: | invalid syntax"), 

221 ("test_failure", r"FAILED | AssertionError: "), 

222 ("hook_failure", r"hook .* failed"), 

223 ] 

224 

225 

226def _get_error_suggestion(error_type: str) -> str: 

227 suggestions = { 

228 "type_error": "Check type annotations and ensure proper imports", 

229 "import_error": "Verify module exists and is properly installed", 

230 "test_failure": "Review test assertions and expected behavior", 

231 "hook_failure": "Run hooks individually to identify specific failures", 

232 } 

233 return suggestions.get(error_type) or "No specific suggestion available" 

234 

235 

236def _detect_errors_and_suggestions( 

237 text: str, 

238 include_suggestions: bool, 

239) -> tuple[list[str], list[str]]: 

240 import re 

241 

242 detected_errors = [] 

243 suggestions = [] 

244 

245 for error_type, pattern in _get_error_patterns(): 

246 if re.search(pattern, text, re.IGNORECASE): 

247 detected_errors.append(error_type) 

248 if include_suggestions: 

249 suggestions.append(_get_error_suggestion(error_type)) 

250 

251 return detected_errors, suggestions 

252 

253 

254def register_analyze_errors_tool(mcp_app: t.Any) -> None: 

255 @mcp_app.tool() 

256 async def analyze_errors(output: str = "", include_suggestions: bool = True) -> str: 

257 context = get_context() 

258 if not context: 

259 return '{"error": "Server context not available"}' 

260 

261 try: 

262 from crackerjack.services.debug import get_ai_agent_debugger 

263 

264 debugger = get_ai_agent_debugger() 

265 if not debugger.enabled: 

266 return '{"analysis": "Debugging not enabled", "suggestions": []}' 

267 

268 analysis_text = output or "No specific output provided" 

269 detected_errors, suggestions = _detect_errors_and_suggestions( 

270 analysis_text, 

271 include_suggestions, 

272 ) 

273 

274 result = { 

275 "analysis": f"Detected {len(detected_errors)} error types", 

276 "error_types": detected_errors, 

277 "suggestions": suggestions if include_suggestions else [], 

278 "raw_output_length": len(analysis_text), 

279 } 

280 

281 import json 

282 

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

284 

285 except Exception as e: 

286 return f'{{"error": "Error analysis failed: {e}"}}'