Skip to main content
Glama

send_command_to_electron

Send JavaScript commands to Electron applications using Chrome DevTools Protocol. Interact with UI elements, execute scripts, navigate routes, and debug page structures for automation and testing purposes.

Instructions

Send JavaScript commands to any running Electron application via Chrome DevTools Protocol.

Enhanced UI interaction commands:

  • 'find_elements': Analyze all interactive elements (buttons, inputs, selects) with their properties

  • 'click_by_text': Click elements by their visible text, aria-label, or title

  • 'click_by_selector': Securely click elements by CSS selector

  • 'fill_input': Fill input fields by selector, placeholder text, or associated label

  • 'select_option': Select dropdown options by value or text

  • 'send_keyboard_shortcut': Send keyboard shortcuts like 'Ctrl+N', 'Meta+N', 'Enter', 'Escape'

  • 'navigate_to_hash': Safely navigate to hash routes (e.g., '#create', '#settings')

  • 'get_page_structure': Get organized overview of page elements (buttons, inputs, selects, links)

  • 'debug_elements': Get debugging info about buttons and form elements on the page

  • 'verify_form_state': Check current form state and validation status

  • 'get_title', 'get_url', 'get_body_text': Basic page information

  • 'eval': Execute custom JavaScript code with enhanced error reporting

IMPORTANT: Arguments must be passed as an object with the correct properties:

Examples:

  • click_by_selector: {"selector": "button.submit-btn"}

  • click_by_text: {"text": "Submit"}

  • fill_input: {"placeholder": "Enter name", "value": "John Doe"}

  • fill_input: {"selector": "#email", "value": "user@example.com"}

  • send_keyboard_shortcut: {"text": "Enter"}

  • eval: {"code": "document.title"}

Use 'get_page_structure' or 'debug_elements' first to understand available elements, then use specific interaction commands.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
argsNoArguments for the command - must be an object with appropriate properties based on the command type
commandYesCommand to send to the Electron process

