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

235 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 

5 

6from crackerjack.mcp.context import get_context 

7from crackerjack.services.bounded_status_operations import ( 

8 execute_bounded_status_operation, 

9) 

10from crackerjack.services.secure_status_formatter import ( 

11 StatusVerbosity, 

12 format_secure_status, 

13 get_secure_status_formatter, 

14) 

15from crackerjack.services.status_authentication import ( 

16 authenticate_status_request, 

17 get_status_authenticator, 

18) 

19from crackerjack.services.status_security_manager import ( 

20 get_status_security_manager, 

21 secure_status_operation, 

22 validate_status_request, 

23) 

24from crackerjack.services.thread_safe_status_collector import ( 

25 get_thread_safe_status_collector, 

26) 

27from crackerjack.services.websocket_resource_limiter import ( 

28 get_websocket_resource_limiter, 

29) 

30 

31 

32def _suggest_agent_for_context(state_manager) -> dict[str, t.Any]: 

33 suggestions = { 

34 "recommended_agent": None, 

35 "reason": "", 

36 "usage": "", 

37 "priority": "MEDIUM", 

38 } 

39 

40 with suppress(Exception): 

41 recent_errors = getattr(state_manager, "recent_errors", []) 

42 stage_statuses = _get_stage_status_dict(state_manager) 

43 

44 if stage_statuses.get("tests") == "failed" or any( 

45 "test" in str(error).lower() for error in recent_errors 

46 ): 

47 suggestions.update( 

48 { 

49 "recommended_agent": "crackerjack - test-specialist", 

50 "reason": "Test failures detected-specialist needed for debugging and fixes", 

51 "usage": 'Task tool with subagent_type ="crackerjack - test-specialist"', 

52 "priority": "HIGH", 

53 } 

54 ) 

55 

56 elif any( 

57 "security" in str(error).lower() or "bandit" in str(error).lower() 

58 for error in recent_errors 

59 ): 

60 suggestions.update( 

61 { 

62 "recommended_agent": "security-auditor", 

63 "reason": "Security issues detected-immediate audit required", 

64 "usage": 'Task tool with subagent_type ="security-auditor"', 

65 "priority": "HIGH", 

66 } 

67 ) 

68 

69 elif any("complex" in str(error).lower() for error in recent_errors): 

70 suggestions.update( 

71 { 

72 "recommended_agent": "crackerjack-architect", 

73 "reason": "Complexity issues detected-architectural review needed", 

74 "usage": 'Task tool with subagent_type ="crackerjack-architect"', 

75 "priority": "HIGH", 

76 } 

77 ) 

78 

79 else: 

80 suggestions.update( 

81 { 

82 "recommended_agent": "crackerjack-architect", 

83 "reason": "Python project-ensure crackerjack compliance from the start", 

84 "usage": 'Task tool with subagent_type ="crackerjack-architect"', 

85 "priority": "MEDIUM", 

86 } 

87 ) 

88 

89 return suggestions 

90 

91 

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

93 import json 

94 

95 return json.dumps({"error": message, "success": success}) 

96 

97 

98def _get_stage_status_dict(state_manager) -> dict[str, str]: 

99 stages = ["fast", "comprehensive", "tests", "cleaning"] 

100 return {stage: state_manager.get_stage_status(stage) for stage in stages} 

101 

102 

103def _get_session_info(state_manager) -> dict[str, t.Any]: 

104 return { 

105 "total_iterations": getattr(state_manager, "iteration_count", 0), 

106 "current_iteration": getattr(state_manager, "current_iteration", 0), 

107 "session_active": getattr(state_manager, "session_active", False), 

108 } 

109 

110 

111def _determine_next_action(state_manager) -> dict[str, t.Any]: 

112 stage_priorities = [ 

113 ("fast", "Fast hooks not completed"), 

114 ("tests", "Tests not completed"), 

115 ("comprehensive", "Comprehensive hooks not completed"), 

116 ] 

117 

118 for stage, reason in stage_priorities: 

119 if state_manager.get_stage_status(stage) != "completed": 

