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

151 statements  

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

1import json 

2import time 

3import typing as t 

4from contextlib import suppress 

5from pathlib import Path 

6 

7from crackerjack.mcp.context import get_context 

8 

9 

10def _create_error_response(message: str, success: bool = False) -> str: 

11 return json.dumps({"error": message, "success": success}, indent=2) 

12 

13 

14def register_utility_tools(mcp_app: t.Any) -> None: 

15 _register_clean_tool(mcp_app) 

16 _register_config_tool(mcp_app) 

17 _register_analyze_tool(mcp_app) 

18 

19 

20def _clean_file_if_old( 

21 file_path: Path, cutoff_time: float, dry_run: bool, file_type: str 

22) -> dict | None: 

23 with suppress(OSError): 

24 if file_path.stat().st_mtime < cutoff_time: 

25 file_size = file_path.stat().st_size 

26 if not dry_run: 

27 file_path.unlink() 

28 return {"path": str(file_path), "size": file_size, "type": file_type} 

29 return None 

30 

31 

32def _clean_temp_files(cutoff_time: float, dry_run: bool) -> tuple[list[dict], int]: 

33 import tempfile 

34 

35 cleaned_files = [] 

36 total_size = 0 

37 temp_dir = Path(tempfile.gettempdir()) 

38 

39 patterns = ("crackerjack-*.log", "crackerjack - task - error-*.log", ".coverage.*") 

40 for pattern in patterns: 

41 for file_path in temp_dir.glob(pattern): 

42 file_info = _clean_file_if_old(file_path, cutoff_time, dry_run, "temp") 

43 if file_info: 

44 cleaned_files.append(file_info) 

45 total_size += file_info["size"] 

46 

47 return cleaned_files, total_size 

48 

49 

50def _clean_progress_files( 

51 context: t.Any, cutoff_time: float, dry_run: bool 

52) -> tuple[list[dict], int]: 

53 cleaned_files = [] 

54 total_size = 0 

55 

56 if context.progress_dir.exists(): 

57 for progress_file in context.progress_dir.glob("*.json"): 

58 file_info = _clean_file_if_old( 

59 progress_file, cutoff_time, dry_run, "progress" 

60 ) 

61 if file_info: 

62 cleaned_files.append(file_info) 

63 total_size += file_info["size"] 

64 

65 return cleaned_files, total_size 

66 

67 

68def _parse_cleanup_options(kwargs: str) -> tuple[dict, str | None]: 

69 try: 

70 extra_kwargs = json.loads(kwargs) if kwargs.strip() else {} 

71 return extra_kwargs, None 

72 except json.JSONDecodeError as e: 

73 return {}, f"Invalid JSON in kwargs: {e}" 

74 

75 

76def _register_clean_tool(mcp_app: t.Any) -> None: 

77 @mcp_app.tool() 

78 async def clean_crackerjack(args: str = "", kwargs: str = "{}") -> str: 

79 context = get_context() 

80 if not context: 

81 return _create_error_response("Server context not available") 

82 

83 clean_config = _parse_clean_configuration(args, kwargs) 

84 if "error" in clean_config: 

85 return _create_error_response(clean_config["error"]) 

86 

87 try: 

88 cleanup_results = _execute_cleanup_operations(context, clean_config) 

89 return _create_cleanup_response(clean_config, cleanup_results) 

90 except Exception as e: 

91 return _create_error_response(f"Cleanup failed: {e}") 

92 

93 

94def _parse_clean_configuration(args: str, kwargs: str) -> dict: 

95 extra_kwargs, parse_error = _parse_cleanup_options(kwargs) 

96 if parse_error: 

97 return {"error": parse_error} 

98 

99 return { 

100 "scope": args.strip().lower() or "all", 

101 "dry_run": extra_kwargs.get("dry_run", False), 

102 "older_than_hours": extra_kwargs.get("older_than", 24), 

103 } 

104 

105 

106def _execute_cleanup_operations(context: t.Any, clean_config: dict) -> dict: 

107 from datetime import datetime, timedelta 

108 

109 cutoff_time = ( 

110 datetime.now() - timedelta(hours=clean_config["older_than_hours"]) 

111 ).timestamp() 

112 all_cleaned_files = [] 

113 total_size = 0 

114 

115 if clean_config["scope"] in ("temp", "all"): 

116 temp_files, temp_size = _clean_temp_files(cutoff_time, clean_config["dry_run"]) 

117 all_cleaned_files.extend(temp_files) 

118 total_size += temp_size 

119 

120 if clean_config["scope"] in ("progress", "all"): 

121 progress_files, progress_size = _clean_progress_files( 

122 context, cutoff_time, clean_config["dry_run"] 

123 ) 

124 all_cleaned_files.extend(progress_files) 

125 total_size += progress_size 

126 

127 if clean_config["scope"] in ("cache", "all"): 

128 pass 

129 

130 return {"all_cleaned_files": all_cleaned_files, "total_size": total_size} 

131 

132 

133def _create_cleanup_response(clean_config: dict, cleanup_results: dict) -> str: 

134 all_cleaned_files = cleanup_results["all_cleaned_files"] 

135 

136 return json.dumps( 

137 { 

138 "success": True, 

139 "command": "clean_crackerjack", 

140 "dry_run": clean_config["dry_run"], 

141 "scope": clean_config["scope"], 

142 "older_than_hours": clean_config["older_than_hours"], 

143 "files_cleaned": len(all_cleaned_files), 

144 "total_size_bytes": cleanup_results["total_size"], 

145 "files": all_cleaned_files 

146 if len(all_cleaned_files) <= 50 

147 else all_cleaned_files[:50], 

148 }, 

149 indent=2, 

150 ) 

