Coverage for session_buddy / tools / prompt_tools.py: 84.62%

33 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-04 00:43 -0800

1#!/usr/bin/env python3 

2"""MCP prompt management tools. 

3 

4This module provides all MCP prompt definitions following crackerjack 

5architecture patterns with single responsibility principle. 

6""" 

7 

8from __future__ import annotations 

9 

10from dataclasses import dataclass 

11from typing import TYPE_CHECKING, Any 

12 

13from session_buddy.session_commands import SESSION_COMMANDS 

14 

15if TYPE_CHECKING: 

16 from collections.abc import Callable, Coroutine 

17 

18 

19@dataclass(frozen=True) 

20class PromptDefinition: 

21 """Immutable prompt definition with metadata.""" 

22 

23 name: str 

24 description: str 

25 content_key: str | None = None 

26 content: str | None = None 

27 

28 def get_content(self) -> str: 

29 """Get prompt content from key or direct content.""" 

30 if self.content_key: 

31 return SESSION_COMMANDS[self.content_key] 

32 return self.content or "" 

33 

34 

35# Core session management prompts 

36CORE_PROMPTS: tuple[PromptDefinition, ...] = ( 

37 PromptDefinition( 

38 "init", 

39 "Initialize Claude session with comprehensive setup including UV dependencies, global workspace verification, and automation tools.", 

40 content_key="init", 

41 ), 

42 PromptDefinition( 

43 "checkpoint", 

44 "Perform mid-session quality checkpoint with workflow analysis and optimization recommendations.", 

45 content_key="checkpoint", 

46 ), 

47 PromptDefinition( 

48 "end", 

49 "End Claude session with cleanup, learning capture, and handoff file creation.", 

50 content_key="end", 

51 ), 

52 PromptDefinition( 

53 "status", 

54 "Get current session status and project context information with health checks.", 

55 content_key="status", 

56 ), 

57) 

58 

59# Permission and reflection prompts 

60REFLECTION_PROMPTS: tuple[PromptDefinition, ...] = ( 

61 PromptDefinition( 

62 "permissions", 

63 "Manage session permissions for trusted operations to avoid repeated prompts.", 

64 content_key="permissions", 

65 ), 

66 PromptDefinition( 

67 "reflect", 

68 "Search past conversations and store reflections with semantic similarity.", 

69 content_key="reflect", 

70 ), 

71 PromptDefinition( 

72 "quick-search", 

73 "Quick search that returns only the count and top result for fast overview.", 

74 content_key="quick-search", 

75 ), 

76 PromptDefinition( 

77 "search-summary", 

78 "Get aggregated insights from search results without individual result details.", 

79 content_key="search-summary", 

80 ), 

81 PromptDefinition( 

82 "reflection-stats", 

83 "Get statistics about the reflection database and conversation memory.", 

84 content_key="reflection-stats", 

85 ), 

86) 

87 

88# Crackerjack integration prompts 

89CRACKERJACK_PROMPTS: tuple[PromptDefinition, ...] = ( 

90 PromptDefinition( 

91 "crackerjack-run", 

92 "Execute a Crackerjack command and parse the output for insights.", 

93 content_key="crackerjack-run", 

94 ), 

95 PromptDefinition( 

96 "crackerjack-history", 

97 "Get recent Crackerjack command execution history with parsed results.", 

98 content_key="crackerjack-history", 

99 ), 

100 PromptDefinition( 

101 "crackerjack-metrics", 

102 "Get quality metrics trends from Crackerjack execution history.", 

103 content_key="crackerjack-metrics", 

104 ), 

105 PromptDefinition( 

106 "crackerjack-patterns", 

107 "Analyze test failure patterns and trends for debugging insights.", 

108 content_key="crackerjack-patterns", 

109 ), 

110) 

111 

112# Memory management prompts 

113MEMORY_PROMPTS: tuple[PromptDefinition, ...] = ( 

114 PromptDefinition( 

115 "compress-memory", 

116 "Compress conversation memory by consolidating old conversations into summaries.", 

117 content="""# Memory Compression 

118 

119Compress conversation memory by consolidating old conversations into summaries. 

120 

121This command will: 

122- Analyze conversation age and importance 

123- Group related conversations into clusters 

124- Create consolidated summaries of old conversations 

125- Remove redundant conversation data 

126- Calculate space savings and compression ratios 

127 

128Examples: 

129- Default compression: compress_memory() 

130- Preview changes: dry_run=True 

131- Aggressive compression: max_age_days=14, importance_threshold=0.5 

132 

133Use this periodically to keep your conversation memory manageable and efficient.""", 

134 ), 

135 PromptDefinition( 

136 "compression-stats", 

137 "Get detailed statistics about memory compression history and current database status.", 

138 content="""# Compression Statistics 

139 

140Get detailed statistics about memory compression history and current database status. 

141 

142This command will: 

143- Show last compression run details 

144- Display space savings and compression ratios 

145- Report current database size and conversation count 

146- Show number of consolidated conversations 

147- Provide compression efficiency metrics 

148 

149Use this to monitor memory usage and compression effectiveness.""", 

150 ), 

151 PromptDefinition( 

152 "retention-policy", 

153 "Configure memory retention policy parameters for automatic compression.", 

154 content="""# Retention Policy 

155 

156Configure memory retention policy parameters for automatic compression. 

157 

158This command will: 

159- Set maximum conversation age and count limits 

160- Configure importance threshold for retention 

161- Define consolidation age triggers 

162- Adjust compression ratio targets 

163 

164Examples: 

165- Conservative: max_age_days=365, importance_threshold=0.2 

166- Aggressive: max_age_days=90, importance_threshold=0.5 

167- Custom: consolidation_age_days=14 

168 

169Use this to customize how your conversation memory is managed over time.""", 

170 ), 

171) 