120 return { 

121 "recommended_action": "run_stage", 

122 "parameters": {"stage": stage}, 

123 "reason": reason, 

124 } 

125 

126 return { 

127 "recommended_action": "complete", 

128 "parameters": {}, 

129 "reason": "All stages completed successfully", 

130 } 

131 

132 

133def _build_server_stats(context) -> dict[str, t.Any]: 

134 return { 

135 "server_info": { 

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

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

138 "websocket_active": getattr(context, "websocket_server_process", None) 

139 is not None, 

140 }, 

141 "rate_limiting": { 

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

143 "config": context.rate_limiter.config.__dict__ 

144 if context.rate_limiter 

145 else None, 

146 }, 

147 "resource_usage": { 

148 "temp_files_count": len(list(context.progress_dir.glob("*.json"))) 

149 if context.progress_dir.exists() 

150 else 0, 

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

152 }, 

153 "timestamp": time.time(), 

154 } 

155 

156 

157def _add_state_manager_stats(stats: dict, state_manager) -> None: 

158 if state_manager: 

159 stats["state_manager"] = { 

160 "iteration_count": getattr(state_manager, "iteration_count", 0), 

161 "session_active": getattr(state_manager, "session_active", False), 

162 "issues_count": len(getattr(state_manager, "issues", [])), 

163 } 

164 

165 

166def _get_active_jobs(context) -> list[dict[str, t.Any]]: 

167 jobs = [] 

168 if not context.progress_dir.exists(): 

169 return jobs 

170 

171 with suppress(Exception): 

172 for progress_file in context.progress_dir.glob("job-*.json"): 

173 try: 

174 progress_data = json.loads(progress_file.read_text()) 

175 jobs.append( 

176 { 

177 "job_id": progress_data.get("job_id", "unknown"), 

178 "status": progress_data.get("status", "unknown"), 

179 "iteration": progress_data.get("iteration", 0), 

180 "max_iterations": progress_data.get("max_iterations", 10), 

181 "current_stage": progress_data.get("current_stage", "unknown"), 

182 "overall_progress": progress_data.get("overall_progress", 0), 

183 "stage_progress": progress_data.get("stage_progress", 0), 

184 "message": progress_data.get("message", ""), 

185 "timestamp": progress_data.get("timestamp", ""), 

186 "error_counts": progress_data.get("error_counts", {}), 

187 }, 

188 ) 

189 except (json.JSONDecodeError, KeyError): 

190 continue 

191 

192 return jobs 

193 

194 