151 

152 

153def _handle_config_list(context: t.Any) -> dict[str, t.Any]: 

154 return { 

155 "project_path": str(context.config.project_path), 

156 "rate_limiter": { 

157 "enabled": context.rate_limiter is not None, 

158 "config": context.rate_limiter.config.__dict__ 

159 if context.rate_limiter 

160 else None, 

161 }, 

162 "progress_dir": str(context.progress_dir), 

163 "websocket_port": getattr(context, "websocket_server_port", None), 

164 } 

165 

166 

167def _handle_config_get(context: t.Any, key: str) -> dict[str, t.Any]: 

168 value = getattr(context.config, key, None) 

169 if value is None: 

170 value = getattr(context, key, "Key not found") 

171 

172 return { 

173 "success": True, 

174 "command": "config_crackerjack", 

175 "action": "get", 

176 "key": key, 

177 "value": str(value), 

178 } 

179 

180 

181def _handle_config_validate(context: t.Any) -> dict[str, t.Any]: 

182 validation_results = { 

183 "project_path_exists": context.config.project_path.exists(), 

184 "progress_dir_writable": context.progress_dir.exists() 

185 and context.progress_dir.is_dir(), 

186 "rate_limiter_configured": context.rate_limiter is not None, 

187 } 

188 

189 all_valid = all(validation_results.values()) 

190 

191 return { 

192 "success": True, 

193 "command": "config_crackerjack", 

194 "action": "validate", 

195 "valid": all_valid, 

196 "checks": validation_results, 

197 } 

198 

199 

200def _register_config_tool(mcp_app: t.Any) -> None: 

201 @mcp_app.tool() 

202 async def config_crackerjack(args: str = "", kwargs: str = "{}") -> str: 

203 context = get_context() 

204 if not context: 

205 return _create_error_response("Server context not available") 

206 

207 extra_kwargs, parse_error = _parse_cleanup_options(kwargs) 

208 if parse_error: 

209 return _create_error_response(parse_error) 

210 

211 args_parts = args.strip().split() if args.strip() else ["list"] 

212 action = args_parts[0].lower() 

213 

214 try: 

215 if action == "list": 

216 config_info = _handle_config_list(context) 

217 result = { 

218 "success": True, 

219 "command": "config_crackerjack", 

220 "action": "list", 

221 "configuration": config_info, 

222 } 

223 elif action == "get" and len(args_parts) > 1: 

224 result = _handle_config_get(context, args_parts[1]) 

225 elif action == "validate": 

226 result = _handle_config_validate(context) 

227 else: 

228 return _create_error_response( 

229 f"Invalid action '{action}'. Valid actions: list, get < key >, validate" 

230 ) 

231 

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

233 

234 except Exception as e: 

235 return _create_error_response(f"Config operation failed: {e}") 

236 

237 

238def _run_hooks_analysis(orchestrator: t.Any, options: t.Any) -> dict: 

239 fast_result = orchestrator.run_fast_hooks_only(options) 

240 comprehensive_result = orchestrator.run_comprehensive_hooks_only(options) 

241 

242 return { 

243 "fast_hooks": "passed" if fast_result else "failed", 

244 "comprehensive_hooks": "passed" if comprehensive_result else "failed", 

245 } 

246 

247 

248def _run_tests_analysis(orchestrator: t.Any, options: t.Any) -> dict: 

249 test_result = orchestrator.run_testing_phase(options) 

250 return {"status": "passed" if test_result else "failed"} 

251 

252 

253def _create_analysis_orchestrator(context: t.Any) -> t.Any: 

254 from crackerjack.core.workflow_orchestrator import WorkflowOrchestrator 

255 

256 return WorkflowOrchestrator( 

257 console=context.console, 

258 pkg_path=context.config.project_path, 

259 dry_run=True, 

260 ) 

261 

262 

263def _register_analyze_tool(mcp_app: t.Any) -> None: 

264 @mcp_app.tool() 

265 async def analyze_crackerjack(args: str = "", kwargs: str = "{}") -> str: 

266 context = get_context() 

267 if not context: 

268 return _create_error_response("Server context not available") 

269 

270 extra_kwargs, parse_error = _parse_cleanup_options(kwargs) 

271 if parse_error: 

272 return _create_error_response(parse_error) 

273 

274 scope = args.strip().lower() or "all" 

275 report_format = extra_kwargs.get("report_format", "summary") 

276 

277 try: 

278 from crackerjack.models.config import WorkflowOptions 

279 

280 orchestrator = _create_analysis_orchestrator(context) 

281 options = WorkflowOptions() 

282 analysis_results = {} 

283 

284 if scope in ("hooks", "all"): 

285 analysis_results["hooks"] = _run_hooks_analysis(orchestrator, options) 

286 

287 if scope in ("tests", "all"): 

288 analysis_results["tests"] = _run_tests_analysis(orchestrator, options) 

289 

290 return json.dumps( 

291 { 

292 "success": True, 

293 "command": "analyze_crackerjack", 

294 "scope": scope, 

295 "report_format": report_format, 

296 "dry_run": True, 

297 "timestamp": time.time(), 

298 "analysis": analysis_results, 

299 }, 

300 indent=2, 

301 ) 

302 

303 except Exception as e: 

304 return _create_error_response(f"Analysis failed: {e}")