172 

173# Context and search prompts 

174CONTEXT_PROMPTS: tuple[PromptDefinition, ...] = ( 

175 PromptDefinition( 

176 "auto-load-context", 

177 "Automatically detect current development context and load relevant conversations.", 

178 content="""# Auto-Context Loading 

179 

180Automatically detect current development context and load relevant conversations. 

181 

182This command will: 

183- Analyze your current project structure and files 

184- Detect programming languages and tools in use 

185- Identify project type (web app, CLI tool, library, etc.) 

186- Find recent file modifications 

187- Load conversations relevant to your current context 

188- Score conversations by relevance to current work 

189 

190Examples: 

191- Load default context: auto_load_context() 

192- Increase results: max_conversations=20 

193- Lower threshold: min_relevance=0.2 

194 

195Use this at the start of coding sessions to get relevant context automatically.""", 

196 ), 

197 PromptDefinition( 

198 "context-summary", 

199 "Get a quick summary of your current development context without loading conversations.", 

200 content="""# Context Summary 

201 

202Get a quick summary of your current development context without loading conversations. 

203 

204This command will: 

205- Detect current project name and type 

206- Identify programming languages and tools 

207- Show Git repository information 

208- Display recently modified files 

209- Calculate detection confidence score 

210 

211Use this to understand what context the system has detected about your current work.""", 

212 ), 

213 PromptDefinition( 

214 "search-code", 

215 "Search for code patterns in conversations using AST parsing.", 

216 content="""# Code Pattern Search 

217 

218Search for code patterns in your conversation history using AST (Abstract Syntax Tree) parsing. 

219 

220This command will: 

221- Parse Python code blocks from conversations 

222- Extract functions, classes, imports, loops, and other patterns 

223- Rank results by relevance to your query 

224- Show code context and project information 

225 

226Examples: 

227- Search for functions: pattern_type='function' 

228- Search for class definitions: pattern_type='class' 

229- Search for error handling: query='try except' 

230 

231Use this to find code examples and patterns from your development sessions.""", 

232 ), 

233 PromptDefinition( 

234 "search-errors", 

235 "Search for error patterns and debugging contexts in conversations.", 

236 content="""# Error Pattern Search 

237 

238Search for error messages, exceptions, and debugging contexts in your conversation history. 

239 

240This command will: 

241- Find Python tracebacks and exceptions 

242- Detect JavaScript errors and warnings 

243- Identify debugging and testing contexts 

244- Show error context and solutions 

245 

246Examples: 

247- Find Python errors: error_type='python_exception' 

248- Find import issues: query='ImportError' 

249- Find debugging sessions: query='debug' 

250 

251Use this to quickly find solutions to similar errors you've encountered before.""", 

252 ), 

253 PromptDefinition( 

254 "search-temporal", 

255 "Search conversations within a specific time range using natural language.", 

256 content="""# Temporal Search 

257 

258Search your conversation history using natural language time expressions. 

259 

260This command will: 

261- Parse time expressions like "yesterday", "last week", "2 days ago" 

262- Find conversations within that time range 

263- Optionally filter by additional search terms 

264- Sort results by time and relevance 

265 

266Examples: 

267- "yesterday" - conversations from yesterday 

268- "last week" - conversations from the past week 

269- "2 days ago" - conversations from 2 days ago 

270- "this month" + query - filter by content within the month 

271 

272Use this to find recent discussions or work from specific time periods.""", 

273 ), 

274) 

275 

276# Monitoring prompts 