Implementation Reference

  • MCP tool handler for send_command_to_electron: validates input schema, performs security checks via securityManager, and calls the sendCommandToElectron utility if approved.
    case ToolName.SEND_COMMAND_TO_ELECTRON: {
      const { command, args: commandArgs } = SendCommandToElectronSchema.parse(args);
    
      // Execute command through security manager
      const securityResult = await securityManager.executeSecurely({
        command,
        args: commandArgs,
        sourceIP,
        userAgent,
        operationType: 'command',
      });
    
      if (securityResult.blocked) {
        return {
          content: [
            {
              type: 'text',
              text: `Command blocked: ${securityResult.error}\nRisk Level: ${securityResult.riskLevel}`,
            },
          ],
          isError: true,
        };
      }
    
      if (!securityResult.success) {
        return {
          content: [
            {
              type: 'text',
              text: `Command failed: ${securityResult.error}`,
            },
          ],
          isError: true,
        };
      }
    
      // Execute the actual command if security checks pass
      const result = await sendCommandToElectron(command, commandArgs);
      return {
        content: [{ type: 'text', text: result }],
        isError: false,
      };
    }
  • Zod input schema defining 'command' (string) and optional 'args' (CommandArgsSchema) for the tool.
    export const SendCommandToElectronSchema = z.object({
      command: z.string().describe('Command to send to the Electron process'),
      args: CommandArgsSchema.optional().describe(
        'Arguments for the command - must be an object with appropriate properties based on the command type',
      ),
    });
  • src/tools.ts:32-62 (registration)
    Tool registration object defining name, detailed description of commands, and input schema conversion for MCP tools array.
      {
        name: ToolName.SEND_COMMAND_TO_ELECTRON,
        description: `Send JavaScript commands to any running Electron application via Chrome DevTools Protocol. 
    
    Enhanced UI interaction commands:
    - 'find_elements': Analyze all interactive elements (buttons, inputs, selects) with their properties
    - 'click_by_text': Click elements by their visible text, aria-label, or title
    - 'click_by_selector': Securely click elements by CSS selector
    - 'fill_input': Fill input fields by selector, placeholder text, or associated label
    - 'select_option': Select dropdown options by value or text
    - 'send_keyboard_shortcut': Send keyboard shortcuts like 'Ctrl+N', 'Meta+N', 'Enter', 'Escape'
    - 'navigate_to_hash': Safely navigate to hash routes (e.g., '#create', '#settings')
    - 'get_page_structure': Get organized overview of page elements (buttons, inputs, selects, links)
    - 'debug_elements': Get debugging info about buttons and form elements on the page
    - 'verify_form_state': Check current form state and validation status
    - 'get_title', 'get_url', 'get_body_text': Basic page information
    - 'eval': Execute custom JavaScript code with enhanced error reporting
    
    IMPORTANT: Arguments must be passed as an object with the correct properties:
    
    Examples:
    - click_by_selector: {"selector": "button.submit-btn"}
    - click_by_text: {"text": "Submit"}
    - fill_input: {"placeholder": "Enter name", "value": "John Doe"}
    - fill_input: {"selector": "#email", "value": "user@example.com"}
    - send_keyboard_shortcut: {"text": "Enter"}
    - eval: {"code": "document.title"}
    
    Use 'get_page_structure' or 'debug_elements' first to understand available elements, then use specific interaction commands.`,
        inputSchema: zodToJsonSchema(SendCommandToElectronSchema) as ToolInput,
      },
  • Core implementation utility: maps command strings to generated JavaScript code, executes via Chrome DevTools Protocol on Electron target, handles numerous enhanced UI commands with security measures, and processes/returns results.
    export async function sendCommandToElectron(command: string, args?: CommandArgs): Promise<string> {
      try {
        const target = await findElectronTarget();
        let javascriptCode: string;
    
        switch (command.toLowerCase()) {
          case 'get_title':
            javascriptCode = 'document.title';
            break;
    
          case 'get_url':
            javascriptCode = 'window.location.href';
            break;
    
          case 'get_body_text':
            javascriptCode = 'document.body.innerText.substring(0, 500)';
            break;
    
          case 'click_button':
            // Validate and escape selector input
            const selector = args?.selector || 'button';
            if (selector.includes('javascript:') || selector.includes('<script')) {
              return 'Invalid selector: contains dangerous content';
            }
            const escapedSelector = JSON.stringify(selector);
    
            javascriptCode = `
              const button = document.querySelector(${escapedSelector});
              if (button && !button.disabled) {
                // Enhanced duplicate prevention
                const buttonId = button.id || button.className || 'button';
                const clickKey = 'mcp_click_' + btoa(buttonId).slice(0, 10);
                
                // Check if this button was recently clicked
                if (window[clickKey] && Date.now() - window[clickKey] < 2000) {
                  return 'Button click prevented - too soon after previous click';
                }
                
                // Mark this button as clicked
                window[clickKey] = Date.now();
                
                // Prevent multiple rapid events
                button.style.pointerEvents = 'none';
                
                // Trigger React events properly
                button.focus();
                
                // Use both React synthetic events and native events
                const clickEvent = new MouseEvent('click', {
                  bubbles: true,
                  cancelable: true,
                  view: window
                });
                
                button.dispatchEvent(clickEvent);
                
                // Re-enable after delay
                setTimeout(() => {
                  button.style.pointerEvents = '';
                }, 1000);
                
                return 'Button clicked with enhanced protection';
              }
              return 'Button not found or disabled';
            `;
            break;
    
          case 'find_elements':
            javascriptCode = generateFindElementsCommand();
            break;
    
          case 'click_by_text':
            const clickText = args?.text || '';
            if (!clickText) {
              return 'ERROR: Missing text. Use: {"text": "button text"}. See MCP_USAGE_GUIDE.md for examples.';
            }
            javascriptCode = generateClickByTextCommand(clickText);
            break;
    
          case 'click_by_selector':
            // Secure selector-based clicking
            const clickSelector = args?.selector || '';
    
            // Better error message for common mistake
            if (!clickSelector) {
              return 'ERROR: Missing selector. Use: {"selector": "your-css-selector"}. See MCP_USAGE_GUIDE.md for examples.';
            }
    
            if (clickSelector.includes('javascript:') || clickSelector.includes('<script')) {
              return 'Invalid selector: contains dangerous content';
            }
            const escapedClickSelector = JSON.stringify(clickSelector);
    
            javascriptCode = `
              (function() {
                try {
                  const element = document.querySelector(${escapedClickSelector});
                  if (element) {
                    // Check if element is clickable
                    const rect = element.getBoundingClientRect();
                    if (rect.width === 0 || rect.height === 0) {
                      return 'Element not visible';
                    }
                    
                    // Prevent rapid clicks
                    const clickKey = 'mcp_selector_click_' + btoa(${escapedClickSelector}).slice(0, 10);
                    if (window[clickKey] && Date.now() - window[clickKey] < 1000) {
                      return 'Click prevented - too soon after previous click';
                    }
                    window[clickKey] = Date.now();
                    
                    // Focus and click
                    element.focus();
                    const event = new MouseEvent('click', {
                      bubbles: true,
                      cancelable: true,
                      view: window
                    });
                    element.dispatchEvent(event);
                    
                    return 'Successfully clicked element: ' + element.tagName + 
                           (element.textContent ? ' - "' + element.textContent.substring(0, 50) + '"' : '');
                  }
                  return 'Element not found: ' + ${escapedClickSelector};
                } catch (e) {
                  return 'Error clicking element: ' + e.message;
                }
              })();
            `;
            break;
    
          case 'send_keyboard_shortcut':
            // Secure keyboard shortcut sending
            const key = args?.text || '';
            const validKeys = [
              'Enter',
              'Escape',
              'Tab',
              'Space',
              'ArrowUp',
              'ArrowDown',
              'ArrowLeft',
              'ArrowRight',
            ];
    
            // Parse shortcut like "Ctrl+N" or "Meta+N"
            const parts = key.split('+').map((p) => p.trim());
            const keyPart = parts[parts.length - 1];
            const modifiers = parts.slice(0, -1);
    
            // Helper function to get proper KeyboardEvent.code value
            function getKeyCode(key: string): string {
              // Special keys mapping
              const specialKeys: Record<string, string> = {
                Enter: 'Enter',
                Escape: 'Escape',
                Tab: 'Tab',
                Space: 'Space',
                ArrowUp: 'ArrowUp',
                ArrowDown: 'ArrowDown',
                ArrowLeft: 'ArrowLeft',
                ArrowRight: 'ArrowRight',
                Backspace: 'Backspace',
                Delete: 'Delete',
                Home: 'Home',
                End: 'End',
                PageUp: 'PageUp',
                PageDown: 'PageDown',
              };
    
              if (specialKeys[key]) {
                return specialKeys[key];
              }
    
              // Single character keys
              if (key.length === 1) {
                const upperKey = key.toUpperCase();
                if (upperKey >= 'A' && upperKey <= 'Z') {
                  return `Key${upperKey}`;
                }
                if (upperKey >= '0' && upperKey <= '9') {
                  return `Digit${upperKey}`;
                }
              }
    
              return `Key${key.toUpperCase()}`;
            }
    
            if (keyPart.length === 1 || validKeys.includes(keyPart)) {
              const modifierProps = modifiers
                .map((mod) => {
                  switch (mod.toLowerCase()) {
                    case 'ctrl':
                      return 'ctrlKey: true';
                    case 'shift':
                      return 'shiftKey: true';
                    case 'alt':
                      return 'altKey: true';
                    case 'meta':
                    case 'cmd':
                      return 'metaKey: true';
                    default:
                      return '';
                  }
                })
                .filter(Boolean)
                .join(', ');
    
              javascriptCode = `
                (function() {
                  try {
                    const event = new KeyboardEvent('keydown', {
                      key: '${keyPart}',
                      code: '${getKeyCode(keyPart)}',
                      ${modifierProps},
                      bubbles: true,
                      cancelable: true
                    });
                    document.dispatchEvent(event);
                    return 'Keyboard shortcut sent: ${key}';
                  } catch (e) {
                    return 'Error sending shortcut: ' + e.message;
                  }
                })();
              `;
            } else {
              return `Invalid keyboard shortcut: ${key}`;
            }
            break;
    
          case 'navigate_to_hash':
            // Secure hash navigation
            const hash = args?.text || '';
            if (hash.includes('javascript:') || hash.includes('<script') || hash.includes('://')) {
              return 'Invalid hash: contains dangerous content';
            }
            const cleanHash = hash.startsWith('#') ? hash : '#' + hash;
    
            javascriptCode = `
              (function() {
                try {
                  // Use pushState for safer navigation
                  if (window.history && window.history.pushState) {
                    const newUrl = window.location.pathname + window.location.search + '${cleanHash}';
                    window.history.pushState({}, '', newUrl);
                    
                    // Trigger hashchange event for React Router
                    window.dispatchEvent(new HashChangeEvent('hashchange', {
                      newURL: window.location.href,
                      oldURL: window.location.href.replace('${cleanHash}', '')
                    }));
                    
                    return 'Navigated to hash: ${cleanHash}';
                  } else {
                    // Fallback to direct assignment
                    window.location.hash = '${cleanHash}';
                    return 'Navigated to hash (fallback): ${cleanHash}';
                  }
                } catch (e) {
                  return 'Error navigating: ' + e.message;
                }
              })();
            `;
            break;
    
          case 'fill_input':
            const inputValue = args?.value || args?.text || '';
            if (!inputValue) {
              return 'ERROR: Missing value. Use: {"value": "text", "selector": "..."} or {"value": "text", "placeholder": "..."}. See MCP_USAGE_GUIDE.md for examples.';
            }
            javascriptCode = generateFillInputCommand(
              args?.selector || '',
              inputValue,
              args?.text || args?.placeholder || '',
            );
            break;
    
          case 'select_option':
            javascriptCode = generateSelectOptionCommand(
              args?.selector || '',
              args?.value || '',
              args?.text || '',
            );
            break;
    
          case 'get_page_structure':
            javascriptCode = generatePageStructureCommand();
            break;
    
          case 'debug_elements':
            javascriptCode = `
              (function() {
                const buttons = Array.from(document.querySelectorAll('button')).map(btn => ({
                  text: btn.textContent?.trim(),
                  id: btn.id,
                  className: btn.className,
                  disabled: btn.disabled,
                  visible: btn.getBoundingClientRect().width > 0,
                  type: btn.type || 'button'
                }));
                
                const inputs = Array.from(document.querySelectorAll('input, textarea, select')).map(inp => ({
                  name: inp.name,
                  placeholder: inp.placeholder,
                  type: inp.type,
                  id: inp.id,
                  value: inp.value,
                  visible: inp.getBoundingClientRect().width > 0,
                  enabled: !inp.disabled
                }));
                
                return JSON.stringify({
                  buttons: buttons.filter(b => b.visible).slice(0, 10),
                  inputs: inputs.filter(i => i.visible).slice(0, 10),
                  url: window.location.href,
                  title: document.title
                }, null, 2);
              })()
            `;
            break;
    
          case 'verify_form_state':
            javascriptCode = `
              (function() {
                const forms = Array.from(document.querySelectorAll('form')).map(form => {
                  const inputs = Array.from(form.querySelectorAll('input, textarea, select')).map(inp => ({
                    name: inp.name,
                    type: inp.type,
                    value: inp.value,
                    placeholder: inp.placeholder,
                    required: inp.required,
                    valid: inp.validity?.valid
                  }));
                  
                  return {
                    id: form.id,
                    action: form.action,
                    method: form.method,
                    inputs: inputs,
                    isValid: form.checkValidity?.() || 'unknown'
                  };
                });
                
                return JSON.stringify({ forms, formCount: forms.length }, null, 2);
              })()
            `;
            break;
    
          case 'console_log':
            javascriptCode = `console.log('MCP Command:', '${
              args?.message || 'Hello from MCP!'
            }'); 'Console message sent'`;
            break;
    
          case 'eval':
            const rawCode = typeof args === 'string' ? args : args?.code || command;
            // Enhanced eval with better error handling and result reporting
            const codeHash = Buffer.from(rawCode).toString('base64').slice(0, 10);
            const isStateTest =
              rawCode.includes('window.testState') ||
              rawCode.includes('persistent-test-value') ||
              rawCode.includes('window.testValue');
    
            javascriptCode = `
              (function() {
                try {
                  // Prevent rapid execution of the same code unless it's a state test
                  const codeHash = '${codeHash}';
                  const isStateTest = ${isStateTest};
                  const rawCode = ${JSON.stringify(rawCode)};
                  
                  if (!isStateTest && window._mcpExecuting && window._mcpExecuting[codeHash]) {
                    return { success: false, error: 'Code already executing', result: null };
                  }
                  
                  window._mcpExecuting = window._mcpExecuting || {};
                  if (!isStateTest) {
                    window._mcpExecuting[codeHash] = true;
                  }
                  
                  let result;
                  ${
                    rawCode.trim().startsWith('() =>') || rawCode.trim().startsWith('function')
                      ? `result = (${rawCode})();`
                      : rawCode.includes('return')
                        ? `result = (function() { ${rawCode} })();`
                        : rawCode.includes(';')
                          ? `result = (function() { ${rawCode}; return "executed"; })();`
                          : `result = (function() { return (${rawCode}); })();`
                  }
                  
                  setTimeout(() => {
                    if (!isStateTest && window._mcpExecuting) {
                      delete window._mcpExecuting[codeHash];
                    }
                  }, 1000);
                  
                  // Enhanced result reporting
                  // For simple expressions, undefined might be a valid result for some cases
                  if (result === undefined && !rawCode.includes('window.') && !rawCode.includes('document.') && !rawCode.includes('||')) {
                    return { success: false, error: 'Command returned undefined - element may not exist or action failed', result: null };
                  }
                  if (result === null) {
                    return { success: false, error: 'Command returned null - element may not exist', result: null };
                  }
                  if (result === false && rawCode.includes('click') || rawCode.includes('querySelector')) {
                    return { success: false, error: 'Command returned false - action likely failed', result: false };
                  }
                  
                  return { success: true, error: null, result: result };
                } catch (error) {
                  return { 
                    success: false, 
                    error: 'JavaScript error: ' + error.message,
                    stack: error.stack,
                    result: null 
                  };
                }
              })()
            `;
            break;
    
          default:
            javascriptCode = command;
        }
    
        const rawResult = await executeInElectron(javascriptCode, target);
    
        // Try to parse structured response from enhanced eval
        if (command.toLowerCase() === 'eval') {
          try {
            const parsedResult = JSON.parse(rawResult);
            if (parsedResult && typeof parsedResult === 'object' && 'success' in parsedResult) {
              if (!parsedResult.success) {
                return `❌ Command failed: ${parsedResult.error}${
                  parsedResult.stack ? '\nStack: ' + parsedResult.stack : ''
                }`;
              }
              return `✅ Command successful${
                parsedResult.result !== null ? ': ' + JSON.stringify(parsedResult.result) : ''
              }`;
            }
          } catch {
            // If it's not JSON, treat as regular result
          }
        }
    
        // Handle regular results
        if (rawResult === 'undefined' || rawResult === 'null' || rawResult === '') {
          return `⚠️ Command executed but returned ${
            rawResult || 'empty'
          } - this may indicate the element wasn't found or the action failed`;
        }
    
        return `✅ Result: ${rawResult}`;
      } catch (error) {
        throw new Error(
          `Failed to send command: ${error instanceof Error ? error.message : String(error)}`,
        );
      }
    }
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing behavioral traits: it explains the enhanced UI interaction capabilities, emphasizes secure clicking ('Securely click'), safe navigation ('Safely navigate'), and enhanced error reporting for eval. However, it doesn't mention authentication needs, rate limits, or what happens on command failure.

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 well-structured with clear sections: purpose statement, command listing, argument format explanation, examples, and usage guidance. While comprehensive, some redundancy exists (e.g., listing all commands could be more concise). Every sentence adds value, but it's slightly longer than optimal.

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 (multiple command types, nested parameters) and no output schema, the description does well by explaining command behaviors, argument structures, and usage patterns. However, it doesn't describe return values or error responses, which would be helpful since there's no output schema. The coverage is strong but not fully complete for such a multifaceted tool.

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?

Schema description coverage is 100%, so baseline is 3. The description adds significant value by explaining the command types and their required argument structures with concrete examples. It clarifies that 'Arguments must be passed as an object with the correct properties' and provides specific mappings between commands and their parameter needs (e.g., click_by_selector requires selector, fill_input requires value).

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

Purpose5/5

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

The description explicitly states 'Send JavaScript commands to any running Electron application via Chrome DevTools Protocol' - a specific verb ('Send') with clear resource ('JavaScript commands to Electron application'). It distinguishes from siblings like get_electron_window_info (info gathering), read_electron_logs (log reading), and take_screenshot (screenshot capture) by focusing on interactive command execution.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use specific commands: 'Use get_page_structure or debug_elements first to understand available elements, then use specific interaction commands.' It also distinguishes between different command types (e.g., click_by_text vs click_by_selector) and provides clear examples for when to use each approach.

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

Related 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/halilural/electron-mcp-server'

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