@wonderwhy-er/desktop-commander 0.2.51 → 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 +14 -24
- package/dist/npm-scripts/remote.js +30 -1
- package/dist/remote-device/desktop-commander-integration.d.ts +20 -0
- package/dist/remote-device/desktop-commander-integration.js +102 -15
- package/dist/remote-device/device-authenticator.d.ts +13 -1
- package/dist/remote-device/device-authenticator.js +87 -47
- package/dist/remote-device/device.js +107 -21
- package/dist/remote-device/remote-channel.d.ts +52 -3
- package/dist/remote-device/remote-channel.js +263 -41
- package/dist/server.js +33 -81
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
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
|
|
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
|
-
|
|
468
|
+
On first run, complete browser authentication, then connect your AI at **[mcp.desktopcommander.app](https://mcp.desktopcommander.app)**.
|
|
476
469
|
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
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
|
|
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
|
|
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,8 +93,14 @@ 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.
|
|
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.
|
|
@@ -99,23 +123,24 @@ export class DesktopCommanderIntegration {
|
|
|
99
123
|
// respawns a live child. Real death arrives through onclose, which
|
|
100
124
|
// only fires once the transport has actually closed.
|
|
101
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;
|
|
102
134
|
console.log(' - 🔌 Connected to Desktop Commander MCP');
|
|
103
135
|
console.debug('[DEBUG] Desktop Commander MCP connection successful');
|
|
104
136
|
}
|
|
105
137
|
catch (error) {
|
|
106
|
-
console.error(' - ❌ Failed to
|
|
107
|
-
console.debug('[DEBUG] MCP
|
|
108
|
-
// Leave no half-built
|
|
109
|
-
// corpse as live on the next attempt.
|
|
110
|
-
|
|
111
|
-
this.
|
|
112
|
-
if (this.mcpTransport) {
|
|
113
|
-
try {
|
|
114
|
-
await this.mcpTransport.close();
|
|
115
|
-
}
|
|
116
|
-
catch { /* already dead — nothing to salvage */ }
|
|
117
|
-
this.mcpTransport = null;
|
|
118
|
-
}
|
|
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();
|
|
119
144
|
await captureRemote('desktop_integration_init_failed', { error });
|
|
120
145
|
throw error;
|
|
121
146
|
}
|
|
@@ -126,6 +151,12 @@ export class DesktopCommanderIntegration {
|
|
|
126
151
|
* if the child is crashing on startup, each tool call fails with the real
|
|
127
152
|
* reason instead of spinning respawns in the background.
|
|
128
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
|
+
}
|
|
129
160
|
async ensureReady() {
|
|
130
161
|
if (this.ready)
|
|
131
162
|
return;
|
|
@@ -133,14 +164,58 @@ export class DesktopCommanderIntegration {
|
|
|
133
164
|
throw new Error('Desktop Commander integration is shutting down');
|
|
134
165
|
}
|
|
135
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
|
+
}
|
|
136
175
|
console.log(' - ♻️ Local Desktop Commander MCP is not running; restarting it...');
|
|
137
|
-
this.reinitPromise = this.
|
|
176
|
+
this.reinitPromise = this.restartChild().finally(() => {
|
|
138
177
|
this.reinitPromise = null;
|
|
139
178
|
});
|
|
140
179
|
}
|
|
141
180
|
// Concurrent calls share the single in-flight restart.
|
|
142
181
|
await this.reinitPromise;
|
|
143
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
|
+
}
|
|
144
219
|
async resolveMcpConfig() {
|
|
145
220
|
console.debug('[DEBUG] Resolving MCP config...');
|
|
146
221
|
// Option 1: Development/Local Build
|
|
@@ -216,6 +291,18 @@ export class DesktopCommanderIntegration {
|
|
|
216
291
|
throw error;
|
|
217
292
|
}
|
|
218
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
|
+
}
|
|
219
306
|
async listClientTools() {
|
|
220
307
|
if (!this.mcpClient)
|
|
221
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
|
-
|
|
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;
|
|
@@ -5,11 +5,15 @@ import { captureRemote } from '../utils/capture.js';
|
|
|
5
5
|
import { observeServerDate } from './remote-channel.js';
|
|
6
6
|
const CLIENT_ID = 'mcp-device';
|
|
7
7
|
export class DeviceAuthenticator {
|
|
8
|
-
constructor(baseServerUrl) {
|
|
8
|
+
constructor(baseServerUrl, deps = {}) {
|
|
9
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);
|
|
10
14
|
}
|
|
11
15
|
async authenticate(deviceId) {
|
|
12
|
-
console.log('🔐
|
|
16
|
+
console.log('🔐 Connecting this computer...\n');
|
|
13
17
|
// Generate PKCE
|
|
14
18
|
const pkce = this.generatePKCE();
|
|
15
19
|
// Step 1: Request device code
|
|
@@ -18,7 +22,7 @@ export class DeviceAuthenticator {
|
|
|
18
22
|
this.displayUserInstructions(deviceAuth);
|
|
19
23
|
// Step 3: Poll for authorization
|
|
20
24
|
const tokens = await this.pollForAuthorization(deviceAuth, pkce.verifier);
|
|
21
|
-
console.log('
|
|
25
|
+
console.log('✅ Device verified\n');
|
|
22
26
|
return tokens;
|
|
23
27
|
}
|
|
24
28
|
generatePKCE() {
|
|
@@ -28,27 +32,50 @@ export class DeviceAuthenticator {
|
|
|
28
32
|
}
|
|
29
33
|
async requestDeviceCode(codeChallenge, deviceId) {
|
|
30
34
|
console.log(' - 📡 Requesting device code...');
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
body: JSON.stringify({
|
|
35
|
-
client_id: CLIENT_ID,
|
|
36
|
-
scope: 'mcp:tools',
|
|
37
|
-
device_name: os.hostname(),
|
|
38
|
-
device_type: 'mcp',
|
|
39
|
-
device_id: deviceId,
|
|
40
|
-
code_challenge: codeChallenge,
|
|
41
|
-
code_challenge_method: 'S256',
|
|
42
|
-
}),
|
|
35
|
+
const startedAt = this.monotonicNow();
|
|
36
|
+
await this.captureFn('remote_device_auth_request_started', {
|
|
37
|
+
has_existing_device_id: Boolean(deviceId),
|
|
43
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
|
+
}
|
|
44
63
|
observeServerDate(response.headers.get('date'));
|
|
45
64
|
if (!response.ok) {
|
|
46
65
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
47
66
|
const errorMessage = error.error_description || 'Failed to start device flow';
|
|
48
|
-
await
|
|
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
|
+
});
|
|
49
72
|
throw new Error(errorMessage);
|
|
50
73
|
}
|
|
51
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
|
+
});
|
|
52
79
|
console.log(' - ✅ Device code received\n');
|
|
53
80
|
return data;
|
|
54
81
|
}
|
|
@@ -59,8 +86,12 @@ export class DeviceAuthenticator {
|
|
|
59
86
|
console.log(' 2. Make sure the code matches:');
|
|
60
87
|
console.log(` ${deviceAuth.user_code}\n`);
|
|
61
88
|
console.log(` Code expires in ${Math.floor(deviceAuth.expires_in / 60)} minutes.\n`);
|
|
62
|
-
// Try to open browser automatically
|
|
63
|
-
|
|
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 });
|
|
64
95
|
console.log(' - Could not open browser automatically.');
|
|
65
96
|
console.log(` - Please visit: ${deviceAuth.verification_uri}\n`);
|
|
66
97
|
});
|
|
@@ -74,8 +105,16 @@ export class DeviceAuthenticator {
|
|
|
74
105
|
attempt++;
|
|
75
106
|
// Wait before polling
|
|
76
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;
|
|
77
116
|
try {
|
|
78
|
-
|
|
117
|
+
response = await this.fetchFn(`${this.baseServerUrl}/device/poll`, {
|
|
79
118
|
method: 'POST',
|
|
80
119
|
headers: { 'Content-Type': 'application/json' },
|
|
81
120
|
body: JSON.stringify({
|
|
@@ -87,43 +126,44 @@ export class DeviceAuthenticator {
|
|
|
87
126
|
// The response that delivers the session states the server's
|
|
88
127
|
// time; correct the clock before that session is used.
|
|
89
128
|
observeServerDate(response.headers.get('date'));
|
|
90
|
-
// Parse response body exactly once
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
if (response.ok && data.access_token) {
|
|
94
|
-
return {
|
|
95
|
-
device_id: data.device_id,
|
|
96
|
-
access_token: data.access_token,
|
|
97
|
-
refresh_token: data.refresh_token || null,
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
// Check error type
|
|
101
|
-
if (data.error === 'authorization_pending') {
|
|
102
|
-
// Still waiting - continue polling
|
|
103
|
-
continue;
|
|
104
|
-
}
|
|
105
|
-
if (data.error === 'slow_down') {
|
|
106
|
-
// Server requested slower polling
|
|
107
|
-
await this.sleep(interval);
|
|
108
|
-
continue;
|
|
109
|
-
}
|
|
110
|
-
// Terminal error
|
|
111
|
-
const errorMessage = data.error_description || data.error || 'Authorization failed';
|
|
112
|
-
await captureRemote('remote_device_auth_failed', { error: errorMessage });
|
|
113
|
-
throw new Error(errorMessage);
|
|
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);
|
|
114
132
|
}
|
|
115
133
|
catch (fetchError) {
|
|
116
|
-
// Network error - retry unless we're out of attempts
|
|
117
134
|
if (attempt >= maxAttempts) {
|
|
118
|
-
await
|
|
135
|
+
await this.captureFn('remote_device_auth_network_error', { error: fetchError });
|
|
119
136
|
throw fetchError;
|
|
120
137
|
}
|
|
121
|
-
// Continue polling on network errors
|
|
122
138
|
continue;
|
|
123
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);
|
|
124
164
|
}
|
|
125
165
|
const timeoutError = 'Authorization timeout - user did not authorize within the time limit';
|
|
126
|
-
await
|
|
166
|
+
await this.captureFn('remote_device_auth_timeout', { error: timeoutError });
|
|
127
167
|
throw new Error(timeoutError);
|
|
128
168
|
}
|
|
129
169
|
sleep(ms) {
|