277MONITORING_PROMPTS: tuple[PromptDefinition, ...] = ( 

278 PromptDefinition( 

279 "start-app-monitoring", 

280 "Start monitoring IDE activity and browser documentation usage.", 

281 content="""# Start Application Monitoring 

282 

283Monitor your development activity to provide better context and insights. 

284 

285This command will: 

286- Start file system monitoring for code changes 

287- Track application focus (IDE, browser, terminal) 

288- Monitor documentation site visits 

289- Build activity profiles for better context 

290 

291Monitoring includes: 

292- File modifications in your project directories 

293- IDE and editor activity patterns 

294- Browser navigation to documentation sites 

295- Application focus and context switching 

296 

297Use this to automatically capture your development context for better session insights.""", 

298 ), 

299 PromptDefinition( 

300 "stop-app-monitoring", 

301 "Stop all application monitoring.", 

302 content="""# Stop Application Monitoring 

303 

304Stop monitoring your development activity. 

305 

306This command will: 

307- Stop file system monitoring 

308- Stop application focus tracking 

309- Preserve collected activity data 

310- Clean up monitoring resources 

311 

312Use this when you want to pause monitoring or when you're done with a development session.""", 

313 ), 

314 PromptDefinition( 

315 "activity-summary", 

316 "Get activity summary for recent development work.", 

317 content="""# Activity Summary 

318 

319Get a comprehensive summary of your recent development activity. 

320 

321This command will: 

322- Show file modification patterns 

323- List most active applications 

324- Display visited documentation sites 

325- Calculate productivity metrics 

326 

327Summary includes: 

328- Event counts by type and application 

329- Most actively edited files 

330- Documentation resources consulted 

331- Average relevance scores 

332 

333Use this to understand your development patterns and identify productive sessions.""", 

334 ), 

335 PromptDefinition( 

336 "context-insights", 

337 "Get contextual insights from recent activity.", 

338 content="""# Context Insights 

339 

340Analyze recent development activity for contextual insights. 

341 

342This command will: 

343- Identify primary focus areas 

344- Detect technologies being used 

345- Count context switches 

346- Calculate productivity scores 

347 

348Insights include: 

349- Primary application focus 

350- Active programming languages 

351- Documentation topics explored 

352- Project switching patterns 

353- Overall productivity assessment 

354 

355Use this to understand your current development context and optimize your workflow.""", 

356 ), 

357 PromptDefinition( 

358 "active-files", 

359 "Get files currently being worked on.", 

360 content="""# Active Files 

361 

362Show files that are currently being actively worked on. 

363 

364This command will: 

365- List recently modified files 

366- Show activity scores and patterns 

367- Highlight most frequently changed files 

368- Include project context 

369 

370File activity is scored based on: 

371- Frequency of modifications 

372- Recency of changes 

373- File type and relevance 

374- Project context 

375 

376Use this to quickly see what you're currently working on and resume interrupted tasks.""", 

377 ), 

378 PromptDefinition( 

379 "quality-monitor", 

380 "Proactive session quality monitoring with trend analysis and early warnings.", 

381 content="""# Quality Monitor 

382 

383Phase 3: Proactive quality monitoring with early warning system. 

384 

385This command will: 

386- Monitor code quality trends in real-time 

387- Detect quality degradation early 

388- Provide alerts for potential issues 

389- Generate improvement recommendations 

390- Track quality metrics over time 

391 

392Use this for continuous quality assurance during development.""", 

393 ), 

394 PromptDefinition( 

395 "auto-compact", 

396 "Automatically trigger conversation compaction with context preservation.", 

397 content="""# Auto Compact 

398 

399Automatically trigger conversation compaction with intelligent summary. 

400 

401This command will: 

402- Analyze conversation length and complexity 

403- Identify consolidation opportunities 

404- Preserve important context and decisions 

405- Compress redundant information 

406- Maintain searchable history 

407 

408Use this to manage conversation memory efficiently.""", 

409 ), 

410) 

411 

412# All prompts grouped for efficient processing 

413ALL_PROMPT_GROUPS: tuple[Any, ...] = ( # type: ignore[assignment] 

414 CORE_PROMPTS, 

415 REFLECTION_PROMPTS, 

416 CRACKERJACK_PROMPTS, 

417 MEMORY_PROMPTS, 

418 CONTEXT_PROMPTS, 

419 MONITORING_PROMPTS, 

420) 

421 

422 

423def _create_prompt_handler( 

424 definition: PromptDefinition, 

425) -> Callable[[], Coroutine[Any, Any, str]]: 

426 """Create async prompt handler function for a definition.""" 

427 

428 async def handler() -> str: 

429 return definition.get_content() 

430 

431 handler.__name__ = f"get_{definition.name.replace('-', '_')}_prompt" 

432 handler.__doc__ = definition.description 

433 return handler 

434 

435 

436def register_prompt_tools(mcp: Any) -> None: 

437 """Register all MCP prompt definitions using data-driven approach. 

438 

439 Args: 

440 mcp: FastMCP server instance 

441 

442 """ 

443 # Register prompts in groups for better organization 

444 for prompt_group in ALL_PROMPT_GROUPS: 

445 _register_prompt_group(mcp, prompt_group) 

446 

447 

448def _register_prompt_group(mcp: Any, prompts: tuple[PromptDefinition, ...]) -> None: 

449 """Register a group of prompts with MCP server.""" 

450 for definition in prompts: 

451 handler = _create_prompt_handler(definition) 

452 mcp.prompt(definition.name)(handler)