#!/usr/bin/env python3 """ Comprehensive demo of tre-based LLM-optimized directory tree functionality """ import asyncio import json from pathlib import Path from enhanced_mcp.file_operations import EnhancedFileOperations async def demo_tre_llm_integration(): """Demo tre integration for LLM-optimized directory analysis""" print("šŸš€ Enhanced MCP Tools - tre Integration Demo") print("=" * 60) # Initialize the file operations class file_ops = EnhancedFileOperations() # Test on current project project_dir = "/home/rpm/claude/enhanced-mcp-tools" # Demo 1: Fast tre-based tree listing print("\n🌳 Demo 1: Lightning-Fast tre Tree Listing") print(f"šŸ“ Scanning: {project_dir}") tre_result = await file_ops.tre_directory_tree( root_path=project_dir, max_depth=2, include_hidden=False, exclude_patterns=[r"\.git", r"\.venv", r"__pycache__"], ) if tre_result.get("success"): metadata = tre_result["metadata"] stats = metadata["statistics"] print(f"⚔ Execution time: {metadata['execution_time_seconds']}s") print( f"šŸ“Š Found: {stats['total']} items ({stats['files']} files, {stats['directories']} directories)" ) print(f"šŸ¤– LLM optimized: {metadata['optimized_for_llm']}") print(f"šŸ”§ Command: {metadata['command']}") # Show sample structure print("\nšŸ“‹ Sample Structure:") tree = tre_result["tree"] for i, item in enumerate(tree.get("contents", [])[:5]): icon = "šŸ“" if item["type"] == "directory" else "šŸ“„" print(f" {icon} {item['name']}") if len(tree.get("contents", [])) > 5: print(f" ... and {len(tree.get('contents', [])) - 5} more items") else: print(f"āŒ Error: {tre_result.get('error')}") return # Demo 2: LLM Context Generation with File Contents print("\nšŸ¤– Demo 2: Complete LLM Context Generation") llm_context = await file_ops.tre_llm_context( root_path=project_dir, max_depth=2, include_file_contents=True, exclude_patterns=[r"\.git", r"\.venv", r"__pycache__", r"test_.*\.py", r"demo_.*\.py"], file_extensions=[".py", ".md", ".toml"], max_file_size_kb=30, ) if llm_context.get("success"): context = llm_context["context"] summary = context["summary"] print("šŸ“Š Context Statistics:") print(f" Total files scanned: {summary['total_files']}") print(f" Files included: {summary['included_files']}") print(f" Files excluded: {summary['excluded_files']}") print(f" Total content size: {summary['total_size_bytes']} bytes") print("\nšŸ“„ Included Files:") for i, (path, content) in enumerate(list(context["file_contents"].items())[:3]): print(f" {i+1}. {path}") print(f" Size: {content['size_bytes']} bytes, Lines: {content['lines']}") if "content" in content and len(content["content"]) > 100: preview = content["content"][:100].replace("\n", "\\n") print(f" Preview: {preview}...") print("\nšŸ¤– LLM Summary:") print(context["llm_summary"]) else: print(f"āŒ LLM Context Error: {llm_context.get('error')}") # Demo 3: Different tre Options print("\nšŸ”§ Demo 3: tre Options Showcase") options_demo = [ {"name": "Directories Only", "params": {"directories_only": True, "max_depth": 1}}, {"name": "Include Hidden Files", "params": {"include_hidden": True, "max_depth": 1}}, {"name": "Deep Scan", "params": {"max_depth": 3}}, {"name": "Selective Exclusion", "params": {"exclude_patterns": [r"\.py$"], "max_depth": 1}}, ] for demo in options_demo: print(f"\n šŸ“‹ {demo['name']}:") result = await file_ops.tre_directory_tree(root_path=project_dir, **demo["params"]) if result.get("success"): stats = result["metadata"]["statistics"] time_taken = result["metadata"]["execution_time_seconds"] print(f" āœ… {stats['total']} items in {time_taken}s") else: print(f" āŒ Error: {result.get('error')}") # Demo 4: Performance Comparison print("\n⚔ Demo 4: Performance Benefits") print("šŸ¦€ tre (Rust-based):") start_time = asyncio.get_event_loop().time() tre_perf = await file_ops.tre_directory_tree(root_path=project_dir, max_depth=3) tre_time = asyncio.get_event_loop().time() - start_time if tre_perf.get("success"): tre_stats = tre_perf["metadata"]["statistics"] print(f" ⚔ {tre_stats['total']} items in {tre_time:.4f}s") print(" šŸš€ Rust performance + LLM optimization") print("\nšŸ Python implementation:") start_time = asyncio.get_event_loop().time() python_perf = await file_ops.list_directory_tree( root_path=project_dir, max_depth=3, include_metadata=False ) python_time = asyncio.get_event_loop().time() - start_time if "error" not in python_perf: python_stats = python_perf["summary"]["total_items"] print(f" 🐌 {python_stats} items in {python_time:.4f}s") print(" šŸ“Š More metadata but slower") speedup = python_time / tre_time if tre_time > 0 else 1 print(f" šŸ† tre is {speedup:.1f}x faster!") # Demo 5: Real-world use cases print("\nšŸŽÆ Demo 5: Real-World Use Cases") use_cases = [ { "name": "Code Review Context", "description": "Generate context for reviewing Python code", "params": { "file_extensions": [".py"], "exclude_patterns": [r"test_.*\.py", r"__pycache__", r"\.pyc$"], "max_file_size_kb": 50, }, }, { "name": "Documentation Analysis", "description": "Analyze project documentation structure", "params": {"file_extensions": [".md", ".rst", ".txt"], "max_file_size_kb": 200}, }, { "name": "Configuration Audit", "description": "Review configuration files", "params": { "file_extensions": [".toml", ".json", ".yaml", ".yml", ".ini"], "max_file_size_kb": 20, }, }, ] for use_case in use_cases: print(f"\n šŸŽÆ {use_case['name']}: {use_case['description']}") context = await file_ops.tre_llm_context( root_path=project_dir, max_depth=3, **use_case["params"] ) if context.get("success"): stats = context["context"]["summary"] print(f" āœ… {stats['included_files']} files ({stats['total_size_bytes']} bytes)") else: print(f" āŒ Error: {context.get('error')}") # Demo 6: JSON Export for External Tools print("\nšŸ’¾ Demo 6: Integration with External Tools") export_result = await file_ops.tre_directory_tree( root_path=project_dir, max_depth=2, exclude_patterns=[r"\.git", r"\.venv"] ) if export_result.get("success"): # Export for different tools exports = [ {"name": "Claude Analysis", "file": "claude_context.json"}, {"name": "VS Code Extension", "file": "vscode_tree.json"}, {"name": "CI/CD Pipeline", "file": "build_manifest.json"}, ] for export in exports: export_path = Path(project_dir) / export["file"] with open(export_path, "w") as f: json.dump(export_result, f, indent=2) size_mb = export_path.stat().st_size / 1024 / 1024 print(f" šŸ“„ {export['name']}: {export['file']} ({size_mb:.2f} MB)") # Clean up export_path.unlink() print("\nšŸŽ‰ tre Integration Demo Complete!") print("✨ Key Benefits:") print(" šŸš€ Lightning-fast Rust performance") print(" šŸ¤– LLM-optimized JSON output") print(" šŸ”§ Extensive filtering and configuration") print(" šŸ“Š Rich metadata and statistics") print(" šŸŽÆ Purpose-built for modern development workflows") print(" šŸ’¾ Perfect for CI/CD and automation") if __name__ == "__main__": asyncio.run(demo_tre_llm_integration())