Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/tools/execution_tools_backup.py: 0%
355 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1import asyncio
2import json
3import time
4import typing as t
5import uuid
6from contextlib import suppress
8from crackerjack.mcp.context import get_context
10from .progress_tools import _update_progress
13def register_execution_tools(mcp_app: t.Any) -> None:
14 _register_execute_crackerjack_tool(mcp_app)
15 _register_smart_error_analysis_tool(mcp_app)
16 _register_init_crackerjack_tool(mcp_app)
17 _register_agent_suggestions_tool(mcp_app)
20def _register_execute_crackerjack_tool(mcp_app: t.Any) -> None:
21 @mcp_app.tool()
22 async def execute_crackerjack(args: str, kwargs: str) -> str:
23 context = get_context()
24 validation_error = await _validate_context_and_rate_limit(context)
25 if validation_error:
26 return validation_error
28 job_id = str(uuid.uuid4())[:8]
30 kwargs_result = _parse_kwargs(kwargs)
31 if "error" in kwargs_result:
32 return json.dumps(kwargs_result)
34 extra_kwargs = kwargs_result["kwargs"]
36 try:
37 result = await _execute_crackerjack_sync(
38 job_id,
39 args,
40 extra_kwargs,
41 context,
42 )
43 return json.dumps(result, indent=2)
44 except Exception as e:
45 return json.dumps(
46 {
47 "job_id": job_id,
48 "status": "failed",
49 "error": f"Execution failed: {e}",
50 },
51 indent=2,
52 )
55def _register_smart_error_analysis_tool(mcp_app: t.Any) -> None:
56 @mcp_app.tool()
57 async def smart_error_analysis(use_cache: bool = True) -> str:
58 context = get_context()
59 if not context:
60 return '{"error": "Server context not available"}'
62 try:
63 from crackerjack.services.debug import get_ai_agent_debugger
65 get_ai_agent_debugger()
67 cached_patterns = _get_cached_patterns(context, use_cache)
68 analysis = _build_error_analysis(use_cache, cached_patterns)
70 return json.dumps(analysis, indent=2)
72 except Exception as e:
73 return f'{{"error": "Smart error analysis failed: {e}"}}'
76async def _validate_context_and_rate_limit(context: t.Any) -> str | None:
77 if not context:
78 return '{"error": "Server context not available"}'
80 if context.rate_limiter:
81 allowed, details = await context.rate_limiter.check_request_allowed("default")
82 if not allowed:
83 return f'{{"error": "Rate limit exceeded: {details.get("reason", "unknown")}", "success": false}}'
85 return None
88def _handle_task_exception(job_id: str, task: asyncio.Task) -> None:
89 import tempfile
90 from pathlib import Path
92 try:
93 exception = task.exception()
94 if exception:
95 debug_file = (
96 Path(tempfile.gettempdir()) / f"crackerjack - task-error -{job_id}.log"
97 )
98 with debug_file.open("w") as f:
99 f.write(
100 f"Background task {job_id} failed with exception: {exception}\n",
101 )
102 f.write(f"Exception type: {type(exception)}\n")
103 import traceback
105 f.write(
106 f"Traceback: \n{traceback.format_exception(type(exception), exception, exception.__traceback__)}\n",
107 )
108 except Exception as e:
109 with suppress(Exception):
110 debug_file = (
111 Path(tempfile.gettempdir())
112 / f"crackerjack - logging-error -{job_id}.log"
113 )
114 with debug_file.open("w") as f:
115 f.write(f"Failed to log task exception: {e}\n")
118def _parse_kwargs(kwargs: str) -> dict[str, t.Any]:
119 try:
120 return {"kwargs": json.loads(kwargs) if kwargs.strip() else {}}
121 except json.JSONDecodeError as e:
122 return {"error": f"Invalid JSON in kwargs: {e}"}
125def _get_cached_patterns(context: t.Any, use_cache: bool) -> list[t.Any]:
126 if use_cache and hasattr(context, "error_cache"):
127 return getattr(context.error_cache, "patterns", [])
128 return []
131def _build_error_analysis(
132 use_cache: bool,
133 cached_patterns: list[t.Any],
134) -> dict[str, t.Any]:
135 analysis = {
136 "analysis_type": "smart_error_analysis",
137 "use_cache": use_cache,
138 "cached_patterns_count": len(cached_patterns),
139 "common_patterns": [
140 {
141 "type": "import_error",
142 "frequency": "high",
143 "typical_fix": "Check import paths and dependencies",
144 },
145 {
146 "type": "type_annotation_missing",
147 "frequency": "medium",
148 "typical_fix": "Add proper type hints to functions and methods",
149 },
150 {
151 "type": "test_failure",
152 "frequency": "medium",
153 "typical_fix": "Review test expectations and implementation",
154 },
155 ],
156 "recommendations": [
157 "Run fast hooks first to fix formatting issues",
158 "Execute tests to identify functional problems",
159 "Run comprehensive hooks for quality analysis",
160 ],
161 }
163 if cached_patterns:
164 analysis["cached_patterns"] = cached_patterns[:5]
166 return analysis
169async def _execute_crackerjack_sync(
170 job_id: str,
171 args: str,
172 kwargs: dict[str, t.Any],
173 context: t.Any,
174) -> dict[str, t.Any]:
175 if not context:
176 return {"job_id": job_id, "status": "failed", "error": "No context available"}
178 max_iterations = kwargs.get("max_iterations", 10)
179 current_iteration = 1
181 try:
182 await _initialize_execution(job_id, max_iterations, current_iteration, context)
184 orchestrator, use_advanced_orchestrator = await _setup_orchestrator(
185 job_id,
186 max_iterations,
187 current_iteration,
188 kwargs,
189 context,
190 )
192 return await _run_workflow_iterations(
193 job_id,
194 max_iterations,
195 orchestrator,
196 use_advanced_orchestrator,
197 kwargs,
198 )
200 except Exception as e:
201 _update_progress(
202 job_id=job_id,
203 status="failed",
204 iteration=current_iteration,
205 max_iterations=max_iterations,
206 current_stage="error",
207 message=f"Execution failed: {e}",
208 )
209 context.safe_print(f"Execution failed: {e}")
210 return {"job_id": job_id, "status": "failed", "error": str(e)}
213async def _initialize_execution(
214 job_id: str,
215 max_iterations: int,
216 current_iteration: int,
217 context: t.Any,
218) -> None:
219 _update_progress(
220 job_id=job_id,
221 iteration=current_iteration,
222 max_iterations=max_iterations,
223 overall_progress=2,
224 message="Initializing crackerjack execution",
225 )
227 status_result = await _check_status_and_prepare(job_id, context)
228 if status_result.get("should_abort", False):
229 msg = f"Execution aborted: {status_result['reason']}"
230 raise RuntimeError(msg)
232 _update_progress(
233 job_id=job_id,
234 iteration=current_iteration,
235 max_iterations=max_iterations,
236 overall_progress=5,
237 current_stage="status_verified",
238 message="Status check complete-no conflicts detected",
239 )
241 await _cleanup_stale_jobs(context)
243 await _ensure_services_running(job_id, context)
245 _update_progress(
246 job_id=job_id,
247 iteration=current_iteration,
248 max_iterations=max_iterations,
249 overall_progress=10,
250 current_stage="services_ready",
251 message="Services initialized successfully",
252 )
255async def _setup_orchestrator(
256 job_id: str,
257 max_iterations: int,
258 current_iteration: int,
259 kwargs: dict[str, t.Any],
260 context: t.Any,
261) -> tuple[t.Any, bool]:
262 context.safe_print("Using Standard WorkflowOrchestrator for MCP compatibility")
263 orchestrator = _create_standard_orchestrator(job_id, kwargs, context)
264 use_advanced_orchestrator = False
266 orchestrator_type = "Standard Orchestrator (MCP Compatible)"
267 _update_progress(
268 job_id=job_id,
269 iteration=current_iteration,
270 max_iterations=max_iterations,
271 overall_progress=15,
272 current_stage="orchestrator_ready",
273 message=f"Initialized {orchestrator_type}",
274 )
276 return orchestrator, use_advanced_orchestrator
279async def _create_advanced_orchestrator(
280 job_id: str,
281 kwargs: dict[str, t.Any],
282 context: t.Any,
283) -> t.Any:
284 from crackerjack.core.session_coordinator import SessionCoordinator
285 from crackerjack.orchestration.advanced_orchestrator import (
286 AdvancedWorkflowOrchestrator,
287 )
288 from crackerjack.orchestration.execution_strategies import (
289 AICoordinationMode,
290 AIIntelligence,
291 ExecutionStrategy,
292 OrchestrationConfig,
293 ProgressLevel,
294 StreamingMode,
295 )
297 optimal_config = OrchestrationConfig(
298 execution_strategy=ExecutionStrategy.ADAPTIVE,
299 progress_level=ProgressLevel.DETAILED,
300 streaming_mode=StreamingMode.WEBSOCKET,
301 ai_coordination_mode=AICoordinationMode.COORDINATOR,
302 ai_intelligence=AIIntelligence.ADAPTIVE,
303 correlation_tracking=True,
304 failure_analysis=True,
305 intelligent_retry=True,
306 max_parallel_hooks=3,
307 max_parallel_tests=4,
308 timeout_multiplier=1.0,
309 debug_level="standard",
310 log_individual_outputs=False,
311 preserve_temp_files=False,
312 )
314 session = SessionCoordinator(
315 context.console,
316 context.config.project_path,
317 web_job_id=job_id,
318 )
319 orchestrator = AdvancedWorkflowOrchestrator(
320 console=context.console,
321 pkg_path=context.config.project_path,
322 session=session,
323 config=optimal_config,
324 )
326 if kwargs.get("debug", False):
327 orchestrator.individual_executor.set_mcp_mode(False)
328 context.safe_print("🐛 Debug mode enabled-full output mode")
330 return orchestrator
333def _create_standard_orchestrator(
334 job_id: str,
335 kwargs: dict[str, t.Any],
336 context: t.Any,
337) -> t.Any:
338 from crackerjack.core.workflow_orchestrator import WorkflowOrchestrator
340 return WorkflowOrchestrator(
341 console=context.console,
342 pkg_path=context.config.project_path,
343 dry_run=kwargs.get("dry_run", False),
344 web_job_id=job_id,
345 )
348async def _run_workflow_iterations(
349 job_id: str,
350 max_iterations: int,
351 orchestrator: t.Any,
352 use_advanced_orchestrator: bool,
353 kwargs: dict[str, t.Any],
354) -> dict[str, t.Any]:
355 success = False
356 current_iteration = 1
358 for iteration in range(1, max_iterations + 1):
359 current_iteration = iteration
361 _update_progress(
362 job_id=job_id,
363 iteration=current_iteration,
364 max_iterations=max_iterations,
365 overall_progress=int((iteration / max_iterations) * 80),
366 current_stage=f"iteration_{iteration}",
367 message=f"Running iteration {iteration} / {max_iterations}",
368 )
370 options = _create_workflow_options(kwargs)
372 try:
373 success = await _execute_single_iteration(
374 orchestrator,
375 use_advanced_orchestrator,
376 options,
377 )
379 if success:
380 return _create_success_result(
381 job_id,
382 current_iteration,
383 max_iterations,
384 iteration,
385 )
387 if iteration < max_iterations:
388 await _handle_iteration_retry(
389 job_id,
390 current_iteration,
391 max_iterations,
392 iteration,
393 )
394 continue
396 except Exception as e:
397 if not await _handle_iteration_error(iteration, max_iterations, e):
398 break
400 return _create_failure_result(job_id, current_iteration, max_iterations)
403def _create_workflow_options(kwargs: dict[str, t.Any]) -> t.Any:
404 from crackerjack.models.config import WorkflowOptions
406 options = WorkflowOptions()
407 options.testing.test = kwargs.get("test", True)
408 options.ai_agent = kwargs.get("ai_agent", True)
409 options.skip_hooks = kwargs.get("skip_hooks", False)
411 options.proactive_mode = kwargs.get("proactive_mode", True)
412 return options
415async def _execute_single_iteration(
416 orchestrator: t.Any,
417 use_advanced_orchestrator: bool,
418 options: t.Any,
419) -> bool:
420 if use_advanced_orchestrator:
421 return await orchestrator.execute_orchestrated_workflow(options)
422 return await orchestrator.run_complete_workflow(options)
425def _create_success_result(
426 job_id: str,
427 current_iteration: int,
428 max_iterations: int,
429 iteration: int,
430) -> dict[str, t.Any]:
431 _update_progress(
432 job_id=job_id,
433 status="completed",
434 iteration=current_iteration,
435 max_iterations=max_iterations,
436 overall_progress=100,
437 current_stage="completed",
438 message=f"Successfully completed after {iteration} iterations",
439 )
440 return {
441 "job_id": job_id,
442 "status": "completed",
443 "iteration": current_iteration,
444 "message": f"Successfully completed after {iteration} iterations",
445 }
448async def _handle_iteration_retry(
449 job_id: str,
450 current_iteration: int,
451 max_iterations: int,
452 iteration: int,
453) -> None:
454 _update_progress(
455 job_id=job_id,
456 iteration=current_iteration,
457 max_iterations=max_iterations,
458 overall_progress=int((iteration / max_iterations) * 80),
459 current_stage="retrying",
460 message=f"Iteration {iteration} failed, retrying...",
461 )
462 await asyncio.sleep(1)
465async def _handle_iteration_error(
466 iteration: int,
467 max_iterations: int,
468 error: Exception,
469) -> bool:
470 if iteration >= max_iterations:
471 return False
472 await asyncio.sleep(1)
473 return True
476def _create_failure_result(
477 job_id: str,
478 current_iteration: int,
479 max_iterations: int,
480) -> dict[str, t.Any]:
481 _update_progress(
482 job_id=job_id,
483 status="failed",
484 iteration=current_iteration,
485 max_iterations=max_iterations,
486 overall_progress=80,
487 current_stage="failed",
488 message=f"Failed after {max_iterations} iterations",
489 )
490 return {
491 "job_id": job_id,
492 "status": "failed",
493 "iteration": current_iteration,
494 "message": f"Failed after {max_iterations} iterations",
495 }
498async def _ensure_services_running(job_id: str, context: t.Any) -> None:
499 import subprocess
501 _update_progress(
502 job_id=job_id,
503 current_stage="service_startup",
504 message="Checking required services...",
505 )
507 websocket_running = False
508 with suppress(Exception):
509 from crackerjack.services.server_manager import find_websocket_server_processes
511 websocket_processes = find_websocket_server_processes()
512 websocket_running = len(websocket_processes) > 0
514 if not websocket_running:
515 _update_progress(
516 job_id=job_id,
517 current_stage="service_startup",
518 message="Starting WebSocket server...",
519 )
521 try:
522 subprocess.Popen(
523 ["python", "- m", "crackerjack", "- - start - websocket-server"],
524 cwd=context.config.project_path,
525 stdout=subprocess.DEVNULL,
526 stderr=subprocess.DEVNULL,
527 start_new_session=True,
528 )
530 for _i in range(10):
531 with suppress(Exception):
532 websocket_processes = find_websocket_server_processes()
533 if websocket_processes:
534 context.safe_print("✅ WebSocket server started successfully")
535 break
536 await asyncio.sleep(0.5)
537 else:
538 context.safe_print("⚠️ WebSocket server may not have started properly")
540 except Exception as e:
541 context.safe_print(f"⚠️ Failed to start WebSocket server: {e}")
542 else:
543 context.safe_print("✅ WebSocket server already running")
546async def _check_status_and_prepare(job_id: str, context: t.Any) -> dict[str, t.Any]:
547 _update_progress(
548 job_id=job_id,
549 current_stage="status_check",
550 message="🔍 Checking system status to prevent conflicts...",
551 )
553 try:
554 status_info = await _get_status_info()
555 if "error" in status_info:
556 return _handle_status_error(status_info, context)
558 cleanup_performed = []
560 _check_active_jobs(status_info, context)
562 cleanup_performed.extend(_check_resource_cleanup(status_info, context))
564 _check_service_health(status_info, context)
566 context.safe_print("✅ Status check complete-ready to proceed")
568 return {
569 "should_abort": False,
570 "reason": "",
571 "status_info": status_info,
572 "cleanup_performed": cleanup_performed,
573 }
575 except Exception as e:
576 return _handle_status_exception(e, context)
579async def _get_status_info() -> dict[str, t.Any]:
580 from .monitoring_tools import _get_comprehensive_status
582 return await _get_comprehensive_status()
585def _handle_status_error(
586 status_info: dict[str, t.Any],
587 context: t.Any,
588) -> dict[str, t.Any]:
589 context.safe_print(f"⚠️ Status check failed: {status_info['error']}")
590 return {
591 "should_abort": False,
592 "reason": "",
593 "status_info": status_info,
594 "cleanup_performed": [],
595 }
598def _check_active_jobs(status_info: dict[str, t.Any], context: t.Any) -> None:
599 active_jobs = [
600 j
601 for j in status_info.get("jobs", {}).get("details", [])
602 if j.get("status") == "running"
603 ]
605 if active_jobs:
606 _handle_conflicting_jobs(active_jobs, context)
607 else:
608 context.safe_print("✅ No active jobs detected-safe to proceed")
611def _handle_conflicting_jobs(
612 active_jobs: list[dict[str, t.Any]],
613 context: t.Any,
614) -> None:
615 conflicting_jobs = active_jobs
617 if conflicting_jobs:
618 job_ids = [j.get("job_id", "unknown") for j in conflicting_jobs]
619 context.safe_print(
620 f"⚠️ Found {len(conflicting_jobs)} active job(s): {', '.join(job_ids[:3])}",
621 )
622 context.safe_print(
623 " Running concurrent crackerjack instances may cause file conflicts",
624 )
625 context.safe_print(" Proceeding with caution...")
628def _check_resource_cleanup(status_info: dict[str, t.Any], context: t.Any) -> list[str]:
629 cleanup_performed = []
631 temp_files_count = (
632 status_info.get("server_stats", {})
633 .get("resource_usage", {})
634 .get("temp_files_count", 0)
635 )
637 if temp_files_count > 50:
638 context.safe_print(
639 f"🗑️ Found {temp_files_count} temporary files-cleanup recommended",
640 )
641 cleanup_performed.append("temp_files_flagged")
643 return cleanup_performed
646def _check_service_health(status_info: dict[str, t.Any], context: t.Any) -> None:
647 services = status_info.get("services", {})
648 mcp_running = services.get("mcp_server", {}).get("running", False)
649 websocket_running = services.get("websocket_server", {}).get("running", False)
651 if not mcp_running:
652 context.safe_print("⚠️ MCP server not running - will auto-start if needed")
654 if not websocket_running:
655 context.safe_print("📡 WebSocket server not running - will auto-start")
658def _handle_status_exception(error: Exception, context: t.Any) -> dict[str, t.Any]:
659 context.safe_print(f"⚠️ Status check encountered error: {error}")
660 return {
661 "should_abort": False,
662 "reason": "",
663 "status_info": {"error": str(error)},
664 "cleanup_performed": [],
665 }
668async def _cleanup_stale_jobs(context: t.Any) -> None:
669 if not context.progress_dir.exists():
670 return
672 current_time = time.time()
673 cleaned_count = 0
675 with suppress(Exception):
676 for progress_file in context.progress_dir.glob("job-*.json"):
677 try:
678 import json
680 progress_data = json.loads(progress_file.read_text())
682 last_update = progress_data.get("updated_at", 0)
683 age_minutes = (current_time - last_update) / 60
685 is_stale = (
686 age_minutes > 30
687 or progress_data.get("job_id") == "unknown"
688 or "analyzing_failures: processing"
689 in progress_data.get("status", "")
690 )
692 if is_stale:
693 progress_file.unlink()
694 cleaned_count += 1
696 except (json.JSONDecodeError, OSError):
697 with suppress(OSError):
698 progress_file.unlink()
699 cleaned_count += 1
701 if cleaned_count > 0:
702 context.safe_print(f"🗑️ Cleaned up {cleaned_count} stale job files")
705def _register_init_crackerjack_tool(mcp_app: t.Any) -> None:
706 @mcp_app.tool()
707 async def init_crackerjack(args: str = "", kwargs: str = "{}") -> str:
708 context = get_context()
709 if not context:
710 return _create_init_error_response("Server context not available")
712 target_path, force, parse_error = _parse_init_arguments(args, kwargs)
713 if parse_error:
714 return parse_error
716 try:
717 results = _execute_initialization(context, target_path, force)
718 return _create_init_success_response(results, target_path, force)
719 except Exception as e:
720 return _create_init_exception_response(e, target_path)
723def _create_init_error_response(message: str) -> str:
724 return json.dumps({"error": message, "success": False}, indent=2)
727def _parse_init_arguments(args: str, kwargs: str) -> tuple[t.Any, bool, str | None]:
728 from pathlib import Path
730 target_path = args.strip() or None
732 try:
733 extra_kwargs = json.loads(kwargs) if kwargs.strip() else {}
734 except json.JSONDecodeError as e:
735 return None, False, _create_init_error_response(f"Invalid JSON in kwargs: {e}")
737 force = extra_kwargs.get("force", False)
739 if target_path:
740 target_path = Path(target_path).resolve()
741 else:
742 target_path = Path.cwd()
744 if not target_path.exists():
745 return (
746 None,
747 False,
748 _create_init_error_response(f"Target path does not exist: {target_path}"),
749 )
751 return target_path, force, None
754def _execute_initialization(
755 context: t.Any, target_path: t.Any, force: bool
756) -> dict[str, t.Any]:
757 from crackerjack.services.filesystem import FileSystemService
758 from crackerjack.services.git import GitService
759 from crackerjack.services.initialization import InitializationService
761 filesystem = FileSystemService()
762 git_service = GitService(context.console, context.config.project_path)
764 return InitializationService(
765 context.console, filesystem, git_service, context.config.project_path
766 ).initialize_project(target_path=target_path, force=force)
769def _create_init_success_response(
770 results: dict[str, t.Any], target_path: t.Any, force: bool
771) -> str:
772 results["command"] = "init_crackerjack"
773 results["target_path"] = str(target_path)
774 results["force"] = force
775 return json.dumps(results, indent=2)
778def _create_init_exception_response(error: Exception, target_path: t.Any) -> str:
779 error_result = {
780 "error": f"Initialization failed: {error}",
781 "success": False,
782 "command": "init_crackerjack",
783 "target_path": str(target_path) if target_path else "current_directory",
784 }
785 return json.dumps(error_result, indent=2)
788def _register_agent_suggestions_tool(mcp_app: t.Any) -> None:
789 @mcp_app.tool()
790 async def suggest_agents(
791 task_description: str = "",
792 project_type: str = "python",
793 current_context: str = "",
794 ) -> str:
795 suggestions = {
796 "primary_agents": [],
797 "task_specific_agents": [],
798 "usage_patterns": [],
799 "rationale": "",
800 }
802 if project_type.lower() == "python" or "python" in task_description.lower():
803 suggestions["primary_agents"].append(
804 {
805 "name": "crackerjack-architect",
806 "emoji": "🏗️",
807 "description": "Expert in crackerjack's modular architecture and Python project management patterns",
808 "usage": "Use PROACTIVELY for all feature development, architectural decisions, and ensuring code follows crackerjack standards",
809 "priority": "HIGH",
810 }
811 )
813 suggestions["primary_agents"].append(
814 {
815 "name": "python-pro",
816 "emoji": "🐍",
817 "description": "Modern Python development with type hints, async / await patterns, and clean architecture",
818 "usage": "Use for implementing Python code with best practices",
819 "priority": "HIGH",
820 }
821 )
823 task_lower = task_description.lower()
824 context_lower = current_context.lower()
826 if any(
827 word in task_lower + context_lower
828 for word in ("test", "testing", "coverage", "pytest")
829 ):
830 suggestions["task_specific_agents"].append(
831 {
832 "name": "crackerjack - test-specialist",
833 "emoji": "🧪",
834 "description": "Advanced testing specialist for complex scenarios and coverage optimization",
835 "usage": "Use for test creation, debugging test failures, and coverage improvements",
836 "priority": "HIGH",
837 }
838 )
840 suggestions["task_specific_agents"].append(
841 {
842 "name": "pytest - hypothesis-specialist",
843 "emoji": "🧪",
844 "description": "Advanced testing patterns and property-based testing",
845 "usage": "Use for comprehensive test development and optimization",
846 "priority": "MEDIUM",
847 }
848 )
850 if any(
851 word in task_lower + context_lower
852 for word in ("security", "vulnerability", "auth", "permission")
853 ):
854 suggestions["task_specific_agents"].append(
855 {
856 "name": "security-auditor",
857 "emoji": "🔒",
858 "description": "Security analysis, vulnerability detection, and secure coding practices",
859 "usage": "Use for security review and vulnerability assessment",
860 "priority": "HIGH",
861 }
862 )
864 if any(
865 word in task_lower + context_lower
866 for word in ("architecture", "design", "api", "backend")
867 ):
868 suggestions["task_specific_agents"].append(
869 {
870 "name": "backend-architect",
871 "emoji": "🏗️",
872 "description": "System design, API architecture, and service integration patterns",
873 "usage": "Use for architectural planning and system design",
874 "priority": "MEDIUM",
875 }
876 )
878 suggestions["usage_patterns"] = [
879 'Task tool with subagent_type ="crackerjack-architect" for feature planning and architecture',
880 'Task tool with subagent_type ="python-pro" for implementation with best practices',
881 'Task tool with subagent_type ="crackerjack - test-specialist" for comprehensive testing',
882 'Task tool with subagent_type ="security-auditor" for security validation',
883 ]
885 if "crackerjack-architect" in [
886 agent["name"] for agent in suggestions["primary_agents"]
887 ]:
888 suggestions["rationale"] = (
889 "The crackerjack-architect agent is essential for this Python project as it ensures "
890 "code follows crackerjack patterns from the start, eliminating retrofitting needs. "
891 "Combined with python - pro for implementation and task-specific agents for specialized "
892 "work, this provides comprehensive development support with built-in quality assurance."
893 )
895 return json.dumps(suggestions, indent=2)
897 @mcp_app.tool()
898 async def detect_agent_needs(
899 error_context: str = "",
900 file_patterns: str = "",
901 recent_changes: str = "",
902 ) -> str:
903 recommendations = {
904 "urgent_agents": [],
905 "suggested_agents": [],
906 "workflow_recommendations": [],
907 "detection_reasoning": "",
908 }
910 _add_urgent_agents_for_errors(recommendations, error_context)
912 _add_python_project_suggestions(recommendations, file_patterns)
914 _set_workflow_recommendations(recommendations)
916 _generate_detection_reasoning(recommendations)
918 return json.dumps(recommendations, indent=2)
921def _add_urgent_agents_for_errors(
922 recommendations: dict[str, t.Any], error_context: str
923) -> None:
924 if any(
925 word in error_context.lower()
926 for word in ("test fail", "coverage", "pytest", "assertion")
927 ):
928 recommendations["urgent_agents"].append(
929 {
930 "agent": "crackerjack - test-specialist",
931 "reason": "Test failures detected-specialist needed for debugging and fixes",
932 "action": 'Task tool with subagent_type ="crackerjack - test-specialist" to analyze and fix test issues',
933 }
934 )
936 if any(
937 word in error_context.lower()
938 for word in ("security", "vulnerability", "bandit", "unsafe")
939 ):
940 recommendations["urgent_agents"].append(
941 {
942 "agent": "security-auditor",
943 "reason": "Security issues detected-immediate audit required",
944 "action": 'Task tool with subagent_type ="security-auditor" to review and fix security vulnerabilities',
945 }
946 )
948 if any(
949 word in error_context.lower()
950 for word in ("complexity", "refactor", "too complex")
951 ):
952 recommendations["urgent_agents"].append(
953 {
954 "agent": "crackerjack-architect",
955 "reason": "Complexity issues detected-architectural review needed",
956 "action": 'Task tool with subagent_type ="crackerjack-architect" to simplify and restructure code',
957 }
958 )
961def _add_python_project_suggestions(
962 recommendations: dict[str, t.Any], file_patterns: str
963) -> None:
964 if "python" in file_patterns.lower() or ".py" in file_patterns:
965 recommendations["suggested_agents"].extend(
966 [
967 {
968 "agent": "crackerjack-architect",
969 "reason": "Python project detected-ensure crackerjack compliance",
970 "priority": "HIGH",
971 },
972 {
973 "agent": "python-pro",
974 "reason": "Python development best practices",
975 "priority": "HIGH",
976 },
977 ]
978 )
981def _set_workflow_recommendations(recommendations: dict[str, t.Any]) -> None:
982 if recommendations["urgent_agents"]:
983 recommendations["workflow_recommendations"] = [
984 "Address urgent issues first with specialized agents",
985 "Run crackerjack quality checks after fixes: python - m crackerjack-t",
986 "Use crackerjack-architect for ongoing compliance",
987 ]
988 else:
989 recommendations["workflow_recommendations"] = [
990 "Start with crackerjack-architect for proper planning",
991 "Use python-pro for implementation",
992 "Run continuous quality checks: python-m crackerjack",
993 ]
996def _generate_detection_reasoning(recommendations: dict[str, t.Any]) -> None:
997 recommendations["detection_reasoning"] = (
998 f"Analysis of context revealed {len(recommendations['urgent_agents'])} urgent issues "
999 f"and {len(recommendations['suggested_agents'])} general recommendations. "
1000 "Prioritize urgent agents first, then follow standard workflow patterns."
1001 )