enhanced-mcp-tools/examples/demo_tre_llm_integration.py
Ryan Malloy 92b158b847
Some checks failed
CI / Code Quality (push) Failing after 17s
CI / Test (ubuntu-latest, 3.10) (push) Failing after 5s
CI / Test (ubuntu-latest, 3.11) (push) Failing after 4s
CI / Test (ubuntu-latest, 3.12) (push) Failing after 4s
CI / Test (ubuntu-latest, 3.13) (push) Failing after 4s
CI / Coverage (push) Failing after 25s
CI / Test (macos-latest, 3.13) (push) Has been cancelled
CI / Test (macos-latest, 3.10) (push) Has been cancelled
CI / Test (macos-latest, 3.11) (push) Has been cancelled
CI / Test (macos-latest, 3.12) (push) Has been cancelled
CI / Test (windows-latest, 3.10) (push) Has been cancelled
CI / Test (windows-latest, 3.11) (push) Has been cancelled
CI / Test (windows-latest, 3.12) (push) Has been cancelled
CI / Test (windows-latest, 3.13) (push) Has been cancelled
🚀 Initial release: Enhanced MCP Tools v1.0.0
 Features:
- 50+ development tools across 13 specialized categories
-  Sneller Analytics: High-performance vectorized SQL (TB/s throughput)
- 🎬 Asciinema Integration: Terminal recording and sharing
- 🧠 AI-Powered Recommendations: Intelligent tool suggestions
- 🔀 Advanced Git Integration: Smart operations with AI suggestions
- 📁 Enhanced File Operations: Monitoring, bulk ops, backups
- 🔍 Semantic Code Search: AST-based intelligent analysis
- 🏗️ Development Workflow: Testing, linting, formatting
- 🌐 Network & API Tools: HTTP client, mock servers
- 📦 Archive & Compression: Multi-format operations
- 🔬 Process Tracing: System call monitoring
- 🌍 Environment Management: Virtual envs, dependencies

🎯 Ready for production with comprehensive documentation and MCP Inspector support!
2025-06-23 02:33:23 -06:00

221 lines
8.2 KiB
Python

#!/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())