@debugelectron/debug-electron-mcp 1.6.9 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,67 +1,86 @@
1
- # Debug Electron MCP
1
+ # Debug Electron MCP
2
2
 
3
- [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
4
3
  [![npm version](https://img.shields.io/npm/v/@debugelectron/debug-electron-mcp)](https://www.npmjs.com/package/@debugelectron/debug-electron-mcp)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
5
5
  [![MCP](https://img.shields.io/badge/MCP-Model%20Context%20Protocol-blue)](https://modelcontextprotocol.io)
6
6
 
7
- A powerful Model Context Protocol (MCP) server that provides comprehensive Electron application automation, debugging, and observability capabilities. Supercharge your Electron development workflow with AI-powered automation through Chrome DevTools Protocol integration.
7
+ **The ultimate Model Context Protocol (MCP) server for automating, debugging, and testing Electron applications.**
8
+
9
+ Use the power of AI to interact with ANY Electron application. Inspect the DOM, click buttons by text, fill forms, capture screenshots, and read console logs—all through a standardized protocol compatible with Claude Code, Claude Desktop, Cursor, and other MCP clients.
10
+
11
+ Install it once globally — it auto-detects which project you're in and scopes itself. Works with multiple Electron apps across multiple sessions with zero extra config.
8
12
 
9
- ## 🎯 What Makes This Special
13
+ ---
10
14
 
11
- Transform your Electron development experience with **AI-powered automation**:
15
+ ## Table of Contents
16
+
17
+ - [Features](#features)
18
+ - [Quick Start](#quick-start)
19
+ - [How Multi-Project Works](#how-multi-project-works)
20
+ - [Enabling Remote Debugging (Required)](#enabling-remote-debugging-required)
21
+ - [Usage Guide](#usage-guide)
22
+ - [Core Workflow](#core-workflow)
23
+ - [Tool Reference](#tool-reference)
24
+ - [Project Management Tools](#project-management-tools)
25
+ - [Interaction Commands](#interaction-commands)
26
+ - [Advanced: HTTP Server Mode](#advanced-http-server-mode)
27
+ - [Development](#development)
28
+ - [Troubleshooting](#troubleshooting)
29
+ - [License](#license)
12
30
 
13
- - **🔄 Real-time UI Automation**: Click buttons, fill forms, and interact with any Electron app programmatically
14
- - **📸 Visual Debugging**: Take screenshots and capture application state without interrupting development
15
- - **🔍 Deep Inspection**: Extract DOM elements, application data, and performance metrics in real-time
16
- - **⚡ DevTools Protocol Integration**: Universal compatibility with any Electron app - no modifications required
17
- - **🚀 Development Observability**: Monitor logs, system info, and application behavior seamlessly
31
+ ---
18
32
 
19
- ## 🚀 Key Features
33
+ ## Features
20
34
 
21
- ### 🎮 Application Control & Automation
35
+ ### Universal Compatibility
36
+ - **Works with ANY Electron app**: No source code modifications required.
37
+ - **Zero-setup integration**: Connects purely via Chrome DevTools Protocol (CDP).
38
+ - **Cross-platform**: Supports Windows, macOS, and Linux.
22
39
 
23
- - **Launch & Manage**: Start, stop, and monitor Electron applications with full lifecycle control
24
- - **Interactive Automation**: Execute JavaScript code directly in running applications via WebSocket
25
- - **UI Testing**: Automate button clicks, form interactions, and user workflows
26
- - **Process Management**: Track PIDs, monitor resource usage, and handle graceful shutdowns
40
+ ### Auto-Detect & Multi-Project
41
+ - **Automatic project detection**: Reads your `package.json` name or folder name each project gets its own port automatically.
42
+ - **No config per project**: Install the MCP once globally. Open Claude Code in any Electron project and it just works.
43
+ - **Multiple apps, no conflicts**: App A on port 9222, App B on port 9223 — each Claude Code session only talks to its own app.
44
+ - **Shared registry on disk**: `~/.debug-electron-mcp.json` persists port assignments across sessions and restarts.
27
45
 
28
- ### 📊 Advanced Observability
46
+ ### Smart UI Automation
47
+ - **Semantic Interaction**: specific `click_by_text` and `fill_input` commands that "just work."
48
+ - **Visual Intelligence**: Take screenshots of specific windows to verify state.
49
+ - **Robust Actions**: Advanced `drag`, `hover`, `type`, and `wait` commands for complex workflows.
29
50
 
30
- - **Screenshot Capture**: Non-intrusive visual snapshots using Playwright and Chrome DevTools Protocol
31
- - **Real-time Logs**: Stream application logs (main process, renderer, console) with filtering
32
- - **Window Information**: Get detailed window metadata, titles, URLs, and target information
33
- - **System Monitoring**: Track memory usage, uptime, and performance metrics
51
+ ### Deep Observability
52
+ - **DOM Inspection**: `get_page_structure` gives AI a clean copy of the interactive operational map.
53
+ - **Log Streaming**: Read main process, renderer, and console logs in real-time.
54
+ - **Performance**: Monitor memory, timing, and system metrics.
34
55
 
35
- ### 🛠️ Development Productivity
56
+ ---
36
57
 
37
- - **Universal Compatibility**: Works with any Electron app without requiring code modifications
38
- - **DevTools Integration**: Leverage Chrome DevTools Protocol for powerful debugging capabilities
39
- - **Build Automation**: Cross-platform building for Windows, macOS, and Linux
40
- - **Environment Management**: Clean environment handling and debugging port configuration
58
+ ## Quick Start
41
59
 
42
- ## 🚀 Quick Start
60
+ ### Step 1: Add to your MCP config (one time)
43
61
 
44
- **Just add to your MCP config and go!** No environment variables needed.
62
+ #### Claude Code (Global recommended)
45
63
 
46
- **VS Code:**
64
+ Add to `~/.claude/settings.json`:
47
65
  ```json
48
66
  {
49
- "mcp": {
50
- "servers": {
51
- "electron": {
52
- "command": "npx",
53
- "args": ["-y", "@debugelectron/debug-electron-mcp@latest"]
54
- }
67
+ "mcpServers": {
68
+ "debug-electron-mcp": {
69
+ "command": "npx",
70
+ "args": ["-y", "@debugelectron/debug-electron-mcp@latest"]
55
71
  }
56
72
  }
57
73
  }
58
74
  ```
59
75
 
60
- **Claude Desktop:**
76
+ Done. Every Claude Code session now has the Electron tools available.
77
+
78
+ #### VS Code / Cursor
79
+
61
80
  ```json
62
81
  {
63
82
  "mcpServers": {
64
- "electron": {
83
+ "debug-electron-mcp": {
65
84
  "command": "npx",
66
85
  "args": ["-y", "@debugelectron/debug-electron-mcp@latest"]
67
86
  }
@@ -69,11 +88,12 @@ Transform your Electron development experience with **AI-powered automation**:
69
88
  }
70
89
  ```
71
90
 
72
- **Cursor IDE** (`%APPDATA%\Cursor\mcp_config.json`):
91
+ #### Claude Desktop
92
+
73
93
  ```json
74
94
  {
75
95
  "mcpServers": {
76
- "electron": {
96
+ "debug-electron-mcp": {
77
97
  "command": "npx",
78
98
  "args": ["-y", "@debugelectron/debug-electron-mcp@latest"]
79
99
  }
@@ -81,749 +101,286 @@ Transform your Electron development experience with **AI-powered automation**:
81
101
  }
82
102
  ```
83
103
 
84
- That's it! The server is ready to use.
85
-
86
- ## 📦 Installation
104
+ ### Step 2: Start your Electron app with remote debugging
87
105
 
88
- See [Quick Start](#-quick-start) above for MCP configuration. For global installation:
106
+ The first time you use the MCP in a project, it auto-registers the project and assigns a port. Check `list_projects()` to see your assigned port, then start your app:
89
107
 
90
108
  ```bash
91
- npm install -g @debugelectron/debug-electron-mcp
92
- ```
93
-
94
- ## Demo
95
-
96
- See the Electron MCP Server in action:
97
-
98
- [![Watch Demo Video](https://vumbnail.com/1104937830.jpg)](https://vimeo.com/1104937830)
99
-
100
- **[🎬 Watch Full Demo on Vimeo](https://vimeo.com/1104937830)**
101
-
102
- *Watch how easy it is to automate Electron applications with AI-powered MCP commands.*
103
-
104
-
105
- ## ⚡ Enabling Remote Debugging (Required)
106
-
107
- **CRITICAL**: For the Electron MCP Server to communicate with your Electron application, the app **MUST** be started with Chrome DevTools Protocol (CDP) remote debugging enabled on port 9222. Without this, the MCP server cannot connect to or control the application.
108
-
109
- ### 🔍 How It Works
110
-
111
- The Electron MCP Server uses the Chrome DevTools Protocol (CDP) to:
112
- - Connect to your Electron app via WebSocket
113
- - Execute JavaScript in the renderer process
114
- - Capture screenshots and inspect the DOM
115
- - Automate UI interactions (clicks, form fills, etc.)
116
-
117
- The server automatically scans ports **9222-9225** to find running Electron apps with debugging enabled.
118
-
119
- ### 📋 Configuration Methods
120
-
121
- Choose **ONE** of the following methods to enable remote debugging:
122
-
123
- ---
124
-
125
- #### Method 1: Command Line Flag (Recommended for Quick Testing)
126
-
127
- Start your Electron app with the `--remote-debugging-port` flag:
128
-
129
- ```bash
130
- # Using electron directly
131
109
  electron . --remote-debugging-port=9222
132
-
133
- # Using npx
134
- npx electron . --remote-debugging-port=9222
135
-
136
- # Via npm script
137
- npm start -- --remote-debugging-port=9222
138
- ```
139
-
140
- ---
141
-
142
- #### Method 2: Modify package.json Scripts (Recommended for Projects)
143
-
144
- This is the most reliable method. It creates a dedicated command for launching your app with AI capabilities enabled.
145
-
146
- **Step 1: Open your `package.json` file**
147
- Locate the file in the root of your project.
148
-
149
- **Step 2: Find the `"scripts"` section**
150
- It usually looks like this:
151
- ```json
152
- "scripts": {
153
- "start": "electron .",
154
- "build": "electron-builder"
155
- }
156
110
  ```
157
111
 
158
- **Step 3: Add the debug script**
159
- Add a new script (e.g., `"dev"`) that includes the `--remote-debugging-port=9222` flag.
160
- *Make sure to add a comma (`,`) to the end of the previous line!*
161
-
162
- ```json
163
- "scripts": {
164
- "start": "electron .", <-- Add comma here if needed
165
- "build": "electron-builder", <-- Add comma here
166
- "dev": "electron . --remote-debugging-port=9222" <-- ADD THIS LINE
167
- }
168
- ```
169
-
170
- **Note for Frameworks:**
171
- - If you use **Electron Forge**: `"dev": "electron-forge start -- -- --remote-debugging-port=9222"`
172
- - If you use **Electron Builder**: `"dev": "electron-builder start -- --remote-debugging-port=9222"`
173
- - Generally, append the flag after your usual start command.
174
-
175
- **Step 4: Run the script**
176
- Execute the command in your terminal:
177
-
178
- ```bash
179
- npm run dev
180
- ```
181
-
182
- Your app will launch with port 9222 open, ready for the MCP server to connect.
112
+ That's it. The MCP auto-detects your project and scopes all commands to it.
183
113
 
184
114
  ---
185
115
 
186
- #### Method 3: Programmatic Configuration (Best for Production Apps)
116
+ ## How Multi-Project Works
187
117
 
188
- Add this code to your Electron app's **main process** file (usually `main.js` or `main.ts`):
118
+ The MCP automatically detects which project it's running in no flags, no `projectName` in every call, no per-project config.
189
119
 
190
- ```javascript
191
- const { app } = require('electron');
120
+ ### What happens when Claude Code opens in your project:
192
121
 
193
- // Enable remote debugging based on environment or command line args
194
- const enableRemoteDebugging =
195
- process.env.NODE_ENV === 'development' ||
196
- process.env.ELECTRON_MCP_DEBUG === 'true' ||
197
- process.argv.includes('--dev') ||
198
- process.argv.includes('--remote-debugging-port=9222');
199
-
200
- if (enableRemoteDebugging) {
201
- // IMPORTANT: This must be called BEFORE app.whenReady()
202
- app.commandLine.appendSwitch('remote-debugging-port', '9222');
203
- console.log('🔧 Remote debugging enabled on port 9222');
204
- }
205
-
206
- // Rest of your app initialization...
207
- app.whenReady().then(() => {
208
- // Create windows, etc.
209
- });
210
- ```
122
+ 1. Claude Code spawns the MCP server from your project directory
123
+ 2. The MCP reads your `package.json` name (or uses the folder name)
124
+ 3. If the project is already registered, it uses the existing port
125
+ 4. If it's new, it auto-registers and assigns the next free port
126
+ 5. All tool calls are automatically scoped to that project's port
211
127
 
212
- **TypeScript version:**
128
+ ### Example: Two apps, two sessions
213
129
 
214
- ```typescript
215
- import { app } from 'electron';
216
-
217
- const enableRemoteDebugging =
218
- process.env.NODE_ENV === 'development' ||
219
- process.env.ELECTRON_MCP_DEBUG === 'true' ||
220
- process.argv.includes('--dev');
221
-
222
- if (enableRemoteDebugging) {
223
- app.commandLine.appendSwitch('remote-debugging-port', '9222');
224
- console.log('🔧 Remote debugging enabled on port 9222');
225
- }
226
- ```
227
-
228
- ---
229
-
230
- #### Method 4: Environment Variable (CI/CD Friendly)
231
-
232
- Set an environment variable before starting your app:
233
-
234
- **Windows (PowerShell):**
235
- ```powershell
236
- $env:ELECTRON_MCP_DEBUG = "true"
237
- npm start
238
- ```
239
-
240
- **Windows (CMD):**
241
- ```cmd
242
- set ELECTRON_MCP_DEBUG=true && npm start
243
130
  ```
131
+ # Session A: Claude Code in ~/projects/music-app/
132
+ # MCP auto-detects "music-app" → port 9222
133
+ take_screenshot() # only sees music-app
244
134
 
245
- **macOS/Linux:**
246
- ```bash
247
- ELECTRON_MCP_DEBUG=true npm start
135
+ # Session B: Claude Code in ~/projects/todo-app/
136
+ # MCP auto-detects "todo-app" → port 9223
137
+ take_screenshot() # only sees todo-app
248
138
  ```
249
139
 
250
- Then check for this variable in your main process (see Method 3).
140
+ No cross-talk. No manual setup. Each session knows its app.
251
141
 
252
- ---
253
-
254
- ### ✅ Verifying Remote Debugging is Enabled
142
+ ### Check your assigned port
255
143
 
256
- When remote debugging is properly enabled, you'll see a message like this in your console:
144
+ Use `list_projects()` from any session to see all registered projects and their ports:
257
145
 
258
146
  ```
259
- DevTools listening on ws://127.0.0.1:9222/devtools/browser/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
147
+ list_projects()
148
+ # -> Registered projects (2):
149
+ # - music-app: port 9222 [connected (1 window(s))]
150
+ # - todo-app: port 9223 [not connected]
260
151
  ```
261
152
 
262
- You can also verify by opening this URL in a browser:
263
- ```
264
- http://localhost:9222/json
265
- ```
266
-
267
- This should return a JSON array of available debugging targets.
268
-
269
- ### 🚨 Common Issues
270
-
271
- | Issue | Cause | Solution |
272
- |-------|-------|----------|
273
- | "No running Electron application found" | App not started with debugging | Use `--remote-debugging-port=9222` flag |
274
- | Port 9222 already in use | Another debugger or Electron app is running | Close other apps or use a different port (9223-9225) |
275
- | Connection refused | Firewall blocking localhost | Check firewall settings for port 9222 |
276
- | `app.commandLine.appendSwitch` not working | Called after `app.whenReady()` | Move the call to the top of main.js, before any async code |
277
-
278
- ### 🤖 For AI Assistants
279
-
280
- When configuring an Electron app for MCP Server:
281
-
282
- 1. **Check if already configured**: Look for `--remote-debugging-port` in `package.json` scripts or `app.commandLine.appendSwitch` in the main process file
283
- 2. **Preferred method**: Modify `package.json` to add a `dev` or `debug` script with `--remote-debugging-port=9222`
284
- 3. **Always verify**: After starting the app, use `get_electron_window_info` or `list_electron_windows` to confirm connection
285
- 4. **Port range**: The MCP server scans ports 9222-9225, so any of these ports will work
286
-
287
- ## 🎯 Proper MCP Usage Guide
288
-
289
- ### ⚠️ Critical: Argument Structure
290
-
291
- **The most common mistake** when using this MCP server is incorrect argument structure for the `send_command_to_electron` tool.
292
-
293
- #### ❌ Wrong (causes "selector is empty" errors):
294
-
295
- ```javascript
296
- {
297
- "command": "click_by_selector",
298
- "args": "button.submit-btn" // ❌ Raw string - WRONG!
299
- }
300
- ```
153
+ ### Registry persistence
301
154
 
302
- #### Correct:
155
+ Port assignments are saved to `~/.debug-electron-mcp.json` and shared across all sessions:
303
156
 
304
- ```javascript
157
+ ```json
305
158
  {
306
- "command": "click_by_selector",
307
- "args": {
308
- "selector": "button.submit-btn" // Object with selector property
159
+ "portRange": [9222, 9322],
160
+ "projects": {
161
+ "music-app": { "port": 9222 },
162
+ "todo-app": { "port": 9223 }
309
163
  }
310
164
  }
311
165
  ```
312
166
 
313
- ### 📋 Command Argument Reference
314
-
315
- | Command | Required Args | Example |
316
- | --------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------ |
317
- | `click_by_selector` | `{"selector": "css-selector"}` | `{"selector": "button.primary"}` |
318
- | `click_by_text` | `{"text": "button text"}` | `{"text": "Submit"}` |
319
- | `fill_input` | `{"value": "text", "selector": "..."}` or `{"value": "text", "placeholder": "..."}` | `{"placeholder": "Enter name", "value": "John"}` |
320
- | `send_keyboard_shortcut` | `{"text": "key combination"}` | `{"text": "Ctrl+N"}` |
321
- | `eval` | `{"code": "javascript"}` | `{"code": "document.title"}` |
322
- | `get_title`, `get_url`, `get_body_text` | No args needed | `{}` or omit args |
323
-
324
- ### 🔄 Recommended Workflow
325
-
326
- 1. **Inspect**: Start with `get_page_structure` or `debug_elements`
327
- 2. **Target**: Use specific selectors or text-based targeting
328
- 3. **Interact**: Use the appropriate command with correct argument structure
329
- 4. **Verify**: Take screenshots or check page state
330
-
331
- ```javascript
332
- // Step 1: Understand the page
333
- {
334
- "command": "get_page_structure"
335
- }
336
-
337
- // Step 2: Click button using text (most reliable)
338
- {
339
- "command": "click_by_text",
340
- "args": {
341
- "text": "Create New Encyclopedia"
342
- }
343
- }
167
+ ### Manual project management
344
168
 
345
- // Step 3: Fill form field
346
- {
347
- "command": "fill_input",
348
- "args": {
349
- "placeholder": "Enter encyclopedia name",
350
- "value": "AI and Machine Learning"
351
- }
352
- }
169
+ You can also manage projects explicitly with the built-in tools:
353
170
 
354
- // Step 4: Submit with selector
355
- {
356
- "command": "click_by_selector",
357
- "args": {
358
- "selector": "button[type='submit']"
359
- }
360
- }
361
171
  ```
362
-
363
- ### 🐛 Troubleshooting Common Issues
364
-
365
- | Error | Cause | Solution |
366
- | -------------------------------- | -------------------------------- | ------------------------------ |
367
- | "The provided selector is empty" | Passing string instead of object | Use `{"selector": "..."}` |
368
- | "Element not found" | Wrong selector | Use `get_page_structure` first |
369
- | "Click prevented - too soon" | Rapid consecutive clicks | Wait before retrying |
370
-
371
-
372
-
373
-
374
-
375
-
376
- ## 🔧 Available Tools
377
-
378
- ### `launch_electron_app`
379
-
380
- Launch an Electron application with debugging capabilities.
381
-
382
- ```javascript
383
- {
384
- "appPath": "/path/to/electron-app",
385
- "devMode": true, // Enables Chrome DevTools Protocol on port 9222
386
- "args": ["--enable-logging", "--dev"]
387
- }
172
+ register_project({ projectName: "my-app" }) # register with auto-assigned port
173
+ register_project({ projectName: "my-app", port: 9250 }) # register with specific port
174
+ unregister_project({ projectName: "old-app" }) # free a port
175
+ list_projects() # see all projects
388
176
  ```
389
177
 
390
- **Returns**: Process ID and launch confirmation
391
-
392
- ### `get_electron_window_info`
393
-
394
- Get comprehensive window and target information via Chrome DevTools Protocol.
178
+ ### Override with projectName
395
179
 
396
- ```javascript
397
- {
398
- "includeChildren": true // Include child windows and DevTools instances
399
- }
180
+ If you need to target a different project from the current session, pass `projectName` explicitly:
400
181
  ```
401
-
402
- **Returns**:
403
-
404
- - Window IDs, titles, URLs, and types
405
- - DevTools Protocol target information
406
- - Platform details and process information
407
-
408
- ### `take_screenshot`
409
-
410
- Capture high-quality screenshots using Playwright and Chrome DevTools Protocol.
411
-
412
- ```javascript
413
- {
414
- "outputPath": "/path/to/screenshot.png", // Optional: defaults to temp directory
415
- "windowTitle": "My App" // Optional: target specific window
416
- }
182
+ take_screenshot({ projectName: "other-app" })
417
183
  ```
418
184
 
419
- **Features**:
185
+ ---
420
186
 
421
- - Non-intrusive capture (doesn't bring window to front)
422
- - Works with any Electron app
423
- - Fallback to platform-specific tools if needed
187
+ ## Enabling Remote Debugging (Required)
424
188
 
425
- ### `send_command_to_electron`
189
+ Your Electron app **must be running with remote debugging enabled** on the port assigned to your project.
426
190
 
427
- Execute JavaScript commands in the running Electron application via WebSocket.
191
+ Use `list_projects()` to check your assigned port, then start your app with that port.
428
192
 
429
- ```javascript
430
- {
431
- "command": "eval", // Built-in commands: eval, get_title, get_url, click_button, console_log
432
- "args": {
433
- "code": "document.querySelector('button').click(); 'Button clicked!'"
434
- }
435
- }
193
+ ### Method 1: Command Line Flag (Easiest)
194
+ ```bash
195
+ electron . --remote-debugging-port=9222
436
196
  ```
437
197
 
438
- **Enhanced UI Interaction Commands**:
439
-
440
- - `find_elements`: Analyze all interactive UI elements with their properties and positions
441
- - `click_by_text`: Click elements by their visible text, aria-label, or title (more reliable than selectors)
442
- - `fill_input`: Fill input fields by selector, placeholder text, or associated label text
443
- - `select_option`: Select dropdown options by value or visible text
444
- - `get_page_structure`: Get organized overview of all page elements (buttons, inputs, selects, links)
445
- - `get_title`: Get document title
446
- - `get_url`: Get current URL
447
- - `get_body_text`: Extract visible text content
448
- - `click_button`: Click buttons by CSS selector (basic method)
449
- - `console_log`: Send console messages
450
- - `eval`: Execute custom JavaScript code
451
-
452
- **Recommended workflow**: Use `get_page_structure` first to understand available elements, then use specific interaction commands like `click_by_text` or `fill_input`.
453
-
454
- ### `read_electron_logs`
455
-
456
- Stream application logs from main process, renderer, and console.
457
-
458
- ```javascript
459
- {
460
- "logType": "all", // Options: "all", "main", "renderer", "console"
461
- "lines": 50, // Number of recent lines
462
- "follow": false // Stream live logs
198
+ ### Method 2: package.json (Persistent)
199
+ ```json
200
+ "scripts": {
201
+ "start": "electron .",
202
+ "dev:debug": "electron . --remote-debugging-port=9222"
463
203
  }
464
204
  ```
205
+ Then run `npm run dev:debug`.
465
206
 
466
- ### `close_electron_app`
467
-
468
- Gracefully close the Electron application.
469
-
207
+ ### Method 3: Programmatic (Best for Codebase)
470
208
  ```javascript
471
- {
472
- "force": false // Force kill if unresponsive
473
- }
474
- ```
475
-
476
- ### `build_electron_app`
477
-
478
- Build Electron applications for distribution.
209
+ const { app } = require('electron');
479
210
 
480
- ```javascript
481
- {
482
- "projectPath": "/path/to/project",
483
- "platform": "darwin", // win32, darwin, linux
484
- "arch": "x64", // x64, arm64, ia32
485
- "debug": false
211
+ if (process.env.NODE_ENV === 'development' || process.argv.includes('--dev')) {
212
+ const port = process.env.DEBUG_PORT || '9222';
213
+ app.commandLine.appendSwitch('remote-debugging-port', port);
214
+ console.log(`Remote debugging enabled on port ${port}`);
486
215
  }
487
216
  ```
488
217
 
489
- ## 🎮 Demo Application
490
-
491
- Try the interactive demo app to test all MCP Server features:
492
-
493
- ```bash
494
- cd examples/demo-app
495
- npm install
496
- npm run dev
497
- ```
218
+ ### Verification
219
+ Open `http://localhost:<port>/json` in your browser. If you see a JSON list of targets, you are ready.
498
220
 
499
- The demo app includes:
500
- - **Interactive UI Elements**: Buttons, forms, dropdowns, checkboxes
501
- - **Real-time Event Logging**: Monitor all interactions
502
- - **MCP Command Examples**: Built-in usage guide
503
- - **DevTools Integration**: Automatically enabled on port 9222
221
+ ---
504
222
 
505
- See [examples/demo-app/README.md](examples/demo-app/README.md) for detailed instructions.
223
+ ## Usage Guide
224
+
225
+ ### Core Workflow
226
+
227
+ 1. **Inspect**: Use `get_page_structure` to see what buttons and inputs are available.
228
+ 2. **Target**: Identify the element you want (e.g., a button with text "Login").
229
+ 3. **Act**: Send a command like `click_by_text` or `fill_input`.
230
+ 4. **Verify**: Use `take_screenshot` or `get_title` to confirm the action succeeded.
231
+
232
+ ### Tool Reference
233
+
234
+ | Tool | Description |
235
+ |------|-------------|
236
+ | `get_electron_window_info` | Lists all open windows, their titles, and connection IDs. |
237
+ | `list_electron_windows` | Lists all available window targets across applications. |
238
+ | `take_screenshot` | Captures a screenshot of a specific window or the active one. |
239
+ | `read_electron_logs` | Streams console logs from the app (great for debugging errors). |
240
+ | **`send_command_to_electron`** | **The main tool.** Executes specific actions inside the app. |
241
+
242
+ ### Project Management Tools
243
+
244
+ | Tool | Description |
245
+ |------|-------------|
246
+ | `register_project` | Register a project name, auto-assigns a debugging port. |
247
+ | `unregister_project` | Remove a project, free its port. |
248
+ | `list_projects` | Show all registered projects with ports and connection status. |
249
+
250
+ ### Interaction Commands
251
+
252
+ Use these inside `send_command_to_electron`:
253
+
254
+ #### Clicking & Selection
255
+ | Command | Description |
256
+ |---------|-------------|
257
+ | **`click_by_text`** | *Best for buttons/links.* Usage: `{"text": "Submit"}` |
258
+ | **`click_by_selector`** | *Precise control.* Usage: `{"selector": ".submit-btn"}` |
259
+ | **`click_button`** | *Legacy click command.* Usage: `{"selector": "#btn"}` |
260
+ | **`select_option`** | *For dropdowns.* Usage: `{"text": "Category", "value": "Books"}` |
261
+ | **`hover`** | *Hover over elements.* Usage: `{"selector": ".tooltip-trigger"}` |
262
+ | **`drag`** | *Drag and drop.* Usage: `{"startSelector": "#item", "endSelector": "#cart"}` |
263
+
264
+ #### Input & Forms
265
+ | Command | Description |
266
+ |---------|-------------|
267
+ | **`fill_input`** | *Smart filling.* Usage: `{"placeholder": "Username", "value": "admin"}` |
268
+ | **`type`** | *Simulates real typing.* Usage: `{"text": "Hello World", "slowly": true}` |
269
+ | **`verify_form_state`** | *Checks validity of all forms.* |
270
+ | **`send_keyboard_shortcut`** | *Send key combinations.* Usage: `{"text": "Ctrl+S"}` |
271
+
272
+ #### Observation
273
+ | Command | Description |
274
+ |---------|-------------|
275
+ | **`get_page_structure`** | *Returns a simplified JSON map of the UI.* |
276
+ | **`find_elements`** | *Detailed list of all interactive elements.* |
277
+ | **`is_visible`** | *Checks visibility.* Usage: `{"selector": "#error-modal"}` |
278
+ | **`get_attribute`** | *Get attributes.* Usage: `{"selector": "img", "attribute": "src"}` |
279
+ | **`count`** | *Count matching elements.* Usage: `{"selector": "li.item"}` |
280
+ | **`debug_elements`** | *Get detailed debug info for buttons and inputs.* |
281
+ | **`get_title`** | *Get the document title.* |
282
+ | **`get_url`** | *Get the current URL.* |
283
+ | **`get_body_text`** | *Get the visible body text.* |
284
+
285
+ #### Advanced
286
+ | Command | Description |
287
+ |---------|-------------|
288
+ | **`wait`** | *Wait for element/time.* Usage: `{"duration": 1000}` or `{"text": "Loading"}` |
289
+ | **`navigate_to_hash`** | *Navigate to hash routes.* Usage: `{"text": "settings"}` |
290
+ | **`eval`** | *Execute custom JavaScript.* Usage: `{"code": "alert('Hello')"}` |
291
+ | **`console_log`** | *Write to app console.* Usage: `{"message": "Hello"}` |
506
292
 
507
- ## 💡 Usage Examples
293
+ ---
508
294
 
509
- ### Smart UI Interaction Workflow
295
+ ## Advanced: HTTP Server Mode
510
296
 
511
- ```javascript
512
- // 1. First, understand the page structure
513
- await send_command_to_electron({
514
- command: 'get_page_structure',
515
- });
516
-
517
- // 2. Click a button by its text (much more reliable than selectors)
518
- await send_command_to_electron({
519
- command: 'click_by_text',
520
- args: {
521
- text: 'Login', // Finds buttons containing "Login" in text, aria-label, or title
522
- },
523
- });
524
-
525
- // 3. Fill inputs by their label or placeholder text
526
- await send_command_to_electron({
527
- command: 'fill_input',
528
- args: {
529
- text: 'username', // Finds input with label "Username" or placeholder "Enter username"
530
- value: 'john.doe@example.com',
531
- },
532
- });
533
-
534
- await send_command_to_electron({
535
- command: 'fill_input',
536
- args: {
537
- text: 'password',
538
- value: 'secretpassword',
539
- },
540
- });
541
-
542
- // 4. Select dropdown options by visible text
543
- await send_command_to_electron({
544
- command: 'select_option',
545
- args: {
546
- text: 'country', // Finds select with label containing "country"
547
- value: 'United States', // Selects option with this text
548
- },
549
- });
550
-
551
- // 5. Take a screenshot to verify the result
552
- await take_screenshot();
553
- ```
297
+ For advanced use cases where you want a single long-lived server that multiple AI clients share, you can run the server in HTTP mode.
554
298
 
555
- ### Advanced Element Detection
299
+ > **Note:** Most users don't need this. The standard setup auto-detects projects and handles multiple apps with zero extra config.
556
300
 
557
- ```javascript
558
- // Find all interactive elements with detailed information
559
- await send_command_to_electron({
560
- command: 'find_elements',
561
- });
562
-
563
- // This returns detailed info about every clickable element and input:
564
- // {
565
- // "type": "clickable",
566
- // "text": "Submit Form",
567
- // "id": "submit-btn",
568
- // "className": "btn btn-primary",
569
- // "ariaLabel": "Submit the registration form",
570
- // "position": { "x": 100, "y": 200, "width": 120, "height": 40 },
571
- // "visible": true
572
- // }
301
+ **Step 1:** Start the server:
302
+ ```bash
303
+ npx @debugelectron/debug-electron-mcp@latest serve
304
+ npx @debugelectron/debug-electron-mcp@latest serve --port 4000
573
305
  ```
574
306
 
575
- ### Automated UI Testing
576
-
577
- ```javascript
578
- // Launch app in development mode
579
- await launch_electron_app({
580
- appPath: '/path/to/app',
581
- devMode: true,
582
- });
583
-
584
- // Take a screenshot
585
- await take_screenshot();
586
-
587
- // Click a button programmatically
588
- await send_command_to_electron({
589
- command: 'eval',
590
- args: {
591
- code: "document.querySelector('#submit-btn').click()",
592
- },
593
- });
594
-
595
- // Verify the result
596
- await send_command_to_electron({
597
- command: 'get_title',
598
- });
307
+ **Step 2:** Point your MCP config to the URL:
308
+ ```json
309
+ {
310
+ "mcpServers": {
311
+ "debug-electron-mcp": {
312
+ "url": "http://localhost:3100/mcp"
313
+ }
314
+ }
315
+ }
599
316
  ```
600
317
 
601
- ### Development Debugging
602
-
603
- ```javascript
604
- // Get window information
605
- const windowInfo = await get_electron_window_info();
606
-
607
- // Extract application data
608
- await send_command_to_electron({
609
- command: 'eval',
610
- args: {
611
- code: 'JSON.stringify(window.appState, null, 2)',
612
- },
613
- });
614
-
615
- // Monitor logs
616
- await read_electron_logs({
617
- logType: 'all',
618
- lines: 100,
619
- });
318
+ **Step 3:** Pass `projectName` in tool calls (no auto-detect in HTTP mode):
620
319
  ```
621
-
622
- ### Performance Monitoring
623
-
624
- ```javascript
625
- // Get system information
626
- await send_command_to_electron({
627
- command: 'eval',
628
- args: {
629
- code: '({memory: performance.memory, timing: performance.timing})',
630
- },
631
- });
632
-
633
- // Take periodic screenshots for visual regression testing
634
- await take_screenshot({
635
- outputPath: '/tests/screenshots/current.png',
636
- });
320
+ send_command_to_electron({ projectName: "music-app", command: "get_title" })
637
321
  ```
638
322
 
639
- ## 🏗️ Architecture
640
-
641
- ### Chrome DevTools Protocol Integration
642
-
643
- - **Universal Compatibility**: Works with any Electron app that has remote debugging enabled
644
- - **Real-time Communication**: WebSocket-based command execution with the renderer process
645
- - **No App Modifications**: Zero changes required to target applications
646
-
647
- ### Process Management
648
-
649
- - **Clean Environment**: Handles `ELECTRON_RUN_AS_NODE` and other environment variables
650
- - **Resource Tracking**: Monitors PIDs, memory usage, and application lifecycle
651
- - **Graceful Shutdown**: Proper cleanup and process termination
323
+ **Health check:** `http://localhost:3100/health`
652
324
 
653
- ### Cross-Platform Support
654
-
655
- - **macOS**: Uses Playwright CDP with screencapture fallback
656
- - **Windows**: PowerShell-based window detection and capture
657
- - **Linux**: X11 window management (planned)
325
+ ---
658
326
 
659
- ## 🧪 Development
327
+ ## Development
660
328
 
661
329
  ### Prerequisites
662
-
663
330
  - Node.js 18+
664
- - TypeScript 4.5+
665
- - **Electron** - Required for running and testing Electron applications
666
-
667
- ```bash
668
- # Install Electron globally (recommended)
669
- npm install -g electron
670
-
671
- # Or install locally in your project
672
- npm install electron --save-dev
673
- ```
674
-
675
- ### Target Application Setup
676
-
677
- For the MCP server to work with your Electron application, you need to enable remote debugging. Add this code to your Electron app's main process:
678
-
679
- ```javascript
680
- const { app } = require('electron');
681
- const isDev = process.env.NODE_ENV === 'development' || process.argv.includes('--dev');
682
-
683
- // Enable remote debugging in development mode
684
- if (isDev) {
685
- app.commandLine.appendSwitch('remote-debugging-port', '9222');
686
- }
687
- ```
688
-
689
- **Alternative approaches:**
690
-
691
- ```bash
692
- # Launch your app with debugging enabled
693
- electron . --remote-debugging-port=9222
694
-
695
- # Or via npm script
696
- npm run dev -- --remote-debugging-port=9222
697
- ```
698
-
699
- **Note:** The MCP server automatically scans ports 9222-9225 to detect running Electron applications with remote debugging enabled.
331
+ - npm or pnpm
700
332
 
701
333
  ### Setup
702
-
703
334
  ```bash
704
335
  git clone https://github.com/TheDarkSkyXD/debug-electron-mcp.git
705
336
  cd debug-electron-mcp
706
-
707
337
  npm install
708
338
  npm run build
709
-
710
- # Run tests
711
- npm test
712
-
713
- # Development mode with auto-rebuild
714
- npm run dev
715
339
  ```
716
340
 
717
- ### Testing
718
-
719
- The project includes comprehensive test files for React compatibility:
720
-
341
+ ### Running Locally
721
342
  ```bash
722
- # Run React compatibility tests
723
- cd tests/integration/react-compatibility
724
- electron test-react-electron.js
343
+ npm run dev # stdio mode
344
+ npx tsx src/index.ts --project my-app # explicit project scope
345
+ npx tsx src/index.ts serve # HTTP mode
725
346
  ```
726
347
 
727
- See [`tests/integration/react-compatibility/README.md`](tests/integration/react-compatibility/README.md) for detailed testing instructions and scenarios.
728
-
729
- ### React Compatibility
730
-
731
- This MCP server has been thoroughly tested with React applications and handles common React patterns correctly:
732
-
733
- - **✅ React Event Handling**: Properly handles `preventDefault()` in click handlers
734
- - **✅ Form Input Detection**: Advanced scoring algorithm works with React-rendered inputs
735
- - **✅ Component Interaction**: Compatible with React components, hooks, and state management
736
-
737
- ### Project Structure
738
-
739
- ```
740
- src/
741
- ├── handlers.ts # MCP tool handlers
742
- ├── index.ts # Server entry point
743
- ├── tools.ts # Tool definitions
744
- ├── screenshot.ts # Screenshot functionality
745
- ├── utils/
746
- │ ├── process.ts # Process management & DevTools Protocol
747
- │ ├── logs.ts # Log management
748
- │ └── project.ts # Project scaffolding
749
- └── schemas/ # JSON schemas for validation
348
+ ### Testing
349
+ ```bash
350
+ npm test # unit tests
351
+ npm run test:react # integration tests
750
352
  ```
751
353
 
752
- ## 🔐 Security & Best Practices
753
-
754
- - **Sandboxed Execution**: All JavaScript execution is contained within the target Electron app
755
- - **Path Validation**: Only operates on explicitly provided application paths
756
- - **Process Isolation**: Each launched app runs in its own process space
757
- - **No Persistent Access**: No permanent modifications to target applications
758
-
759
- ## 🤝 Contributing
760
-
761
- We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
762
-
763
- **Before reporting issues**: Please use the standardized [`ISSUE_TEMPLATE.md`](ISSUE_TEMPLATE.md) for proper bug reporting format. For React compatibility problems or similar technical issues, also review [`REACT_COMPATIBILITY_ISSUES.md`](REACT_COMPATIBILITY_ISSUES.md) for detailed debugging examples, including proper command examples, error outputs, and reproduction steps.
764
-
765
- 1. Fork the repository
766
- 2. Create a feature branch (`git checkout -b feature/awesome-feature`)
767
- 3. Commit your changes (`git commit -m 'Add awesome feature'`)
768
- 4. Push to the branch (`git push origin feature/awesome-feature`)
769
- 5. Open a Pull Request
770
-
771
- ## 📄 License
772
-
773
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
774
-
775
- ## 🙌 Credits & Attribution
776
-
777
- **Original Author**: [Halil Ural](https://github.com/halilural)
778
-
779
- This project is a fork of [halilural/electron-mcp-server](https://github.com/halilural/electron-mcp-server) with enhancements for **Cursor IDE compatibility** and improved stability.
780
-
781
- ### Forked & Maintained By
782
-
783
- - [Antigravity](https://github.com/TheDarkSkyXD) - Cursor IDE integration improvements, bug fixes, and ongoing maintenance
784
-
785
- ### Key Improvements in This Fork
786
-
787
- - ✅ **Cursor IDE Compatibility**: Full integration with Cursor IDE for seamless AI-powered Electron automation
788
- - ✅ **Enhanced Stability**: Improved error handling and reliability
789
- - ✅ **Better Documentation**: Added comprehensive guides for local development and troubleshooting
790
- - ✅ **Scoped Package**: Published as `@debugelectron/electron-mcp-server` on npm
791
-
792
- ### Contributing to This Fork
793
-
794
- We welcome contributions! If you have improvements or bug fixes, please feel free to:
795
- 1. Fork this repository
796
- 2. Create a feature branch
797
- 3. Submit a pull request with your improvements
798
-
799
354
  ---
800
355
 
801
- ## ☕ Support
356
+ ## Troubleshooting
802
357
 
803
- If this project helped you, consider buying me a coffee! ☕
358
+ **"Target not found" / "No running Electron application"**
359
+ - Check your assigned port with `list_projects()`.
360
+ - Start your Electron app with `--remote-debugging-port=<port>`.
361
+ - Verify: open `http://localhost:<port>/json` in your browser.
804
362
 
805
- [![Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/)
363
+ **"Project 'xyz' is not registered"**
364
+ - This shouldn't happen with auto-detect. If it does, run `register_project({ projectName: "xyz" })`.
365
+ - Check `list_projects()` to see registered projects.
806
366
 
807
- Your support helps me maintain and improve this project. Thank you! 🙏
367
+ **Wrong project detected**
368
+ - The MCP uses your `package.json` name, or the folder name if no package.json exists.
369
+ - To override, use `--project` flag: `"args": ["-y", "@debugelectron/debug-electron-mcp@latest", "--project", "correct-name"]`
808
370
 
809
- ## 🙏 Acknowledgments
371
+ **"No free ports available"**
372
+ - Default range is 9222-9322 (100 ports).
373
+ - Free unused ports: `unregister_project({ projectName: "old-app" })`.
810
374
 
811
- - **[Model Context Protocol](https://modelcontextprotocol.io)** - Standardized AI-application interface
812
- - **[Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/)** - Universal debugging interface
813
- - **[Playwright](https://playwright.dev)** - Reliable browser automation
814
- - **[Electron](https://electronjs.org)** - Cross-platform desktop applications
375
+ **"Selector is empty" error**
376
+ - **Wrong:** `{"command": "click_by_selector", "args": ".btn"}`
377
+ - **Correct:** `{"command": "click_by_selector", "args": {"selector": ".btn"}}`
815
378
 
816
- ## 🔗 Links
379
+ ---
817
380
 
818
- - **[GitHub Repository](https://github.com/TheDarkSkyXD/electron-mcp-server)**
819
- - **[NPM Package](https://www.npmjs.com/package/@debugelectron/electron-mcp-server)**
820
- - **[Original Repository](https://github.com/halilural/electron-mcp-server)** - Original project by Halil Ural
821
- - **[Model Context Protocol](https://modelcontextprotocol.io)**
822
- - **[Chrome DevTools Protocol Docs](https://chromedevtools.github.io/devtools-protocol/)**
823
- - **[Cursor IDE Setup Guide](./CURSOR_SETUP.md)** - Complete setup guide for Cursor IDE integration
824
- - **[Issue Template](./ISSUE_TEMPLATE.md)** - Standardized bug reporting format
825
- - **[React Compatibility Issues Documentation](./REACT_COMPATIBILITY_ISSUES.md)** - Technical debugging guide for React applications
381
+ ## License
826
382
 
827
- ---
383
+ MIT License. See [LICENSE](LICENSE) for details.
828
384
 
829
- **Ready to supercharge your Electron development with AI-powered automation?** Install the MCP server and start building smarter workflows today! 🚀
385
+ ### Credits
386
+ Forked and maintained by [Antigravity](https://github.com/TheDarkSkyXD), originally based on work by [halilural](https://github.com/halilural).