Coverage for /Users/les/Projects/crackerjack/crackerjack/mcp/tools/proactive_tools.py: 0%
85 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 typing as t
4def _create_architectural_assessment(args: str, parsed_kwargs: dict) -> dict:
5 assessment = {
6 "feature": parsed_kwargs.get("feature", "unknown"),
7 "complexity": parsed_kwargs.get("complexity", "medium"),
8 "context": args or "General development planning",
9 "proactive_recommendations": [],
10 }
12 recommendations = []
14 recommendations.append(
15 {
16 "agent": "crackerjack-architect",
17 "priority": "high",
18 "reason": "Expert architectural planning for crackerjack compliance",
19 "action": 'Task tool with subagent_type ="crackerjack-architect" for feature planning and architecture',
20 "benefits": [
21 "Prevents violations through proper initial architecture",
22 "Applies crackerjack patterns from the start",
23 "Reduces iteration cycles by 50 % +",
24 "Ensures consistency with project standards",
25 ],
26 }
27 )
29 complexity = parsed_kwargs.get("complexity", "medium")
30 if complexity in ("high", "complex"):
31 recommendations.append(
32 {
33 "agent": "refactoring-specialist",
34 "priority": "high",
35 "reason": "Complex features require careful structural planning",
36 "action": 'Task tool with subagent_type ="refactoring-specialist" for complexity management',
37 }
38 )
40 feature = parsed_kwargs.get("feature", "")
41 if any(
42 keyword in feature.lower() for keyword in ("auth", "security", "api", "data")
43 ):
44 recommendations.append(
45 {
46 "agent": "security-auditor",
47 "priority": "medium",
48 "reason": "Security-sensitive feature requires expert review",
49 "action": 'Task tool with subagent_type ="security-auditor" for security validation',
50 }
51 )
53 assessment["proactive_recommendations"] = recommendations
54 assessment["planning_strategy"] = "proactive_architecture_first"
56 return assessment
59def _create_validation_results(file_path: str) -> dict:
60 validation = {
61 "file_path": file_path,
62 "validation_results": [],
63 "architectural_compliance": "unknown",
64 "recommendations": [],
65 }
67 compliance_checks = [
68 {
69 "check": "complexity_compliance",
70 "status": "requires_analysis",
71 "message": "Cognitive complexity should be ≤13 per function",
72 "tool": "complexipy",
73 },
74 {
75 "check": "clean_code_patterns",
76 "status": "requires_analysis",
77 "message": "Follow DRY, YAGNI, KISS principles",
78 "patterns": [
79 "extract_method",
80 "protocol_interfaces",
81 "dependency_injection",
82 ],
83 },
84 {
85 "check": "security_patterns",
86 "status": "requires_analysis",
87 "message": "Use secure temp files, proper input validation",
88 "tool": "bandit",
89 },
90 {
91 "check": "type_annotations",
92 "status": "requires_analysis",
93 "message": "All functions must have proper type hints",
94 "tool": "pyright",
95 },
96 ]
98 validation["validation_results"] = compliance_checks
100 validation["recommendations"] = [
101 "Run full crackerjack quality process: python - m crackerjack-t",
102 "Use crackerjack-architect for complex refactoring decisions",
103 "Apply pattern learning from successful fixes",
104 "Validate against architectural plan before committing",
105 ]
107 validation["next_steps"] = [
108 'Task tool with subagent_type ="crackerjack-architect" for architectural guidance',
109 "Run comprehensive quality checks",
110 "Apply learned patterns from pattern cache",
111 ]
113 return validation
116def _create_pattern_suggestions(problem_context: str) -> dict:
117 pattern_suggestions = {
118 "context": problem_context,
119 "recommended_patterns": [],
120 "implementation_guidance": [],
121 "specialist_agents": [],
122 }
124 _add_complexity_patterns(pattern_suggestions, problem_context)
125 _add_dry_patterns(pattern_suggestions, problem_context)
126 _add_performance_patterns(pattern_suggestions, problem_context)
127 _add_security_patterns(pattern_suggestions, problem_context)
129 pattern_suggestions["specialist_agents"] = [
130 {
131 "agent": "crackerjack-architect",
132 "when_to_use": "For architectural decisions and complex pattern application",
133 "action": 'Task tool with subagent_type ="crackerjack-architect"',
134 },
135 {
136 "agent": "refactoring-specialist",
137 "when_to_use": "For complexity reduction and structural improvements",
138 "action": 'Task tool with subagent_type ="refactoring-specialist"',
139 },
140 {
141 "agent": "security-auditor",
142 "when_to_use": "For security pattern validation and vulnerability assessment",
143 "action": 'Task tool with subagent_type ="security-auditor"',
144 },
145 ]
147 pattern_suggestions["implementation_guidance"] = [
148 "Start with crackerjack-architect for overall planning",
149 "Apply one pattern at a time to avoid complexity",
150 "Validate each pattern with crackerjack quality checks",
151 "Cache successful patterns for future use",
152 "Document architectural decisions for team knowledge",
153 ]
155 if not pattern_suggestions["recommended_patterns"]:
156 pattern_suggestions["recommended_patterns"] = [
157 {
158 "pattern": "standard_crackerjack_patterns",
159 "description": "Apply standard crackerjack clean code patterns",
160 "benefits": [
161 "Consistent code quality",
162 "Better maintainability",
163 "Team alignment",
164 ],
165 }
166 ]
168 return pattern_suggestions
171def _add_complexity_patterns(pattern_suggestions: dict, problem_context: str) -> None:
172 if any(
173 keyword in problem_context.lower()
174 for keyword in ("complex", "refactor", "cleanup")
175 ):
176 pattern_suggestions["recommended_patterns"].extend(
177 [
178 {
179 "pattern": "extract_method",
180 "description": "Break complex functions into smaller, focused methods",
181 "benefits": [
182 "Reduces cognitive complexity",
183 "Improves testability",
184 "Follows KISS principle",
185 ],
186 },
187 {
188 "pattern": "dependency_injection",
189 "description": "Use protocol interfaces for better decoupling",
190 "benefits": [
191 "Improves testability",
192 "Reduces coupling",
193 "Enables better mocking",
194 ],
195 },
196 ]
197 )
200def _add_dry_patterns(pattern_suggestions: dict, problem_context: str) -> None:
201 if any(
202 keyword in problem_context.lower() for keyword in ("duplicate", "repeat", "dry")
203 ):
204 pattern_suggestions["recommended_patterns"].extend(
205 [
206 {
207 "pattern": "common_base_class",
208 "description": "Extract shared functionality to base classes or mixins",
209 "benefits": [
210 "Reduces duplication",
211 "Centralizes common logic",
212 "Easier maintenance",
213 ],
214 },
215 {
216 "pattern": "utility_functions",
217 "description": "Create reusable utility functions for common operations",
218 "benefits": [
219 "Single source of truth",
220 "Reduces code duplication",
221 "Easier testing",
222 ],
223 },
224 ]
225 )
228def _add_performance_patterns(pattern_suggestions: dict, problem_context: str) -> None:
229 if any(
230 keyword in problem_context.lower()
231 for keyword in ("slow", "performance", "optimize")
232 ):
233 pattern_suggestions["recommended_patterns"].extend(
234 [
235 {
236 "pattern": "list_comprehension",
237 "description": "Use list comprehensions instead of manual loops",
238 "benefits": [
239 "Better performance",
240 "More readable",
241 "Pythonic code",
242 ],
243 },
244 {
245 "pattern": "generator_pattern",
246 "description": "Use generators for memory-efficient processing",
247 "benefits": [
248 "Reduced memory usage",
249 "Lazy evaluation",
250 "Better for large datasets",
251 ],
252 },
253 ]
254 )
257def _add_security_patterns(pattern_suggestions: dict, problem_context: str) -> None:
258 if any(
259 keyword in problem_context.lower() for keyword in ("security", "safe", "secure")
260 ):
261 pattern_suggestions["recommended_patterns"].extend(
262 [
263 {
264 "pattern": "secure_temp_files",
265 "description": "Use tempfile module instead of hardcoded paths",
266 "benefits": [
267 "Prevents security vulnerabilities",
268 "Cross-platform compatibility",
269 "Automatic cleanup",
270 ],
271 },
272 {
273 "pattern": "input_validation",
274 "description": "Validate and sanitize all user inputs",
275 "benefits": [
276 "Prevents injection attacks",
277 "Better error handling",
278 "Data integrity",
279 ],
280 },
281 ]
282 )
285def _create_error_response(error: Exception, recommendation: str) -> str:
286 import json
288 return json.dumps(
289 {
290 "error": str(error),
291 "fallback_patterns": [
292 "clean_code",
293 "single_responsibility",
294 "dry_principle",
295 ],
296 "recommendation": recommendation,
297 }
298 )
301def register_proactive_tools(mcp_app: t.Any) -> None:
302 return _register_proactive_tools(mcp_app)
305def _register_proactive_tools(mcp_app: t.Any) -> None:
306 _register_plan_development_tool(mcp_app)
307 _register_validate_architecture_tool(mcp_app)
308 _register_suggest_patterns_tool(mcp_app)
311def _register_plan_development_tool(mcp_app: t.Any) -> None:
312 @mcp_app.tool()
313 async def plan_development(args: str, kwargs: str) -> str:
314 import json
316 try:
317 parsed_kwargs = json.loads(kwargs) if kwargs else {}
318 assessment = _create_architectural_assessment(args, parsed_kwargs)
319 return json.dumps(assessment, indent=2)
320 except Exception as e:
321 return _create_error_response(e, "Use standard development approach")
324def _register_validate_architecture_tool(mcp_app: t.Any) -> None:
325 @mcp_app.tool()
326 async def validate_architecture(args: str, kwargs: str) -> str:
327 import json
329 try:
330 parsed_kwargs = json.loads(kwargs) if kwargs else {}
331 file_path = args or parsed_kwargs.get("file_path", "")
332 validation = _create_validation_results(file_path)
333 return json.dumps(validation, indent=2)
334 except Exception as e:
335 return _create_error_response(
336 e, "Run standard crackerjack validation: python-m crackerjack"
337 )
340def _register_suggest_patterns_tool(mcp_app: t.Any) -> None:
341 @mcp_app.tool()
342 async def suggest_patterns(args: str, kwargs: str) -> str:
343 import json
345 try:
346 json.loads(kwargs) if kwargs else {}
347 problem_context = args or "General pattern suggestions"
348 pattern_suggestions = _create_pattern_suggestions(problem_context)
349 return json.dumps(pattern_suggestions, indent=2)
350 except Exception as e:
351 return _create_error_response(
352 e,
353 'Use Task tool with subagent_type ="crackerjack-architect" for expert guidance',
354 )