Skip to main content
Glama

debug_window_detection

Diagnose window detection issues by providing detailed PowerShell environment diagnostics, process enumeration, and detection capability analysis.

Instructions

Comprehensive debugging information for window detection issues.

Returns:
    JSON string with detailed diagnostics about PowerShell environment,
    process enumeration, and window detection capabilities.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • MCP tool handler for debug_window_detection. Collects environment info, delegates to WindowsWindowManager for detailed diagnostics if available, lists current windows, and returns formatted JSON.
    @mcp.tool()
    async def debug_window_detection() -> str:
        """
        Comprehensive debugging information for window detection issues.
        
        Returns:
            JSON string with detailed diagnostics about PowerShell environment,
            process enumeration, and window detection capabilities.
        """
        try:
            wm = get_window_manager()
            
            # Get basic environment info
            env_info = wm.get_environment_info()
            
            debug_result = {
                "status": "success",
                "environment": env_info,
                "window_detection_debug": {}
            }
            
            # If using Windows manager, get detailed debug info
            if hasattr(wm.manager, 'debug_window_detection'):
                logger.info("Running comprehensive window detection debug...")
                debug_info = wm.manager.debug_window_detection()
                debug_result["window_detection_debug"] = debug_info
            else:
                debug_result["window_detection_debug"] = {
                    "message": "Debug functionality only available for Windows Window Manager"
                }
            
            # Also include current window list for comparison
            current_windows = wm.list_windows()
            debug_result["current_window_list"] = current_windows
            debug_result["current_window_count"] = len(current_windows)
            
            logger.info(f"Debug complete: found {len(current_windows)} windows")
            
            return json.dumps(debug_result, indent=2)
            
        except Exception as e:
            logger.error(f"Failed to run debug window detection: {e}")
            return json.dumps({
                "status": "error", 
                "error": str(e),
                "environment": {"error": "Could not determine environment"}
            })
  • Core helper method in WindowsWindowManager class that provides comprehensive PowerShell-based diagnostics for Windows window detection, including process counts, window filtering logic, and raw outputs for troubleshooting.
        def debug_window_detection(self) -> Dict[str, any]:
            """
            Comprehensive debugging information for window detection.
            Returns detailed diagnostics about the PowerShell environment and window detection.
            """
            debug_info = {
                'powershell_available': self.powershell_available,
                'detection_methods': [],
                'raw_powershell_output': '',
                'parsing_errors': [],
                'process_info': {}
            }
            
            if not self.powershell_available:
                debug_info['error'] = 'PowerShell not available'
                return debug_info
            
            try:
                # Test basic PowerShell functionality
                basic_test = subprocess.run(
                    ['powershell.exe', '-Command', 'Get-Process | Select-Object -First 5 Name, Id | ConvertTo-Json'],
                    capture_output=True,
                    text=True,
                    check=True,
                    timeout=10
                )
                debug_info['basic_powershell_test'] = 'SUCCESS'
                debug_info['sample_processes'] = basic_test.stdout.strip()[:200] + '...'
                
            except Exception as e:
                debug_info['basic_powershell_test'] = f'FAILED: {str(e)}'
                return debug_info
            
            # Test our enhanced window detection script with verbose output
            try:
                debug_script = '''
                $VerbosePreference = "Continue"
                Write-Verbose "Starting window detection debug..."
                
                Add-Type -TypeDefinition @"
                    using System;
                    using System.Runtime.InteropServices;
                    using System.Text;
                    
                    public class Win32 {
                        [DllImport("user32.dll")]
                        public static extern bool IsWindowVisible(IntPtr hWnd);
                        
                        [DllImport("user32.dll")]
                        public static extern bool IsIconic(IntPtr hWnd);
                        
                        [DllImport("user32.dll")]
                        public static extern bool IsZoomed(IntPtr hWnd);
                        
                        [DllImport("user32.dll")]
                        public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
                        
                        [DllImport("user32.dll")]
                        public static extern int GetWindowTextLength(IntPtr hWnd);
                    }
    "@
                
                $allProcesses = Get-Process | Measure-Object | Select-Object -ExpandProperty Count
                Write-Verbose "Total processes found: $allProcesses"
                
                $processesWithWindows = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 } | Measure-Object | Select-Object -ExpandProperty Count
                Write-Verbose "Processes with windows: $processesWithWindows"
                
                $windows = @()
                Get-Process | Where-Object { 
                    $_.MainWindowHandle -ne 0 -and $_.ProcessName -notmatch "^(dwm|csrss|winlogon|wininit)$"
                } | ForEach-Object {
                    Write-Verbose "Processing: $($_.ProcessName) (ID: $($_.Id))"
                    
                    $handle = [IntPtr]$_.MainWindowHandle
                    $isVisible = [Win32]::IsWindowVisible($handle)
                    $isMinimized = [Win32]::IsIconic($handle)
                    $isMaximized = [Win32]::IsZoomed($handle)
                    
                    # Only include capturable windows (same logic as main script)
                    if (-not ($isVisible -or $isMinimized)) {
                        Write-Verbose "Skipping hidden window: $($_.ProcessName)"
                        return
                    }
                    
                    $windows += @{
                        process_name = $_.ProcessName
                        process_id = $_.Id
                        window_handle = $_.MainWindowHandle.ToString()
                        main_window_title = $_.MainWindowTitle
                        is_visible = $isVisible
                        is_minimized = $isMinimized
                        is_maximized = $isMaximized
                        window_state = if ($isMinimized) { "minimized" } elseif ($isMaximized) { "maximized" } else { "normal" }
                    }
                }
                
                Write-Host "PROCESS_COUNT:$allProcesses"
                Write-Host "WINDOWS_COUNT:$processesWithWindows"
                Write-Host "FILTERED_COUNT:$($windows.Count)"
                $windows | ConvertTo-Json -Depth 2
                '''
                
                result = subprocess.run(
                    ['powershell.exe', '-Command', debug_script],
                    capture_output=True,
                    text=True,
                    timeout=30
                )
                
                debug_info['enhanced_script_exit_code'] = result.returncode
                debug_info['raw_powershell_output'] = result.stdout
                debug_info['powershell_stderr'] = result.stderr
                
                # Parse the debug output
                lines = result.stdout.split('\n')
                for line in lines:
                    if line.startswith('PROCESS_COUNT:'):
                        debug_info['total_processes'] = int(line.split(':')[1])
                    elif line.startswith('WINDOWS_COUNT:'):
                        debug_info['processes_with_windows'] = int(line.split(':')[1])
                    elif line.startswith('FILTERED_COUNT:'):
                        debug_info['filtered_windows'] = int(line.split(':')[1])
                
            except Exception as e:
                debug_info['enhanced_script_error'] = str(e)
            
            return debug_info
  • server.py:608-608 (registration)
    FastMCP tool registration decorator for the debug_window_detection tool.
    @mcp.tool()
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses that the tool returns 'detailed diagnostics' in JSON format, covering specific areas (PowerShell environment, process enumeration, window detection capabilities). However, it doesn't mention whether this is a read-only operation, if it affects system state, performance characteristics, or error handling. The description adds some behavioral context but leaves significant gaps for a debugging tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise with two sentences. The first sentence states the purpose, and the second describes the return format and scope. There's no wasted text, and information is front-loaded. It could be slightly more structured by explicitly separating purpose from output details, but it's efficient.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (debugging with no inputs), the description is reasonably complete. It explains the purpose and output format. Since an output schema exists, the description doesn't need to detail return values. However, for a debugging tool with no annotations, it could better cover behavioral aspects like side effects or usage context. The description is adequate but not fully comprehensive.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has 0 parameters with 100% schema description coverage, so the schema fully documents the lack of inputs. The description doesn't need to compensate for any parameter gaps. It appropriately doesn't discuss parameters, focusing instead on the output. This meets the baseline for zero-parameter tools.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: providing 'comprehensive debugging information for window detection issues.' It specifies the verb ('debugging') and resource ('window detection'), though it doesn't explicitly differentiate from sibling tools like 'check_system_dependencies' or 'list_windows' that might also provide diagnostic information. The purpose is clear but lacks sibling differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites, appropriate contexts, or exclusions. With sibling tools like 'check_system_dependencies' that might also provide diagnostics, the agent receives no help in choosing between them. The description merely states what the tool does, not when to invoke it.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/PovedaAqui/auto-snap-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server