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

96 statements  

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

1import contextlib 

2import json 

3import typing as t 

4from pathlib import Path 

5 

6from crackerjack.mcp.context import get_context 

7from crackerjack.services.input_validator import get_input_validator 

8 

9 

10def _create_progress_file(job_id: str) -> Path: 

11 import tempfile 

12 

13 # Use secure input validation 

14 validator = get_input_validator() 

15 job_id_result = validator.validate_job_id(job_id) 

16 

17 if not job_id_result.valid: 

18 msg = f"Invalid job_id: {job_id_result.error_message}" 

19 raise ValueError(msg) 

20 

21 # Use sanitized job ID 

22 sanitized_job_id = job_id_result.sanitized_value 

23 

24 context = get_context() 

25 if context: 

26 return context.progress_dir / f"job-{sanitized_job_id}.json" 

27 

28 # Create secure temporary directory 

29 progress_dir = Path(tempfile.gettempdir()) / "crackerjack-mcp-progress" 

30 progress_dir.mkdir(exist_ok=True, mode=0o750) # Restrictive permissions 

31 return progress_dir / f"job-{sanitized_job_id}.json" 

32 

33 

34def _clamp_progress(value: int) -> int: 

35 return min(100, max(0, value)) 

36 

37 

38def _get_timestamp() -> str: 

39 context = get_context() 

40 return context.get_current_time() if context else "" 

41 

42 

43def _build_dict_format_progress( 

44 job_id: str, 

45 progress_data: dict[str, t.Any], 

46 iteration: int, 

47 max_iterations: int, 

48 overall_progress: int, 

49 current_stage: str, 

50 stage_progress: int, 

51 message: str, 

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

53 return { 

54 "job_id": job_id, 

55 "status": progress_data.get("status", "running"), 

56 "iteration": progress_data.get("iteration", iteration), 

57 "max_iterations": progress_data.get("max_iterations", max_iterations), 

58 "overall_progress": _clamp_progress( 

59 progress_data.get("overall_progress", overall_progress) 

60 ), 

61 "current_stage": progress_data.get("type", current_stage), 

62 "stage_progress": _clamp_progress( 

63 progress_data.get("stage_progress", stage_progress) 

64 ), 

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

66 "timestamp": _get_timestamp(), 

67 } 

68 

69 

70def _build_legacy_format_progress( 

71 job_id: str, 

72 progress_data: str | None, 

73 iteration: int, 

74 max_iterations: int, 

75 overall_progress: int, 

76 current_stage: str, 

77 stage_progress: int, 

78 message: str, 

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

80 status = progress_data if isinstance(progress_data, str) else "running" 

81 return { 

82 "job_id": job_id, 

83 "status": status, 

84 "iteration": iteration, 

85 "max_iterations": max_iterations, 

86 "overall_progress": _clamp_progress(overall_progress), 

87 "current_stage": current_stage, 

88 "stage_progress": _clamp_progress(stage_progress), 

89 "message": message, 

90 "timestamp": _get_timestamp(), 

91 } 

92 

93 

94def _notify_websocket(final_progress_data: dict[str, t.Any]) -> None: 

95 context = get_context() 

96 if context and hasattr(context, "websocket_progress_queue"): 

97 with contextlib.suppress(Exception): 

98 context.websocket_progress_queue.put_nowait(final_progress_data) 

99 

100 

101def _update_progress( 

102 job_id: str, 

103 progress_data: dict[str, t.Any] | str = None, 

104 context: t.Any = None, 

105 iteration: int = 1, 

106 max_iterations: int = 10, 

107 overall_progress: int = 0, 

108 current_stage: str = "initialization", 

109 stage_progress: int = 0, 

110 message: str = "", 

111) -> None: 

112 try: 

113 progress_file = _create_progress_file(job_id) 

114 

115 if isinstance(progress_data, dict): 

116 final_progress_data = _build_dict_format_progress( 

117 job_id, 

118 progress_data, 

119 iteration, 

120 max_iterations, 

121 overall_progress, 

122 current_stage, 

123 stage_progress, 

124 message, 

125 ) 

126 else: 

127 final_progress_data = _build_legacy_format_progress( 

128 job_id, 

129 progress_data, 

130 iteration, 

131 max_iterations, 

132 overall_progress, 

133 current_stage, 

134 stage_progress, 

135 message, 

136 ) 

137 

138 progress_file.write_text(json.dumps(final_progress_data, indent=2)) 

139 _notify_websocket(final_progress_data) 

140 

141 except Exception as e: 

142 context = get_context() 

143 if context: 

144 context.safe_print(f"Warning: Failed to update progress for {job_id}: {e}") 

145 

146 

147def _handle_get_job_progress(job_id: str) -> str: 

148 context = get_context() 

149 if not context: 

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

151 

152 if not context.validate_job_id(job_id): 

153 return f'{{"error": "Invalid job_id: {job_id}"}}' 

154 

155 try: 

156 progress_file = _create_progress_file(job_id) 

157 

158 if not progress_file.exists(): 

159 return f'{{"error": "Job {job_id} not found", "job_id": "{job_id}"}}' 

160 

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

162 return json.dumps(progress_data, indent=2) 

163 

164 except json.JSONDecodeError as e: 

165 return f'{{"error": "Invalid progress data for job {job_id}: {e}"}}' 

166 except Exception as e: 

167 return f'{{"error": "Failed to get progress for job {job_id}: {e}"}}' 

168 

169 

170async def _execute_session_action( 

171 state_manager, 

172 action: str, 

173 checkpoint_name: str | None, 

174 context, 

175) -> str: 

176 if action == "start": 

177 state_manager.start_session() 

178 return '{"status": "session_started", "action": "start"}' 

179 

180 if action == "checkpoint": 

181 checkpoint_name = checkpoint_name or f"checkpoint_{context.get_current_time()}" 

182 await state_manager.save_checkpoint(checkpoint_name) 

183 return f'{{"status": "checkpoint_created", "action": "checkpoint", "name": "{checkpoint_name}"}}' 

184 

185 if action == "complete": 

186 state_manager.complete_session() 

187 return '{"status": "session_completed", "action": "complete"}' 

188 

189 if action == "reset": 

190 state_manager.reset_session() 

191 return '{"status": "session_reset", "action": "reset"}' 

192 

193 return f'{{"error": "Invalid action: {action}. Valid actions: start, checkpoint, complete, reset"}}' 

194 

195 

196async def _handle_session_management( 

197 action: str, checkpoint_name: str | None = None 

198) -> str: 

199 context = get_context() 

200 if not context: 

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

202 

203 try: 

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

205 if not state_manager: 

206 return '{"error": "State manager not available"}' 

207 

208 return await _execute_session_action( 

209 state_manager, action, checkpoint_name, context 

210 ) 

211 

212 except Exception as e: 

213 return f'{{"error": "Session management failed: {e}"}}' 

214 

215 

216def register_progress_tools(mcp_app: t.Any) -> None: 

217 @mcp_app.tool() 

218 async def get_job_progress(job_id: str) -> str: 

219 return _handle_get_job_progress(job_id) 

220 

221 @mcp_app.tool() 

222 async def session_management( 

223 action: str, 

224 checkpoint_name: str | None = None, 

225 ) -> str: 

226 return await _handle_session_management(action, checkpoint_name)