@wonderwhy-er/desktop-commander 0.2.50 → 0.2.52

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
@@ -17,19 +17,6 @@ Work with code and text, run processes, and automate tasks, going far beyond oth
17
17
  <img width="380" height="200" src="https://glama.ai/mcp/servers/zempur9oh4/badge" alt="Desktop Commander MCP" />
18
18
  </a>
19
19
 
20
- ## 🖥️ Try the Desktop Commander App (Beta)
21
-
22
- **Want a better experience?** The Desktop Commander App gives you everything the MCP server does, plus:
23
-
24
- - **Use any AI model** — Claude, GPT-4.5, Gemini 2.5, or any model you prefer
25
- - **See file changes live** — visual file previews as AI edits your files
26
- - **Add custom MCPs and context** — extend with your own tools, no config files
27
- - **Coming soon** — skills system, dictation, background scheduled tasks, and more
28
-
29
- **👉 [Download the App](https://desktopcommander.app/#download)** (macOS & Windows)
30
-
31
- > The MCP server below still works great with Claude Desktop and other MCP clients — the app is for those who want a dedicated, polished experience.
32
-
33
20
  ## Table of Contents
34
21
  - [Features](#features)
35
22
  - [How to install](#how-to-install)
@@ -470,21 +457,24 @@ Or add to `.qwen/settings.json` (project) or `~/.qwen/settings.json` (global). S
470
457
  <details>
471
458
  <summary><b>ChatGPT / Claude Web (Remote MCP)</b></summary>
472
459
 
473
- Use Desktop Commander from **ChatGPT**, **Claude web**, and other AI services via Remote MCP — no desktop app required.
460
+ Use Desktop Commander from **ChatGPT**, **Claude web**, and other AI services while commands still execute on your computer.
461
+
462
+ Start the Remote Device:
463
+
464
+ ```bash
465
+ npx @wonderwhy-er/desktop-commander@latest remote
466
+ ```
474
467
 
475
- **👉 [Get started at mcp.desktopcommander.app](https://mcp.desktopcommander.app)**
468
+ On first run, complete browser authentication, then connect your AI at **[mcp.desktopcommander.app](https://mcp.desktopcommander.app)**.
476
469
 
477
- How it works:
478
- 1. You run a lightweight **Remote Device** on your computer
479
- 2. It connects securely to the cloud Remote MCP service
480
- 3. Your AI sends commands through the cloud to your device
481
- 4. Commands execute locally, results return to your AI
482
- 5. **You stay in control** — stop anytime with `Ctrl+C`
470
+ - Stop the local device temporarily with `Ctrl+C`
471
+ - See available CLI options with `npx @wonderwhy-er/desktop-commander@latest remote --help`
472
+ - See **[Remote MCP setup, logout/revocation, CLI reference, and troubleshooting](src/remote-device/README.md)**
483
473
 
484
474
  ### Security
485
475
 
486
- - ✅ Device only runs when you start it
487
- - ✅ Commands execute under your user permissions
476
+ - ✅ The Remote Device only accepts commands while it is running
477
+ - ✅ Commands execute locally under your user permissions
488
478
  - ✅ Secure OAuth authentication and encrypted communication channel
489
479
 
490
480
  </details>
@@ -823,7 +813,7 @@ Locations:
823
813
 
824
814
  ### Remote calls and server-side retention
825
815
 
826
- Calls executed through Remote Desktop Commander are still handled by the local MCP server and use the same local history files above. The Remote Desktop Commander service does **not currently retain command arguments or command results as a historical server-side audit trail after execution is complete**.
816
+ Calls executed through Remote Desktop Commander are still handled by the local MCP server and use the same local history files above. The Remote Desktop Commander service temporarily stores tool arguments and results in `mcp_remote_calls` so calls can be routed and completed. Terminal rows are automatically swept shortly after completion (eligible for deletion after one minute, with a one-hour creation-time backstop), so they are not kept as a long-term historical server-side audit trail.
827
817
 
828
818
  These local history files are also separate from Desktop Commander's optional telemetry. The files themselves are not uploaded as telemetry. See [Data Collection & Privacy](#data-collection--privacy) and [PRIVACY.md](PRIVACY.md) for telemetry details.
829
819
 
@@ -1,6 +1,21 @@
1
1
  import { MCPDevice, getRemoteDeviceConfigPath } from '../remote-device/device.js';
2
2
  import fs from 'fs/promises';
3
3
  import os from 'os';
4
+ import { captureRemote } from '../utils/capture.js';
5
+ const BLUE = '\x1b[34m';
6
+ const RESET = '\x1b[0m';
7
+ function printRemoteHeader() {
8
+ console.log();
9
+ console.log(`${BLUE}██████╗ ███████╗███████╗██╗ ██╗████████╗ ██████╗ ██████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗ █████╗ ███╗ ██╗██████╗ ███████╗██████╗${RESET}`);
10
+ console.log(`${BLUE}██╔══██╗██╔════╝██╔════╝██║ ██╔╝╚══██╔══╝██╔═══██╗██╔══██╗ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔══██╗████╗ ██║██╔══██╗██╔════╝██╔══██╗${RESET}`);
11
+ console.log(`${BLUE}██║ ██║█████╗ ███████╗█████╔╝ ██║ ██║ ██║██████╔╝ ██║ ██║ ██║██╔████╔██║██╔████╔██║███████║██╔██╗ ██║██║ ██║█████╗ ██████╔╝${RESET}`);
12
+ console.log(`${BLUE}██║ ██║██╔══╝ ╚════██║██╔═██╗ ██║ ██║ ██║██╔═══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║██╔══╝ ██╔══██╗${RESET}`);
13
+ console.log(`${BLUE}██████╔╝███████╗███████║██║ ██╗ ██║ ╚██████╔╝██║ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝███████╗██║ ██║${RESET}`);
14
+ console.log(`${BLUE}╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝${RESET}`);
15
+ console.log();
16
+ console.log(`${BLUE}🌐 Remote Connection${RESET}`);
17
+ console.log();
18
+ }
4
19
  export async function runRemote() {
5
20
  if (process.argv.includes('--help') || process.argv.includes('-h')) {
6
21
  console.log(`Desktop Commander Remote MCP device
@@ -13,7 +28,16 @@ Options:
13
28
  --no-persist-session Do not reuse or save authentication for this run
14
29
  --disable-no-sleep Do not prevent sleep while the remote device is running
15
30
  --debug Enable verbose debug logging
16
- -h, --help Show this help`);
31
+ -h, --help Show this help
32
+
33
+ Examples:
34
+ npx @wonderwhy-er/desktop-commander@latest remote
35
+ npx @wonderwhy-er/desktop-commander@latest remote --debug
36
+ npx @wonderwhy-er/desktop-commander@latest remote --logout
37
+
38
+ Note:
39
+ --logout removes local credentials only. Revoke the device in the Remote MCP
40
+ dashboard if you also want to invalidate its server-side authorization.`);
17
41
  return;
18
42
  }
19
43
  if (process.argv.includes('--logout')) {
@@ -29,6 +53,7 @@ Options:
29
53
  }
30
54
  return;
31
55
  }
56
+ printRemoteHeader();
32
57
  // --persist-session is kept as an accepted no-op so existing invocations
33
58
  // and docs keep working; --no-persist-session opts back out.
34
59
  const persistSession = !process.argv.includes('--no-persist-session');
@@ -44,6 +69,10 @@ Options:
44
69
  console.debug = () => { };
45
70
  }
46
71
  console.debug('[DEBUG] Platform:', os.platform());
72
+ await captureRemote('remote_device_command_started', {
73
+ node_version: process.version,
74
+ persist_session: persistSession,
75
+ });
47
76
  // Start caffeinate on macOS (unless disabled)
48
77
  // Caffeinate will monitor this process and automatically exit when it terminates
49
78
  if (!disableNoSleep && os.platform() === 'darwin') {
@@ -11,6 +11,10 @@ export declare class DesktopCommanderIntegration {
11
11
  private isShuttingDown;
12
12
  private disconnectHandler;
13
13
  private reinitPromise;
14
+ /** Consecutive failed restarts; reset by a successful one. */
15
+ private restartAttempts;
16
+ /** Before this, ensureReady() refuses rather than spawning again. */
17
+ private nextRestartAt;
14
18
  /** True only while the local stdio child is actually reachable. */
15
19
  get ready(): boolean;
16
20
  /**
@@ -34,7 +38,15 @@ export declare class DesktopCommanderIntegration {
34
38
  * if the child is crashing on startup, each tool call fails with the real
35
39
  * reason instead of spinning respawns in the background.
36
40
  */
41
+ /** Same refusal ensureReady() makes up front, for an attempt already running. */
42
+ private abortIfShuttingDown;
37
43
  ensureReady(): Promise<void>;
44
+ /** One restart, with the pacing bookkeeping around it. */
45
+ private restartChild;
46
+ /** Drop an unusable child so `ready` is false and the next attempt rebuilds. */
47
+ private discardChild;
48
+ /** How long ensureReady() will refuse for. 0 when it will try immediately. */
49
+ get msUntilRestartAllowed(): number;
38
50
  resolveMcpConfig(): Promise<McpConfig | null>;
39
51
  callClientTool(toolName: string, args: any, metadata?: any): Promise<{
40
52
  [x: string]: unknown;
@@ -128,6 +140,14 @@ export declare class DesktopCommanderIntegration {
128
140
  } | undefined;
129
141
  } | undefined;
130
142
  }>;
143
+ /**
144
+ * Prove the child can serve a request, not merely that it completed the
145
+ * handshake. connect() only exchanges `initialize`, which says the process
146
+ * is up and speaks MCP - the same substitution issue #4 is about, one level
147
+ * down. Throws so initialize() can withhold readiness; listClientTools()
148
+ * keeps swallowing, because registerDevice() wants a tool list or nothing.
149
+ */
150
+ private verifyExecution;
131
151
  listClientTools(): Promise<{
132
152
  tools: {
133
153
  inputSchema: {
@@ -5,6 +5,20 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
5
5
  import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js';
6
6
  import { fileURLToPath } from 'url';
7
7
  import { captureRemote } from '../utils/capture.js';
8
+ // Restart pacing: grows with consecutive failures, caps, and jitters so a
9
+ // fleet-wide fault does not stampede.
10
+ //
11
+ // The cap is what a user waits after fixing whatever broke the child, so it is
12
+ // deliberately short. It can be: readiness now keeps an unusable device out of
13
+ // the server's selection, so no routed calls arrive to spawn anything, and the
14
+ // only thing asking for a restart is this connector's own recovery loop. The
15
+ // cost of the short cap is one short-lived spawn every few seconds while a
16
+ // child stays broken; the cost of a long one is a device that sits dead for
17
+ // most a minute after it could have come back.
18
+ const RESTART_BACKOFF_CAP_MS = 5000;
19
+ const restartBackoffMs = (attempt) =>
20
+ // Cap AFTER jitter, so the cap is the wait this comment claims it is.
21
+ Math.min(RESTART_BACKOFF_CAP_MS, 250 * 2 ** Math.min(attempt, 5) * (0.5 + Math.random()));
8
22
  const __filename = fileURLToPath(import.meta.url);
9
23
  const __dirname = path.dirname(__filename);
10
24
  export class DesktopCommanderIntegration {
@@ -15,6 +29,10 @@ export class DesktopCommanderIntegration {
15
29
  this.isShuttingDown = false;
16
30
  this.disconnectHandler = null;
17
31
  this.reinitPromise = null;
32
+ /** Consecutive failed restarts; reset by a successful one. */
33
+ this.restartAttempts = 0;
34
+ /** Before this, ensureReady() refuses rather than spawning again. */
35
+ this.nextRestartAt = 0;
18
36
  }
19
37
  /** True only while the local stdio child is actually reachable. */
20
38
  get ready() {
@@ -75,30 +93,54 @@ export class DesktopCommanderIntegration {
75
93
  });
76
94
  // Connect to Desktop Commander
77
95
  console.debug('[DEBUG] Connecting MCP client to transport');
96
+ // shutdown() sets the flag and tears down what exists; it cannot
97
+ // reach back into a restart already in flight. Without these
98
+ // checks that restart carries on past the teardown, connects a
99
+ // child nobody will close and sets `ready` behind it. The catch
100
+ // below discards whatever this attempt built.
101
+ this.abortIfShuttingDown();
78
102
  await this.mcpClient.connect(this.mcpTransport);
79
- this.isReady = true;
103
+ this.abortIfShuttingDown();
80
104
  // Supervise the local half. Without these, a child crash is silent:
81
105
  // the SDK clears its transport and every subsequent call throws
82
106
  // "Not connected" with nothing tying it back to the death.
83
- this.mcpTransport.onclose = () => this.handleLocalDisconnect('stdio transport closed');
84
- this.mcpTransport.onerror = (err) => this.handleLocalDisconnect(`stdio transport error: ${err?.message ?? String(err)}`);
107
+ //
108
+ // These MUST hang off the client, not the transport. connect() wraps
109
+ // transport.onclose/onerror with its own handlers and the SDK states
110
+ // that "The Protocol object assumes ownership of the Transport,
111
+ // replacing any callbacks that have already been set". Assigning to
112
+ // the transport here instead would drop the SDK's wrapper, and with
113
+ // it Protocol._onclose() — the only place a pending response is
114
+ // rejected with ConnectionClosed. The call in flight when the child
115
+ // died would then hang for the SDK's 60s default request timeout
116
+ // before the user heard anything.
117
+ this.mcpClient.onclose = () => this.handleLocalDisconnect('stdio transport closed');
118
+ // Diagnostics only. Protocol.onerror is raised for eleven non-fatal
119
+ // conditions that say nothing about the child's health — a response
120
+ // for an unknown message id, an unknown progress token, a failed
121
+ // cancellation send, an uncaught notification-handler error — and
122
+ // treating any of those as death takes a working device offline and
123
+ // respawns a live child. Real death arrives through onclose, which
124
+ // only fires once the transport has actually closed.
125
+ this.mcpClient.onerror = (err) => console.error(` - ⚠️ Local Desktop Commander MCP error: ${err?.message ?? String(err)}`);
126
+ // Ready means the child has served a request, not that it
127
+ // completed the handshake — one definition, whichever path
128
+ // started the child, so no caller has to remember a second
129
+ // step to get the stronger meaning. A failure here lands in
130
+ // the catch below and leaves nothing half-built behind.
131
+ await this.verifyExecution();
132
+ this.abortIfShuttingDown();
133
+ this.isReady = true;
85
134
  console.log(' - 🔌 Connected to Desktop Commander MCP');
86
135
  console.debug('[DEBUG] Desktop Commander MCP connection successful');
87
136
  }
88
137
  catch (error) {
89
- console.error(' - ❌ Failed to connect to Desktop Commander MCP:', error);
90
- console.debug('[DEBUG] MCP connection error:', error);
91
- // Leave no half-built client behind, or ensureReady() would treat the
92
- // corpse as live on the next attempt.
93
- this.isReady = false;
94
- this.mcpClient = null;
95
- if (this.mcpTransport) {
96
- try {
97
- await this.mcpTransport.close();
98
- }
99
- catch { /* already dead — nothing to salvage */ }
100
- this.mcpTransport = null;
101
- }
138
+ console.error(' - ❌ Failed to start Desktop Commander MCP:', error);
139
+ console.debug('[DEBUG] MCP startup error:', error);
140
+ // Leave no half-built child behind, or ensureReady() would treat
141
+ // the corpse as live on the next attempt. Covers a child that
142
+ // connected and then failed verification, too.
143
+ await this.discardChild();
102
144
  await captureRemote('desktop_integration_init_failed', { error });
103
145
  throw error;
104
146
  }
@@ -109,6 +151,12 @@ export class DesktopCommanderIntegration {
109
151
  * if the child is crashing on startup, each tool call fails with the real
110
152
  * reason instead of spinning respawns in the background.
111
153
  */
154
+ /** Same refusal ensureReady() makes up front, for an attempt already running. */
155
+ abortIfShuttingDown() {
156
+ if (this.isShuttingDown) {
157
+ throw new Error('Desktop Commander integration is shutting down');
158
+ }
159
+ }
112
160
  async ensureReady() {
113
161
  if (this.ready)
114
162
  return;
@@ -116,14 +164,58 @@ export class DesktopCommanderIntegration {
116
164
  throw new Error('Desktop Commander integration is shutting down');
117
165
  }
118
166
  if (!this.reinitPromise) {
167
+ // A child that crashes on start would otherwise be respawned once
168
+ // per routed tool call. Refuse inside the window instead, so the
169
+ // caller gets the real reason and the machine is left alone.
170
+ const waitMs = this.nextRestartAt - Date.now();
171
+ if (waitMs > 0) {
172
+ throw new Error(`Local Desktop Commander MCP failed to start ${this.restartAttempts} time(s); ` +
173
+ `next attempt in ${Math.ceil(waitMs / 1000)}s`);
174
+ }
119
175
  console.log(' - ♻️ Local Desktop Commander MCP is not running; restarting it...');
120
- this.reinitPromise = this.initialize().finally(() => {
176
+ this.reinitPromise = this.restartChild().finally(() => {
121
177
  this.reinitPromise = null;
122
178
  });
123
179
  }
124
180
  // Concurrent calls share the single in-flight restart.
125
181
  await this.reinitPromise;
126
182
  }
183
+ /** One restart, with the pacing bookkeeping around it. */
184
+ async restartChild() {
185
+ try {
186
+ // initialize() resolves only once the child has served a request,
187
+ // so there is nothing further to prove here.
188
+ await this.initialize();
189
+ this.restartAttempts = 0;
190
+ this.nextRestartAt = 0;
191
+ }
192
+ catch (error) {
193
+ await this.discardChild();
194
+ this.restartAttempts++;
195
+ this.nextRestartAt = Date.now() + restartBackoffMs(this.restartAttempts);
196
+ throw error;
197
+ }
198
+ }
199
+ /** Drop an unusable child so `ready` is false and the next attempt rebuilds. */
200
+ async discardChild() {
201
+ this.isReady = false;
202
+ const client = this.mcpClient;
203
+ const transport = this.mcpTransport;
204
+ this.mcpClient = null;
205
+ this.mcpTransport = null;
206
+ try {
207
+ await client?.close();
208
+ }
209
+ catch { /* already dead */ }
210
+ try {
211
+ await transport?.close();
212
+ }
213
+ catch { /* already dead */ }
214
+ }
215
+ /** How long ensureReady() will refuse for. 0 when it will try immediately. */
216
+ get msUntilRestartAllowed() {
217
+ return Math.max(0, this.nextRestartAt - Date.now());
218
+ }
127
219
  async resolveMcpConfig() {
128
220
  console.debug('[DEBUG] Resolving MCP config...');
129
221
  // Option 1: Development/Local Build
@@ -199,6 +291,18 @@ export class DesktopCommanderIntegration {
199
291
  throw error;
200
292
  }
201
293
  }
294
+ /**
295
+ * Prove the child can serve a request, not merely that it completed the
296
+ * handshake. connect() only exchanges `initialize`, which says the process
297
+ * is up and speaks MCP - the same substitution issue #4 is about, one level
298
+ * down. Throws so initialize() can withhold readiness; listClientTools()
299
+ * keeps swallowing, because registerDevice() wants a tool list or nothing.
300
+ */
301
+ async verifyExecution() {
302
+ if (!this.mcpClient)
303
+ throw new Error('Local Desktop Commander MCP is not connected');
304
+ await this.mcpClient.listTools();
305
+ }
202
306
  async listClientTools() {
203
307
  if (!this.mcpClient)
204
308
  return { tools: [] };
@@ -1,11 +1,23 @@
1
+ import open from 'open';
2
+ import { captureRemote } from '../utils/capture.js';
1
3
  interface AuthSession {
2
4
  access_token: string;
3
5
  refresh_token: string | null;
4
6
  device_id?: string;
5
7
  }
8
+ type DeviceAuthenticatorDeps = {
9
+ fetch?: typeof fetch;
10
+ open?: typeof open;
11
+ capture?: typeof captureRemote;
12
+ monotonicNow?: () => number;
13
+ };
6
14
  export declare class DeviceAuthenticator {
7
15
  private baseServerUrl;
8
- constructor(baseServerUrl: string);
16
+ private fetchFn;
17
+ private openFn;
18
+ private captureFn;
19
+ private monotonicNow;
20
+ constructor(baseServerUrl: string, deps?: DeviceAuthenticatorDeps);
9
21
  authenticate(deviceId?: string): Promise<AuthSession>;
10
22
  private generatePKCE;
11
23
  private requestDeviceCode;
@@ -2,13 +2,18 @@ import open from 'open';
2
2
  import os from 'os';
3
3
  import crypto from 'crypto';
4
4
  import { captureRemote } from '../utils/capture.js';
5
+ import { observeServerDate } from './remote-channel.js';
5
6
  const CLIENT_ID = 'mcp-device';
6
7
  export class DeviceAuthenticator {
7
- constructor(baseServerUrl) {
8
+ constructor(baseServerUrl, deps = {}) {
8
9
  this.baseServerUrl = baseServerUrl;
10
+ this.fetchFn = deps.fetch ?? fetch;
11
+ this.openFn = deps.open ?? open;
12
+ this.captureFn = deps.capture ?? captureRemote;
13
+ this.monotonicNow = deps.monotonicNow ?? performance.now.bind(performance);
9
14
  }
10
15
  async authenticate(deviceId) {
11
- console.log('🔐 Starting device authorization flow...\n');
16
+ console.log('🔐 Connecting this computer...\n');
12
17
  // Generate PKCE
13
18
  const pkce = this.generatePKCE();
14
19
  // Step 1: Request device code
@@ -17,7 +22,7 @@ export class DeviceAuthenticator {
17
22
  this.displayUserInstructions(deviceAuth);
18
23
  // Step 3: Poll for authorization
19
24
  const tokens = await this.pollForAuthorization(deviceAuth, pkce.verifier);
20
- console.log(' - ✅ Authorization successful!\n');
25
+ console.log('✅ Device verified\n');
21
26
  return tokens;
22
27
  }
23
28
  generatePKCE() {
@@ -27,38 +32,66 @@ export class DeviceAuthenticator {
27
32
  }
28
33
  async requestDeviceCode(codeChallenge, deviceId) {
29
34
  console.log(' - 📡 Requesting device code...');
30
- const response = await fetch(`${this.baseServerUrl}/device/start`, {
31
- method: 'POST',
32
- headers: { 'Content-Type': 'application/json' },
33
- body: JSON.stringify({
34
- client_id: CLIENT_ID,
35
- scope: 'mcp:tools',
36
- device_name: os.hostname(),
37
- device_type: 'mcp',
38
- device_id: deviceId,
39
- code_challenge: codeChallenge,
40
- code_challenge_method: 'S256',
41
- }),
35
+ const startedAt = this.monotonicNow();
36
+ await this.captureFn('remote_device_auth_request_started', {
37
+ has_existing_device_id: Boolean(deviceId),
42
38
  });
39
+ let response;
40
+ try {
41
+ response = await this.fetchFn(`${this.baseServerUrl}/device/start`, {
42
+ method: 'POST',
43
+ headers: { 'Content-Type': 'application/json' },
44
+ body: JSON.stringify({
45
+ client_id: CLIENT_ID,
46
+ scope: 'mcp:tools',
47
+ device_name: os.hostname(),
48
+ device_type: 'mcp',
49
+ device_id: deviceId,
50
+ code_challenge: codeChallenge,
51
+ code_challenge_method: 'S256',
52
+ }),
53
+ });
54
+ }
55
+ catch (error) {
56
+ await this.captureFn('remote_device_auth_request_network_error', {
57
+ error,
58
+ duration_ms: Math.round(this.monotonicNow() - startedAt),
59
+ has_existing_device_id: Boolean(deviceId),
60
+ });
61
+ throw error;
62
+ }
63
+ observeServerDate(response.headers.get('date'));
43
64
  if (!response.ok) {
44
65
  const error = await response.json().catch(() => ({ error: 'Unknown error' }));
45
66
  const errorMessage = error.error_description || 'Failed to start device flow';
46
- await captureRemote('remote_device_auth_request_failed', { error: errorMessage });
67
+ await this.captureFn('remote_device_auth_request_failed', {
68
+ error: errorMessage,
69
+ duration_ms: Math.round(this.monotonicNow() - startedAt),
70
+ has_existing_device_id: Boolean(deviceId),
71
+ });
47
72
  throw new Error(errorMessage);
48
73
  }
49
74
  const data = await response.json();
75
+ await this.captureFn('remote_device_auth_code_received', {
76
+ duration_ms: Math.round(this.monotonicNow() - startedAt),
77
+ has_existing_device_id: Boolean(deviceId),
78
+ });
50
79
  console.log(' - ✅ Device code received\n');
51
80
  return data;
52
81
  }
53
82
  displayUserInstructions(deviceAuth) {
54
83
  console.log('📋 Please complete authentication:\n');
55
- console.log(' 1. Open this URL in your browser:');
56
- console.log(` ${deviceAuth.verification_uri}\n`);
57
- console.log(' 2. Enter this code when prompted:');
84
+ console.log(' 1. Verify this device in your browser:');
85
+ console.log(` ${deviceAuth.verification_uri_complete}\n`);
86
+ console.log(' 2. Make sure the code matches:');
58
87
  console.log(` ${deviceAuth.user_code}\n`);
59
88
  console.log(` Code expires in ${Math.floor(deviceAuth.expires_in / 60)} minutes.\n`);
60
- // Try to open browser automatically
61
- open(deviceAuth.verification_uri_complete).catch(() => {
89
+ // Try to open browser automatically. This only confirms the OS accepted
90
+ // the launch request; page-load completion is measured by the web event.
91
+ void this.openFn(deviceAuth.verification_uri_complete)
92
+ .then(() => this.captureFn('remote_device_browser_launch_succeeded'))
93
+ .catch(async (error) => {
94
+ await this.captureFn('remote_device_browser_launch_failed', { error });
62
95
  console.log(' - Could not open browser automatically.');
63
96
  console.log(` - Please visit: ${deviceAuth.verification_uri}\n`);
64
97
  });
@@ -72,8 +105,16 @@ export class DeviceAuthenticator {
72
105
  attempt++;
73
106
  // Wait before polling
74
107
  await this.sleep(interval);
108
+ // Only transport problems are retried here. The request, and a body
109
+ // we cannot read, are the transient part; an answer the server
110
+ // actually gave (access_denied, expired_token, ...) is final. Before,
111
+ // the terminal throw sat inside this try and its own catch swallowed
112
+ // it, so a denied or expired code kept the terminal on "Waiting for
113
+ // authorization" until the whole code lifetime ran out.
114
+ let response;
115
+ let data;
75
116
  try {
76
- const response = await fetch(`${this.baseServerUrl}/device/poll`, {
117
+ response = await this.fetchFn(`${this.baseServerUrl}/device/poll`, {
77
118
  method: 'POST',
78
119
  headers: { 'Content-Type': 'application/json' },
79
120
  body: JSON.stringify({
@@ -82,43 +123,47 @@ export class DeviceAuthenticator {
82
123
  code_verifier: codeVerifier,
83
124
  }),
84
125
  });
85
- // Parse response body exactly once
86
- const data = await response.json().catch(() => ({ error: 'unknown' }));
87
- // Successful authentication
88
- if (response.ok && data.access_token) {
89
- return {
90
- device_id: data.device_id,
91
- access_token: data.access_token,
92
- refresh_token: data.refresh_token || null,
93
- };
94
- }
95
- // Check error type
96
- if (data.error === 'authorization_pending') {
97
- // Still waiting - continue polling
98
- continue;
99
- }
100
- if (data.error === 'slow_down') {
101
- // Server requested slower polling
102
- await this.sleep(interval);
103
- continue;
104
- }
105
- // Terminal error
106
- const errorMessage = data.error_description || data.error || 'Authorization failed';
107
- await captureRemote('remote_device_auth_failed', { error: errorMessage });
108
- throw new Error(errorMessage);
126
+ // The response that delivers the session states the server's
127
+ // time; correct the clock before that session is used.
128
+ observeServerDate(response.headers.get('date'));
129
+ // Parse response body exactly once. null = not a JSON answer
130
+ // (e.g. a proxy's HTML 502), which is not a verdict on the code.
131
+ data = await response.json().catch(() => null);
109
132
  }
110
133
  catch (fetchError) {
111
- // Network error - retry unless we're out of attempts
112
134
  if (attempt >= maxAttempts) {
113
- await captureRemote('remote_device_auth_network_error', { error: fetchError });
135
+ await this.captureFn('remote_device_auth_network_error', { error: fetchError });
114
136
  throw fetchError;
115
137
  }
116
- // Continue polling on network errors
117
138
  continue;
118
139
  }
140
+ // Successful authentication
141
+ if (response.ok && data?.access_token) {
142
+ return {
143
+ device_id: data.device_id,
144
+ access_token: data.access_token,
145
+ refresh_token: data.refresh_token || null,
146
+ };
147
+ }
148
+ // Server-side trouble or an unreadable body: transient, keep polling.
149
+ if (!data || response.status >= 500) {
150
+ continue;
151
+ }
152
+ if (data.error === 'authorization_pending') {
153
+ continue;
154
+ }
155
+ if (data.error === 'slow_down') {
156
+ // Server requested slower polling
157
+ await this.sleep(interval);
158
+ continue;
159
+ }
160
+ // Terminal error: the server answered, and the answer is no.
161
+ const errorMessage = data.error_description || data.error || 'Authorization failed';
162
+ await this.captureFn('remote_device_auth_failed', { error: errorMessage, error_code: data.error ?? null });
163
+ throw new Error(errorMessage);
119
164
  }
120
165
  const timeoutError = 'Authorization timeout - user did not authorize within the time limit';
121
- await captureRemote('remote_device_auth_timeout', { error: timeoutError });
166
+ await this.captureFn('remote_device_auth_timeout', { error: timeoutError });
122
167
  throw new Error(timeoutError);
123
168
  }
124
169
  sleep(ms) {
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { type AuthSession } from './remote-channel.js';
2
3
  export interface MCPDeviceOptions {
3
4
  persistSession?: boolean;
4
5
  }
@@ -11,6 +12,13 @@ export declare class MCPDevice {
11
12
  private configPath;
12
13
  private persistSession;
13
14
  private desktop;
15
+ /**
16
+ * Serialises config writes. Rotations are 45 minutes apart in normal
17
+ * running, but a save that stalls must not land after a newer one and
18
+ * persist a token that is already spent. Shutdown awaits this to drain
19
+ * whatever is still in flight.
20
+ */
21
+ private configWriteChain;
14
22
  /** Call ids already handled by THIS process (insertion-ordered, bounded). */
15
23
  private seenCallIds;
16
24
  constructor(options?: MCPDeviceOptions);
@@ -19,7 +27,12 @@ export declare class MCPDevice {
19
27
  private findPersistedDeviceWithRetry;
20
28
  loadPersistedConfig(): Promise<any>;
21
29
  clearPersistedConfig(): Promise<void>;
22
- savePersistedConfig(): Promise<void>;
30
+ /**
31
+ * Queue a config write. Returns the queued write, so a caller that must not
32
+ * outlive it - shutdown() - can await it.
33
+ */
34
+ savePersistedConfig(rotated?: AuthSession): Promise<void>;
35
+ private writePersistedConfig;
23
36
  fetchSupabaseConfig(): Promise<{
24
37
  supabaseUrl: any;
25
38
  anonKey: any;