195async def _get_comprehensive_status_secure( 

196 client_id: str = "mcp_client", 

197 client_ip: str = "127.0.0.1", 

198 auth_header: str | None = None, 

199 verbosity: StatusVerbosity = StatusVerbosity.STANDARD, 

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

201 """Get comprehensive status with full security integration.""" 

202 

203 # 1. Authentication 

204 auth_manager = get_status_authenticator() 

205 try: 

206 credentials = await authenticate_status_request( 

207 auth_header, client_ip, "get_comprehensive_status" 

208 ) 

209 

210 # Check if operation is allowed for this auth level 

211 if not auth_manager.is_operation_allowed( 

212 "get_comprehensive_status", credentials.access_level 

213 ): 

214 return {"error": "Insufficient privileges for comprehensive status"} 

215 

216 except Exception as e: 

217 return {"error": f"Authentication failed: {e}"} 

218 

219 # 2. Security validation 

220 try: 

221 await validate_status_request(client_id, "get_comprehensive_status", {}) 

222 except Exception as e: 

223 return {"error": f"Security validation failed: {e}"} 

224 

225 # 3. Resource management with bounded operations 

226 try: 

227 return await execute_bounded_status_operation( 

228 "status_collection", 

229 client_id, 

230 _collect_comprehensive_status_internal, 

231 client_id=client_id, 

232 verbosity=verbosity, 

233 ) 

234 except Exception as e: 

235 return {"error": f"Resource limit exceeded: {e}"} 

236 

237 

238async def _collect_comprehensive_status_internal( 

239 client_id: str = "mcp_client", 

240 verbosity: StatusVerbosity = StatusVerbosity.STANDARD, 

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

242 """Internal comprehensive status collection using thread-safe collector.""" 

243 

244 # Use thread-safe status collector 

245 collector = get_thread_safe_status_collector() 

246 

247 try: 

248 # Collect status with thread safety and proper timeout handling 

249 snapshot = await collector.collect_comprehensive_status( 

250 client_id=client_id, 

251 include_jobs=True, 

252 include_services=True, 

253 include_stats=True, 

254 ) 

255 

256 # Build final status from snapshot 

257 status = { 

258 "services": snapshot.services, 

259 "jobs": snapshot.jobs, 

260 "server_stats": snapshot.server_stats, 

261 "collection_info": { 

262 "timestamp": snapshot.timestamp, 

263 "duration": snapshot.collection_duration, 

264 "is_complete": snapshot.is_complete, 

265 "errors": snapshot.errors, 

266 }, 

267 } 

268 

269 # Add agent suggestions if available 

270 context = None 

271 try: 

272 context = get_context() 

273 except RuntimeError: 

274 pass 

275 

276 if context: 

277 state_manager = getattr(context, "state_manager", None) 

278 if state_manager: 

279 status["agent_suggestions"] = _suggest_agent_for_context(state_manager) 

280 

281 return status 

282 

283 except Exception as e: 

284 return {"error": f"Failed to collect comprehensive status: {e}"} 

285 

286 

287async def _get_comprehensive_status() -> dict[str, t.Any]: 

288 """Legacy wrapper for backward compatibility.""" 

289 return await _get_comprehensive_status_secure() 

290 try: 

291 context = get_context() 

292 except RuntimeError: 

293 context = None 

294 

295 if not context: 

296 return {"error": "Server context not available"} 

297 

298 try: 

299 from crackerjack.services.server_manager import ( 

300 find_mcp_server_processes, 

301 find_websocket_server_processes, 

302 ) 

303 

304 mcp_processes = find_mcp_server_processes() 

305 websocket_processes = find_websocket_server_processes() 

306 

307 active_jobs = _get_active_jobs(context) 

308 

309 websocket_status = None 

310 try: 

311 websocket_status = await context.get_websocket_server_status() 

312 except (ConnectionError, TimeoutError) as e: 

313 websocket_status = {"error": f"Connection failed: {e}"} 

314 except Exception as e: 

315 websocket_status = {"error": f"Status unavailable: {e}"} 

316 

317 status = { 

318 "services": { 

319 "mcp_server": { 

320 "running": len(mcp_processes) > 0, 

321 "processes": mcp_processes, 

322 }, 

323 "websocket_server": { 

324 "running": len(websocket_processes) > 0, 

325 "processes": websocket_processes, 

326 "port": getattr(context, "websocket_server_port", 8675), 

327 "status": websocket_status, 

328 }, 

329 }, 

330 "jobs": { 

331 "active_count": len( 

332 [j for j in active_jobs if j["status"] == "running"], 

333 ), 

334 "completed_count": len( 

335 [j for j in active_jobs if j["status"] == "completed"], 

336 ), 

337 "failed_count": len( 

338 [j for j in active_jobs if j["status"] == "failed"], 

339 ), 

340 "details": active_jobs, 

341 }, 

342 "server_stats": _build_server_stats(context), 

343 "timestamp": time.time(), 

344 } 

345 

346 state_manager = getattr(context, "state_manager", None) 

347 _add_state_manager_stats(status["server_stats"], state_manager) 

348 

349 if state_manager: 

350 status["agent_suggestions"] = _suggest_agent_for_context(state_manager) 

351 

352 return status 

353 

354 except Exception as e: 

355 return {"error": f"Failed to get comprehensive status: {e}"} 

356 

357 

358def register_monitoring_tools(mcp_app: t.Any) -> None: 

359 _register_stage_status_tool(mcp_app) 

360 _register_next_action_tool(mcp_app) 

361 _register_server_stats_tool(mcp_app) 

362 _register_comprehensive_status_tool(mcp_app) 

363 _register_command_help_tool(mcp_app) 

364 _register_filtered_status_tool(mcp_app) 

365 

366 

367def _register_stage_status_tool(mcp_app: t.Any) -> None: 

368 @mcp_app.tool() 

369 async def get_stage_status() -> str: 

370 client_id = "mcp_client" 

371 

372 try: 

373 # Security validation 

374 await validate_status_request(client_id, "get_stage_status", {}) 

375 

376 context = get_context() 

377 if not context: 

378 return _create_error_response("Server context not available") 

379 

380 state_manager = getattr(context, "state_manager", None) 

381 if not state_manager: 

382 return _create_error_response("State manager not available") 

383 

384 # Use bounded operation for resource protection 

385 result = await execute_bounded_status_operation( 

386 "stage_status", 

387 client_id, 

388 _build_stage_status, 

389 state_manager, 

390 ) 

391 

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

393 

394 except Exception as e: 

395 return f'{{"error": "Failed to get stage status: {e}"}}' 

396 

397 

398def _build_stage_status(state_manager) -> dict[str, t.Any]: 

399 """Build stage status with bounded resource usage.""" 

400 return { 

401 "stages": _get_stage_status_dict(state_manager), 

402 "session": _get_session_info(state_manager), 

403 "timestamp": time.time(), 

404 } 

405 

406 

407def _register_next_action_tool(mcp_app: t.Any) -> None: 

408 @mcp_app.tool() 

409 async def get_next_action() -> str: 

410 client_id = "mcp_client" 

411 

412 try: 

413 # Security validation 

414 await validate_status_request(client_id, "get_next_action", {}) 

415 

416 context = get_context() 

417 if not context: 

418 return _create_error_response("Server context not available") 

419 

420 state_manager = getattr(context, "state_manager", None) 

421 if not state_manager: 

422 return '{"recommended_action": "initialize", "reason": "No state manager available"}' 

423 

424 # Use bounded operation for consistency 

425 action = await execute_bounded_status_operation( 

426 "next_action", 

427 client_id, 

428 _determine_next_action, 

429 state_manager, 

430 ) 

431 

432 return json.dumps(action, indent=2) 

433 

434 except Exception as e: 

435 return f'{{"error": "Failed to determine next action: {e}"}}' 

436 

437 

438def _register_server_stats_tool(mcp_app: t.Any) -> None: 

439 @mcp_app.tool() 

440 async def get_server_stats() -> str: 

441 client_id = "mcp_client" 

442 

443 try: 

444 # Security validation 

445 await validate_status_request(client_id, "get_server_stats", {}) 

446 

447 # Use secure status operation with resource limits 

448 async with await secure_status_operation( 

449 client_id, "get_server_stats", timeout=15.0 

450 ): 

451 # Get context 

452 context = get_context() 

453 if not context: 

454 formatter = get_secure_status_formatter() 

455 error_response = formatter.format_error_response( 

456 "Server context not available", 

457 verbosity=StatusVerbosity.STANDARD, 

458 ) 

459 return json.dumps(error_response, indent=2) 

460 

461 # Get raw stats with bounded operation 

462 raw_stats = await execute_bounded_status_operation( 

463 "server_stats", 

464 client_id, 

465 _build_server_stats_secure, 

466 context, 

467 ) 

468 

469 # Apply secure formatting 

470 secure_stats = format_secure_status( 

471 raw_stats, 

472 verbosity=StatusVerbosity.STANDARD, 

473 project_root=context.config.project_path, 

474 user_context="mcp_client", 

475 ) 

476 

477 return json.dumps(secure_stats, indent=2) 

478 

479 except Exception as e: 

480 # Use secure error formatting 

481 formatter = get_secure_status_formatter() 

482 error_response = formatter.format_error_response( 

483 str(e), 

484 verbosity=StatusVerbosity.STANDARD, 

485 ) 

486 return json.dumps(error_response, indent=2) 

487 

488 

489def _build_server_stats_secure(context) -> dict[str, t.Any]: 

490 """Build server stats with security controls.""" 

491 

492 # Build base stats 

493 stats = _build_server_stats(context) 

494 

495 # Add state manager stats 

496 state_manager = getattr(context, "state_manager", None) 

497 _add_state_manager_stats(stats, state_manager) 

498 

499 # Add security status 

500 security_manager = get_status_security_manager() 

501 stats["security_status"] = security_manager.get_security_status() 

502 

503 # Add resource limiter status if available 

504 try: 

505 resource_limiter = get_websocket_resource_limiter() 

506 stats["websocket_resources"] = resource_limiter.get_resource_status() 

507 except Exception: 

508 # Resource limiter may not be initialized 

509 pass 

510 

511 return stats 

512 

513 

514def _register_comprehensive_status_tool(mcp_app: t.Any) -> None: 

515 @mcp_app.tool() 

516 async def get_comprehensive_status() -> str: 

517 client_id = "mcp_client" 

518 client_ip = "127.0.0.1" 

519 

520 try: 

521 # Use secure status operation with request lock 

522 async with await secure_status_operation( 

523 client_id, "get_comprehensive_status", timeout=30.0 

524 ): 

525 # Get raw status data with full security integration 

526 raw_status = await _get_comprehensive_status_secure( 

527 client_id=client_id, 

528 client_ip=client_ip, 

529 auth_header=None, # Local-only access 

530 verbosity=StatusVerbosity.STANDARD, 

531 ) 

532 

533 # Apply secure formatting 

534 context = get_context() 

535 project_root = context.config.project_path if context else None 

536 

537 secure_status = format_secure_status( 

538 raw_status, 

539 verbosity=StatusVerbosity.STANDARD, 

540 project_root=project_root, 

541 user_context="mcp_client", 

542 ) 

543 

544 return json.dumps(secure_status, indent=2) 

545 

546 except Exception as e: 

547 # Use secure error formatting 

548 formatter = get_secure_status_formatter() 

549 error_response = formatter.format_error_response( 

550 str(e), 

551 verbosity=StatusVerbosity.STANDARD, 

552 include_details=False, 

553 ) 

554 return json.dumps(error_response, indent=2) 

555 

556 

557def _register_command_help_tool(mcp_app: t.Any) -> None: 

558 @mcp_app.tool() 

559 async def list_slash_commands() -> str: 

560 try: 

561 commands = { 

562 "/ crackerjack: run": { 

563 "description": "Run full iterative auto-fixing with AI agent, tests, progress tracking, and verbose output", 

564 "usage": "Direct execution-no parameters needed", 

565 "features": [ 

566 "Up to 10 iterations of quality improvement", 

567 "Real-time WebSocket progress streaming", 

568 "Advanced orchestrator with adaptive strategies", 

569 "Automatic service management", 

570 "Debug mode support", 

571 ], 

572 }, 

573 "/ crackerjack: status": { 

574 "description": "Get comprehensive system status including servers, jobs, and resource usage", 

575 "usage": "Direct execution-no parameters needed", 

576 "features": [ 

577 "MCP server health monitoring", 

578 "WebSocket server status", 

579 "Active job tracking", 

580 "Resource usage metrics", 

581 "Error counts and progress data", 

582 ], 

583 }, 

584 "/ crackerjack: init": { 

585 "description": "Initialize or update crackerjack configuration with smart configuration merging", 

586 "usage": "Optional parameters: target_path (defaults to current directory)", 

587 "kwargs": { 

588 "force": "boolean-force overwrite existing configurations" 

589 }, 

590 "features": [ 

591 "Smart merge preserving existing configurations", 

592 "Universal Python project compatibility", 

593 "pyproject.toml and pre-commit setup", 

594 "Documentation and MCP configuration", 

595 "Non-destructive configuration updates", 

596 ], 

597 }, 

598 } 

599 

600 return json.dumps( 

601 { 

602 "available_commands": list(commands.keys()), 

603 "command_details": commands, 

604 "total_commands": len(commands), 

605 }, 

606 indent=2, 

607 ) 

608 

609 except Exception as e: 

610 return json.dumps( 

611 {"error": f"Failed to list slash commands: {e}", "success": False}, 

612 indent=2, 

613 ) 

614 

615 

616def _validate_status_components(components: str) -> tuple[set[str], str | None]: 

617 valid_components = {"services", "jobs", "resources", "all"} 

618 requested = {c.strip().lower() for c in components.split(", ")} 

619 

620 invalid = requested - valid_components 

621 if invalid: 

622 return set(), f"Invalid components: {invalid}. Valid: {valid_components}" 

623 

624 return requested, None 

625 

626 

627def _get_services_status() -> dict: 

628 from crackerjack.services.server_manager import ( 

629 find_mcp_server_processes, 

630 find_websocket_server_processes, 

631 ) 

632 

633 mcp_processes = find_mcp_server_processes() 

634 websocket_processes = find_websocket_server_processes() 

635 

636 return { 

637 "mcp_server": { 

638 "running": len(mcp_processes) > 0, 

639 "processes": mcp_processes, 

640 }, 

641 "websocket_server": { 

642 "running": len(websocket_processes) > 0, 

643 "processes": websocket_processes, 

644 }, 

645 } 

646 

647 

648def _get_resources_status(context: t.Any) -> dict: 

649 temp_files_count = ( 

650 len(list(context.progress_dir.glob("*.json"))) 

651 if context.progress_dir.exists() 

652 else 0 

653 ) 

654 

655 return { 

656 "temp_files_count": temp_files_count, 

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

658 } 

659 

660 

661def _build_filtered_status(requested: set[str], context: t.Any) -> dict: 

662 filtered_status = {"timestamp": time.time()} 

663 

664 if "services" in requested: 

665 filtered_status["services"] = _get_services_status() 

666 

667 if "jobs" in requested: 

668 filtered_status["jobs"] = {"active": _get_active_jobs(context)} 

669 

670 if "resources" in requested: 

671 filtered_status["resources"] = _get_resources_status(context) 

672 

673 return filtered_status 

674 

675 

676def _register_filtered_status_tool(mcp_app: t.Any) -> None: 

677 @mcp_app.tool() 

678 async def get_filtered_status(components: str = "all") -> str: 

679 client_id = "mcp_client" 

680 

681 try: 

682 # Security validation with component filter data 

683 await validate_status_request( 

684 client_id, "get_filtered_status", {"components": components} 

685 ) 

686 

687 requested, error = _validate_status_components(components) 

688 if error: 

689 formatter = get_secure_status_formatter() 

690 error_response = formatter.format_error_response( 

691 error, 

692 verbosity=StatusVerbosity.STANDARD, 

693 ) 

694 return json.dumps(error_response, indent=2) 

695 

696 # Use secure status operation with timeout 

697 async with await secure_status_operation( 

698 client_id, "get_filtered_status", timeout=20.0 

699 ): 

700 context = get_context() 

701 

702 if "all" in requested: 

703 raw_status = await _get_comprehensive_status_secure( 

704 client_id=client_id, 

705 client_ip="127.0.0.1", 

706 verbosity=StatusVerbosity.STANDARD, 

707 ) 

708 else: 

709 if not context: 

710 formatter = get_secure_status_formatter() 

711 error_response = formatter.format_error_response( 

712 "Server context not available", 

713 verbosity=StatusVerbosity.STANDARD, 

714 ) 

715 return json.dumps(error_response, indent=2) 

716 

717 # Use bounded operation for filtered status 

718 raw_status = await execute_bounded_status_operation( 

719 "filtered_status", 

720 client_id, 

721 _build_filtered_status, 

722 requested, 

723 context, 

724 ) 

725 

726 # Apply secure formatting 

727 project_root = context.config.project_path if context else None 

728 secure_status = format_secure_status( 

729 raw_status, 

730 verbosity=StatusVerbosity.STANDARD, 

731 project_root=project_root, 

732 user_context="mcp_client", 

733 ) 

734 

735 return json.dumps(secure_status, indent=2) 

736 

737 except Exception as e: 

738 formatter = get_secure_status_formatter() 

739 error_response = formatter.format_error_response( 

740 str(e), 

741 verbosity=StatusVerbosity.STANDARD, 

742 ) 

743 return json.dumps(error_response, indent=2)