CtrEditor/Documentation/MCP/MCP_LLM_Guide.md

250 lines
9.1 KiB
Markdown

# CtrEditor MCP Server - LLM Guide
*MCP 2025-06-18 compliant | Compatible: Claude Desktop + Cursor*
## ⚡ Command Efficiency Tiers
### 🚀 **Ultra-Fast** (Use Liberally)
- `get_simulation_status` → ~25 tokens, instant
- `get_ctreditor_status` → ~20 tokens, instant
- `start/stop_simulation` → ~15 tokens, 2-3 sec
### 🟡 **Medium** (Use When Needed)
- `get_debug_stats` → ~30 tokens, instant
- `search_debug_log` → 50-200 tokens (max_lines=3-10)
- `build_project` → 100-500 tokens (errors only)
- `execute_python` → 50-500 tokens (depends on script)
- `python_help` → 100-300 tokens
- `clear_debug_buffer` → ~20 tokens, instant
### 🔴 **Heavy** (Use Sparingly)
- `list_objects` → 500-2000+ tokens
- `take_screenshot` → 100-300 tokens + file
## 🔧 Core Operations
### Process Management
```json
{"tool": "start_ctreditor", "parameters": {}}
{"tool": "get_ctreditor_status", "parameters": {}}
{"tool": "stop_ctreditor", "parameters": {}}
```
### Build & Debug
**Sistema de debug logging circular completamente refactorizado y validado ✅**
- Buffer circular automático: mantiene últimos 1000 eventos
- Captura en tiempo real: System.Diagnostics.Trace integration
- Timer de limpieza automática: previene memory leaks
- Thread-safe: ConcurrentQueue para alta concurrencia
- Performance validada: maneja miles de eventos sin degradación
```json
{"tool": "build_project", "parameters": {}}
{"tool": "get_debug_stats", "parameters": {}}
{"tool": "search_debug_log", "parameters": {"pattern": "error|exception", "max_lines": 5}}
{"tool": "search_debug_log", "parameters": {"pattern": "Tanque.*Nivel|PIPE.*Apply", "max_lines": 10}}
{"tool": "clear_debug_buffer", "parameters": {}}
```
### Simulation Control
```json
{"tool": "get_simulation_status", "parameters": {}}
{"tool": "start_simulation", "parameters": {}}
{"tool": "stop_simulation", "parameters": {}}
```
### Object Management
```json
{"tool": "list_objects", "parameters": {}}
{"tool": "create_object", "parameters": {"type": "osHydPump", "x": 10, "y": 5}}
{"tool": "update_object", "parameters": {"id": "123", "properties": {"PumpHead": 75.0}}}
{"tool": "delete_objects", "parameters": {"ids": ["123", "456"]}}
```
### Python Debug Scripts ⚡ NEW
```json
{"tool": "execute_python", "parameters": {"code": "print(f'Total objects: {len(objects)}')"}}
{"tool": "execute_python", "parameters": {
"code": "result = [obj for obj in objects if 'Pump' in str(type(obj))]",
"return_variables": ["result"]
}}
{"tool": "python_help", "parameters": {"object_name": "app"}}
```
## ⚡ Optimal Workflows
### Quick Development Cycle
```json
{"tool": "get_ctreditor_status", "parameters": {}}
{"tool": "build_project", "parameters": {}}
{"tool": "start_simulation", "parameters": {}}
{"tool": "execute_python", "parameters": {"code": "print(f'Objects: {len(objects)}, Running: {app.IsSimulationRunning}')"}}
{"tool": "get_simulation_status", "parameters": {}}
```
### Bug Investigation & Performance Testing
```json
{"tool": "get_debug_stats", "parameters": {}}
{"tool": "search_debug_log", "parameters": {"pattern": "error|exception|fail", "max_lines": 5}}
{"tool": "search_debug_log", "parameters": {"pattern": "MCP Server.*herramienta", "max_lines": 3}}
{"tool": "execute_python", "parameters": {"code": "print([type(obj).__name__ for obj in objects[:5]])"}}
{"tool": "get_simulation_status", "parameters": {}}
```
### Debug Log Stress Testing 🔥 NEW
```json
{"tool": "start_simulation", "parameters": {}}
{"tool": "get_debug_stats", "parameters": {}}
{"tool": "search_debug_log", "parameters": {"pattern": "Tanque.*Nivel|Bomba.*MaxFlow", "max_lines": 10}}
{"tool": "stop_simulation", "parameters": {}}
{"tool": "get_debug_stats", "parameters": {}}
```
### System Recovery
```json
{"tool": "stop_ctreditor", "parameters": {}}
{"tool": "start_ctreditor", "parameters": {}}
```
## 📊 Key Object Properties
### Python Debug Variables
- **app**: MainViewModel (simulation state, canvas, objects)
- **canvas**: MainCanvas (Width, Height, visual elements)
- **objects**: ObservableCollection of all simulable objects
- **get_objects()**: Returns List<object> for easier manipulation
### Hydraulic Components
- **osHydTank**: `TankPressure`, `MaxLevel`, `MinLevel`, `IsFixedPressure`
- **osHydPump**: `PumpHead`, `MaxFlow`, `SpeedRatio`, `IsRunning`
- **osHydPipe**: `Length`, `Diameter`, `CurrentFlow`, `PressureDrop`
### Common Properties
- **Position**: `Left`, `Top` (meters)
- **Dimensions**: `Ancho`, `Alto` (meters)
- **Connections**: `Id_ComponenteA`, `Id_ComponenteB`
## 🖼️ Screenshots
### Full Canvas
```json
{"tool": "take_screenshot", "parameters": {}}
```
### Targeted Area
```json
{"tool": "take_screenshot", "parameters": {
"x": 39.0, "y": 19.0, "width": 7.0, "height": 3.0
}}
```
## 🔍 Debug Search Patterns
**Validated patterns from stress testing with thousands of events:**
### High-Value Production Patterns
- **Critical System**: `"error|exception|fail"` (max_lines=3)
- **MCP Operations**: `"MCP Server.*herramienta|Cliente.*conectado"` (max_lines=5)
- **Hydraulic System**: `"Tanque.*Nivel|Bomba.*MaxFlow|PIPE.*Apply"` (max_lines=10)
- **Background Tasks**: `"3D Background|Timing adaptativo"` (max_lines=5)
- **Performance**: `"fps|slow|memory|Simulation.*stopped"` (max_lines=3)
### Load Testing Patterns
- **High-frequency events**: `"Tanque.*Nivel"` (thousands during simulation)
- **Pipe processing**: `"PIPE.*ApplyHydraulicResults"` (continuous flow analysis)
- **System timing**: `"Timing adaptativo.*reseteados"` (performance monitoring)
## 🐍 Python Debug Examples
### Quick Inspections
```python
# Object count by type
types = {}
for obj in objects:
t = type(obj).__name__
types[t] = types.get(t, 0) + 1
print(types)
# Canvas info
print(f"Canvas: {canvas.Width}x{canvas.Height}")
print(f"Simulation: {app.IsSimulationRunning}")
# Find specific objects
pumps = [obj for obj in objects if 'Pump' in str(type(obj))]
print(f"Found {len(pumps)} pumps")
```
## 📋 Debug System Validation Results
**Stress Test Results (September 2025):**
-**Buffer Capacity**: Successfully handled 1600+ events
-**Circular Management**: Automatic cleanup maintains 1000-event limit
-**Real-time Search**: Pattern matching works during high-load simulation
-**Memory Safety**: No leaks observed during 41-second stress test
-**Event Types Captured**: MCP operations, hydraulic calculations, system events
-**Performance**: No degradation under continuous event generation
**Common Event Categories Found in Production:**
```
[MCP Server] Nueva conexión aceptada
[MCP Server] Ejecutando herramienta: search_debug_log
Tanque Tanque Origen: Nivel=1,00m (50,0%), Flujo_neto=0,00L/min
[PIPE] ApplyHydraulicResults for Tubería Hidráulica
[3D Background] ✅ Imagen de fondo agregada con convenciones WPF-BEPU
Timing adaptativo: Contadores y intervalos reseteados
Bomba Bomba Hidráulica: MaxFlow establecido a 0,015000 m³/s
```
## 🚨 Troubleshooting
### Debug Logging Issues ⚡ NEW
```json
{"tool": "get_debug_stats", "parameters": {}}
{"tool": "search_debug_log", "parameters": {"pattern": "MCP Server.*Error|Stack trace", "max_lines": 3}}
{"tool": "clear_debug_buffer", "parameters": {}}
```
**Debug System Status Indicators:**
- `current_log_count`: Current events in buffer (0-1000+)
- `is_buffer_full`: true = circular buffer active (normal under load)
- `cleanup_timer_enabled`: true = automatic memory management active
### Build Issues
```json
{"tool": "get_ctreditor_status", "parameters": {}}
{"tool": "stop_ctreditor", "parameters": {}}
{"tool": "clean_project", "parameters": {}}
{"tool": "build_project", "parameters": {}}
```
### Connection Issues
1. Use `get_simulation_status` to test connectivity
2. Check CtrEditor is running with `get_ctreditor_status`
3. Verify MCP server is active on port 5006
### MCP Client Issues
- **Red LED in Cursor**: Proxy now handles all standard MCP methods correctly
- **Connection timeout**: CtrEditor must be running for tool calls to work
- **Build errors**: Use `build_project` to see only error output
## 💡 Best Practices
### Debug Logging Best Practices ⚡ NEW
- **Monitoring buffer health**: Use `get_debug_stats` to check system status
- **Efficient searching**: Use specific regex patterns with low max_lines (3-10)
- **Load testing**: Start simulation to generate thousands of events safely
- **Buffer management**: System automatically maintains 1000-event limit
- **Memory safety**: Circular buffer prevents memory leaks under heavy load
- **Performance**: Validated to handle 1600+ events without degradation
### General Best Practices
- Always use `get_simulation_status` before expensive operations
- Call `list_objects` only when object data is actually needed
- **NEW**: Use `execute_python` for quick object inspections instead of `list_objects`
- Stop simulation before major structural changes
- Use appropriate units: meters, Pascal, m³/s
- **Python scripts**: Keep under 30 seconds, use `return_variables` for results
- **Debug logs**: Available automatically from app start, no setup required
- **Production ready**: Debug system validated for high-load environments
- Proxy works with both Claude Desktop and Cursor (MCP 2025-06-18)