@juexibobi/private-desktop-mcp 0.3.6 → 0.5.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/bin/proxy.mjs CHANGED
@@ -1,53 +1,181 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { getProxyForUrl } from "proxy-from-env";
3
3
 
4
- const proxyEnvironmentKeys=[
5
- "https_proxy","http_proxy","all_proxy",
6
- "npm_config_https_proxy","npm_config_http_proxy","npm_config_proxy"
4
+ const proxyEnvironmentKeys = [
5
+ "https_proxy",
6
+ "http_proxy",
7
+ "all_proxy",
8
+ "npm_config_https_proxy",
9
+ "npm_config_http_proxy",
10
+ "npm_config_proxy"
7
11
  ];
8
- export function hasEnvironmentProxy(env=process.env){
9
- const names=new Set(Object.keys(env).filter(k=>proxyEnvironmentKeys.includes(k.toLowerCase())));
10
- return [...names].some(k=>String(env[k]??"").trim().length>0);
12
+
13
+ export function hasEnvironmentProxy(env = process.env) {
14
+ const names = new Set(Object.keys(env).filter((k) => proxyEnvironmentKeys.includes(k.toLowerCase())));
15
+ return [...names].some((k) => String(env[k] ?? "").trim().length > 0);
16
+ }
17
+
18
+ export function normalizeProxy(value, source) {
19
+ const raw = String(value || "").trim();
20
+ if (!raw) return { mode: "direct", source };
21
+ const uri = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : "http://" + raw;
22
+ let parsed;
23
+ try {
24
+ parsed = new URL(uri);
25
+ } catch {
26
+ return { mode: "unsupported", source, reason: "Invalid proxy address" };
27
+ }
28
+ if (!["http:", "https:"].includes(parsed.protocol)) {
29
+ return {
30
+ mode: "unsupported",
31
+ source,
32
+ reason: "Proxy protocol " + parsed.protocol + " is not HTTP CONNECT; use an HTTP/Mixed proxy port"
33
+ };
34
+ }
35
+ if (!parsed.hostname) return { mode: "unsupported", source, reason: "Missing proxy hostname" };
36
+ return {
37
+ mode: "proxy",
38
+ source,
39
+ url: parsed.href,
40
+ description:
41
+ parsed.protocol.slice(0, -1).toUpperCase() +
42
+ " CONNECT via " +
43
+ parsed.hostname +
44
+ ":" +
45
+ (parsed.port || (["https:"].includes(parsed.protocol) ? "443" : "80"))
46
+ };
47
+ }
48
+
49
+ export function queryWindowsProxy(url, { spawn = spawnSync } = {}) {
50
+ // Windows WinINET system proxy, including static proxy, exclusions, PAC and WPAD.
51
+ // Use the Windows user's configuration instead of guessing a Clash/v2rayN port.
52
+ const target = String(url).replace(/'/g, "''");
53
+ const script =
54
+ "$ErrorActionPreference='Stop';" +
55
+ "$u=[Uri]'" +
56
+ target +
57
+ "';" +
58
+ "$p=[System.Net.WebRequest]::GetSystemWebProxy();" +
59
+ "if($p.IsBypassed($u)){[Console]::Out.Write('DIRECT')}" +
60
+ "else{$v=$p.GetProxy($u);if($v.AbsoluteUri -eq $u.AbsoluteUri){[Console]::Out.Write('DIRECT')}else{[Console]::Out.Write($v.AbsoluteUri)}}";
61
+ const result = spawn("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], {
62
+ encoding: "utf8",
63
+ timeout: 6000,
64
+ windowsHide: true,
65
+ maxBuffer: 4096
66
+ });
67
+ if (result.error || result.status !== 0) {
68
+ return {
69
+ mode: "unavailable",
70
+ source: "windows",
71
+ reason: result.error?.code === "ETIMEDOUT" ? "Windows proxy lookup timed out" : "Windows proxy lookup failed"
72
+ };
73
+ }
74
+ const output = String(result.stdout || "").trim();
75
+ if (output === "DIRECT") return { mode: "direct", source: "windows" };
76
+ if (!output) return { mode: "unavailable", source: "windows", reason: "Windows proxy lookup returned no result" };
77
+ return normalizeProxy(output, "windows");
78
+ }
79
+
80
+ function hostMatchesException(hostname, pattern) {
81
+ const host = String(hostname || "").toLowerCase();
82
+ const pat = String(pattern || "").trim().toLowerCase();
83
+ if (!host || !pat) return false;
84
+ if (pat === "*") return true;
85
+ if (pat.startsWith("*.")) {
86
+ const suffix = pat.slice(1); // ".local"
87
+ return host.endsWith(suffix) && host.length > suffix.length;
88
+ }
89
+ if (pat.startsWith(".")) {
90
+ return host === pat.slice(1) || host.endsWith(pat);
91
+ }
92
+ return host === pat;
11
93
  }
12
- export function normalizeProxy(value,source){
13
- const raw=String(value||"").trim();
14
- if(!raw)return {mode:"direct",source};
15
- const uri=/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)?raw:"http://"+raw;
16
- let parsed;
17
- try{parsed=new URL(uri)}catch{return {mode:"unsupported",source,reason:"Invalid proxy address"}}
18
- if(!["http:","https:"].includes(parsed.protocol)){
19
- return {mode:"unsupported",source,reason:"Proxy protocol "+parsed.protocol+" is not HTTP CONNECT; use an HTTP/Mixed proxy port"};
20
- }
21
- if(!parsed.hostname)return {mode:"unsupported",source,reason:"Missing proxy hostname"};
22
- return {mode:"proxy",source,url:parsed.href,description:parsed.protocol.slice(0,-1).toUpperCase()+" CONNECT via "+parsed.hostname+":"+(parsed.port||(["https:"].includes(parsed.protocol)?"443":"80"))};
94
+
95
+ export function parseMacOsScutilProxy(output, url) {
96
+ const text = String(output || "");
97
+ if (!text.trim()) return { mode: "direct", source: "macos" };
98
+
99
+ const fields = new Map();
100
+ const exceptions = [];
101
+ let inExceptions = false;
102
+
103
+ for (const rawLine of text.split(/\r?\n/)) {
104
+ const line = rawLine.trim();
105
+ if (/^ExceptionsList\s*:\s*<array>/.test(line)) {
106
+ inExceptions = true;
107
+ continue;
108
+ }
109
+ if (inExceptions) {
110
+ if (line === "}") {
111
+ inExceptions = false;
112
+ continue;
113
+ }
114
+ const m = line.match(/^\d+\s*:\s*(.+)$/);
115
+ if (m) exceptions.push(m[1].trim());
116
+ continue;
117
+ }
118
+ const kv = line.match(/^([A-Za-z0-9_]+)\s*:\s*(.+)$/);
119
+ if (kv) fields.set(kv[1], kv[2].trim());
120
+ }
121
+
122
+ let parsedTarget;
123
+ try {
124
+ parsedTarget = new URL(url);
125
+ } catch {
126
+ parsedTarget = null;
127
+ }
128
+ if (parsedTarget && exceptions.some((pat) => hostMatchesException(parsedTarget.hostname, pat))) {
129
+ return { mode: "direct", source: "macos" };
130
+ }
131
+
132
+ const wantHttps = parsedTarget ? ["https:", "wss:"].includes(parsedTarget.protocol) : true;
133
+ if (wantHttps && fields.get("HTTPSEnable") === "1" && fields.get("HTTPSProxy")) {
134
+ const port = fields.get("HTTPSPort") ? `:${fields.get("HTTPSPort")}` : "";
135
+ return normalizeProxy(`http://${fields.get("HTTPSProxy")}${port}`, "macos");
136
+ }
137
+ if (fields.get("HTTPEnable") === "1" && fields.get("HTTPProxy")) {
138
+ const port = fields.get("HTTPPort") ? `:${fields.get("HTTPPort")}` : "";
139
+ return normalizeProxy(`http://${fields.get("HTTPProxy")}${port}`, "macos");
140
+ }
141
+ if (fields.get("SOCKSEnable") === "1" && fields.get("SOCKSProxy")) {
142
+ const port = fields.get("SOCKSPort") ? `:${fields.get("SOCKSPort")}` : "";
143
+ return normalizeProxy(`socks5://${fields.get("SOCKSProxy")}${port}`, "macos");
144
+ }
145
+ return { mode: "direct", source: "macos" };
23
146
  }
24
- export function queryWindowsProxy(url,{spawn=spawnSync}={}){
25
- // Windows WinINET system proxy, including static proxy, exclusions, PAC and WPAD.
26
- // Use the Windows user's configuration instead of guessing a Clash/v2rayN port.
27
- const target=String(url).replace(/'/g,"''");
28
- const script="$ErrorActionPreference='Stop';"
29
- +"$u=[Uri]'"+target+"';"
30
- +"$p=[System.Net.WebRequest]::GetSystemWebProxy();"
31
- +"if($p.IsBypassed($u)){[Console]::Out.Write('DIRECT')}"
32
- +"else{$v=$p.GetProxy($u);if($v.AbsoluteUri -eq $u.AbsoluteUri){[Console]::Out.Write('DIRECT')}else{[Console]::Out.Write($v.AbsoluteUri)}}";
33
- const result=spawn("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-Command",script],{
34
- encoding:"utf8",timeout:6000,windowsHide:true,maxBuffer:4096
35
- });
36
- if(result.error||result.status!==0){
37
- return {mode:"unavailable",source:"windows",reason:result.error?.code==="ETIMEDOUT"?"Windows proxy lookup timed out":"Windows proxy lookup failed"};
38
- }
39
- const output=String(result.stdout||"").trim();
40
- if(output==="DIRECT")return {mode:"direct",source:"windows"};
41
- if(!output)return {mode:"unavailable",source:"windows",reason:"Windows proxy lookup returned no result"};
42
- return normalizeProxy(output,"windows");
147
+
148
+ export function queryMacOsProxy(url, { spawn = spawnSync } = {}) {
149
+ const result = spawn("scutil", ["--proxy"], {
150
+ encoding: "utf8",
151
+ timeout: 4000,
152
+ maxBuffer: 16384
153
+ });
154
+ if (result.error || result.status !== 0) {
155
+ return {
156
+ mode: "unavailable",
157
+ source: "macos",
158
+ reason: result.error?.code === "ETIMEDOUT" ? "macOS proxy lookup timed out" : "macOS proxy lookup failed"
159
+ };
160
+ }
161
+ return parseMacOsScutilProxy(result.stdout, url);
43
162
  }
44
- export function resolveProxyForUrl(url,{
45
- platform=process.platform,env=process.env,envLookup=getProxyForUrl,windowsLookup=queryWindowsProxy
46
- }={}){
47
- if(hasEnvironmentProxy(env)){
48
- const chosen=envLookup(url);
49
- return chosen?normalizeProxy(chosen,"environment"):{mode:"direct",source:"environment-bypass"};
50
- }
51
- if(platform==="win32")return windowsLookup(url);
52
- return {mode:"direct",source:"system"};
163
+
164
+ export function resolveProxyForUrl(
165
+ url,
166
+ {
167
+ platform = process.platform,
168
+ env = process.env,
169
+ envLookup = getProxyForUrl,
170
+ windowsLookup = queryWindowsProxy,
171
+ macosLookup = queryMacOsProxy
172
+ } = {}
173
+ ) {
174
+ if (hasEnvironmentProxy(env)) {
175
+ const chosen = envLookup(url);
176
+ return chosen ? normalizeProxy(chosen, "environment") : { mode: "direct", source: "environment-bypass" };
177
+ }
178
+ if (platform === "win32") return windowsLookup(url);
179
+ if (platform === "darwin") return macosLookup(url);
180
+ return { mode: "direct", source: "system" };
53
181
  }
@@ -0,0 +1,110 @@
1
+ # Install & Connect Private Desktop MCP with an Agent
2
+
3
+ Last reviewed: 2026-11-25
4
+
5
+ This guide is written for both people and AI coding agents (Claude Code, Codex, Cursor, VS Code Copilot, Gemini CLI, OpenClaw, Windsurf, and Antigravity).
6
+
7
+ It separates two roles that can run on the same computer or across different computers:
8
+
9
+ 1. **Connecting an AI Client (Remote Streamable HTTP MCP)** — registering the Cloudflare Access-protected `/mcp` endpoint in the user's AI client or installing the repository plugin/skill.
10
+ 2. **Running the Device Connector (`private-desktop-mcp connect`)** — running the outbound WebSocket agent on each Windows, macOS, or Linux desktop the user wants to control.
11
+
12
+ ---
13
+
14
+ ## Prompt to Paste into Your Coding Agent
15
+
16
+ ```text
17
+ Install and configure Private Desktop MCP for me using the official instructions at:
18
+ https://github.com/KFCheems/private-desktop-mcp/blob/main/docs/agent-install.md
19
+
20
+ Before changing anything:
21
+ 1. Identify my operating system and AI client(s), and run `npx --yes @juexibobi/private-desktop-mcp@latest doctor --json`.
22
+ 2. Ask whether I want to:
23
+ (a) register the remote MCP server in my AI client,
24
+ (b) pair/connect this computer as a controllable desktop device (and whether to use `--readonly` or `--allow-dir`), or
25
+ (c) both.
26
+ 3. Preview the exact configuration file changes using `setup-client <client> --dry-run --json` and wait for my confirmation before writing files.
27
+ 4. Never ask me to paste Cloudflare tokens, Access cookies, or `device.json` secrets into chat.
28
+ ```
29
+
30
+ ---
31
+
32
+ ## Instructions for the Installing Agent
33
+
34
+ ### Step 1: Preflight Check (Read-Only)
35
+
36
+ Run the built-in JSON doctor to verify Node.js (`>=20.18.1`), effective system proxy (Windows WinINET / macOS `scutil` / environment), relay reachability, and local pairing state:
37
+
38
+ ```bash
39
+ npx --yes @juexibobi/private-desktop-mcp@latest doctor --json
40
+ ```
41
+
42
+ ### Step 2: Register the Remote MCP Server in the AI Client
43
+
44
+ #### Option A: Native Plugin / Extension Install (Recommended where supported)
45
+
46
+ - **Claude Code**:
47
+ ```bash
48
+ claude mcp add --transport http private-desktop https://private-desktop-device-relay.ljx2043979076.workers.dev/mcp
49
+ ```
50
+ Or install from the plugin marketplace:
51
+ ```text
52
+ /plugin marketplace add KFCheems/private-desktop-mcp
53
+ /plugin install private-desktop-mcp@private-desktop-mcp
54
+ ```
55
+ - **Codex**:
56
+ ```bash
57
+ codex plugin marketplace add KFCheems/private-desktop-mcp
58
+ ```
59
+ - **Gemini CLI**:
60
+ ```bash
61
+ gemini extensions install https://github.com/KFCheems/private-desktop-mcp
62
+ ```
63
+ - **Antigravity**:
64
+ ```bash
65
+ agy plugin install https://github.com/KFCheems/private-desktop-mcp
66
+ ```
67
+ - **Agent Skill only** (`npx skills`):
68
+ ```bash
69
+ npx --yes skills add KFCheems/private-desktop-mcp
70
+ ```
71
+
72
+ #### Option B: Automated Non-Destructive Config Merge (`setup-client`)
73
+
74
+ For `claude-code`, `claude-desktop`, `cursor`, `vscode`, `codex`, `gemini`, or `windsurf`:
75
+
76
+ 1. **Preview first (`--dry-run --json`)**:
77
+ ```bash
78
+ npx --yes @juexibobi/private-desktop-mcp@latest setup-client <client> --dry-run --json
79
+ ```
80
+ *(If the user self-hosts their own Cloudflare Worker, append `--relay https://<their-worker-domain>`.)*
81
+ 2. Show the user `path`, `action`, and `preview`, and wait for confirmation.
82
+ 3. **Apply**:
83
+ ```bash
84
+ npx --yes @juexibobi/private-desktop-mcp@latest setup-client <client> --json
85
+ ```
86
+
87
+ ### Step 3: Pair & Start the Device Connector (When Controlling the Local Machine)
88
+
89
+ 1. Choose the appropriate safety profile with the user:
90
+ - **Read-only + Workspace Jail (Safest default for exploration/debugging)**:
91
+ ```bash
92
+ npx --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --readonly --allow-dir "<workspace_path>" --json
93
+ ```
94
+ - **Full Desktop Commander access (Filesystem + Shell + Process management)**:
95
+ ```bash
96
+ npx --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --json
97
+ ```
98
+ 2. If `"paired": false`, the connector emits a single JSON line:
99
+ ```json
100
+ {"event":"pairing_required","deviceName":"...","code":"XXXXXXXXXX","approvalUrl":"https://.../admin/devices","pairId":"...","expiresIn":3600}
101
+ ```
102
+ Display the **`code`** and **`approvalUrl`** to the user and ask them to sign into Cloudflare Access in their browser and click **批准设备 (Approve)**.
103
+ 3. Once approved, the connector saves `device.json` locally (`0600`) and maintains the outbound WebSocket connection until stopped with `Ctrl+C`.
104
+
105
+ ### Step 4: Verify Multi-Device MCP Connectivity
106
+
107
+ Once connected, verify from the MCP client with a harmless read-only call:
108
+
109
+ 1. Call `relay_list_devices` (or read resource `relay://devices`) to confirm the machine appears as `online: true`.
110
+ 2. Call `relay_ping_device` to verify round-trip latency and `gatewayReady: true`.
package/gateway.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import crypto from "node:crypto";
1
2
  import path from "node:path";
2
3
  import fs from "node:fs";
3
4
  import { fileURLToPath } from "node:url";
@@ -7,38 +8,235 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
7
8
  import { Server } from "@modelcontextprotocol/server";
8
9
  import { proxyServer, startHTTPServer } from "mcp-proxy";
9
10
 
10
- const root = path.dirname(fileURLToPath(import.meta.url));
11
- if (process.platform === "win32" && !process.env.PUPPETEER_EXECUTABLE_PATH) {
12
- const edge = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe";
13
- if (fs.existsSync(edge)) process.env.PUPPETEER_EXECUTABLE_PATH = edge;
11
+ const __filename = fileURLToPath(import.meta.url);
12
+
13
+ export function isAllowedLocalHost(hostHeader, port) {
14
+ const host = String(hostHeader || "").trim().toLowerCase();
15
+ if (!host) return false;
16
+ const p = String(port);
17
+ return host === `127.0.0.1:${p}` || host === `localhost:${p}` || host === `[::1]:${p}`;
18
+ }
19
+
20
+ export function constantTimeTokenEqual(actual, expected) {
21
+ const a = Buffer.from(String(actual || ""), "utf8");
22
+ const b = Buffer.from(String(expected || ""), "utf8");
23
+ return a.length === b.length && a.length > 0 && crypto.timingSafeEqual(a, b);
24
+ }
25
+
26
+ /**
27
+ * Local MCP HTTP security guard:
28
+ * - Blocks DNS rebinding via strict Host header validation.
29
+ * - Blocks browser CSRF by rejecting any Origin header.
30
+ * - Enforces ephemeral per-launch Bearer token when MCP_LOCAL_TOKEN is set.
31
+ */
32
+ export function createLocalAuthGuard({ port, localToken = "" }) {
33
+ return async (req) => {
34
+ if (!isAllowedLocalHost(req.headers?.host, port)) {
35
+ throw new Response("Forbidden: invalid Host header", { status: 403 });
36
+ }
37
+ if (req.headers?.origin) {
38
+ throw new Response("Forbidden: browser Origin not allowed on local gateway", { status: 403 });
39
+ }
40
+ if (localToken) {
41
+ const auth = String(req.headers?.authorization || "");
42
+ const prefix = "Bearer ";
43
+ if (!auth.startsWith(prefix) || !constantTimeTokenEqual(auth.slice(prefix.length), localToken)) {
44
+ return { authenticated: false, error: "Unauthorized: invalid local gateway token" };
45
+ }
46
+ }
47
+ return { authenticated: true };
48
+ };
49
+ }
50
+
51
+ export function loadExtraServersConfig(configPath) {
52
+ if (!configPath) return [];
53
+ const resolved = path.resolve(configPath);
54
+ const raw = JSON.parse(fs.readFileSync(resolved, "utf8"));
55
+ const map = raw?.mcpServers || raw?.servers || {};
56
+ const entries = [];
57
+ for (const [rawName, cfg] of Object.entries(map)) {
58
+ const namespace = String(rawName)
59
+ .replace(/[^a-zA-Z0-9_-]/g, "_")
60
+ .slice(0, 32);
61
+ if (!namespace || !cfg || typeof cfg.command !== "string" || !cfg.command.trim()) continue;
62
+ entries.push({
63
+ namespace,
64
+ command: cfg.command.trim(),
65
+ args: Array.isArray(cfg.args) ? cfg.args.map(String) : [],
66
+ env: cfg.env && typeof cfg.env === "object" ? Object.fromEntries(Object.entries(cfg.env).map(([k, v]) => [k, String(v)])) : undefined,
67
+ cwd: typeof cfg.cwd === "string" ? cfg.cwd : undefined
68
+ });
69
+ }
70
+ return entries;
71
+ }
72
+
73
+ export function createAggregatedClient(primary, extras = []) {
74
+ if (!extras.length) return primary;
75
+ const byNamespace = new Map(extras.map((e) => [e.namespace, e.client]));
76
+
77
+ return new Proxy(primary, {
78
+ get(target, prop, receiver) {
79
+ if (prop === "listTools") {
80
+ return async (params, options) => {
81
+ const base = await target.listTools(params, options);
82
+ const merged = [...(base.tools || [])];
83
+ for (const [ns, client] of byNamespace) {
84
+ try {
85
+ const extraRes = await client.listTools(undefined, options);
86
+ for (const tool of extraRes.tools || []) {
87
+ merged.push({
88
+ ...tool,
89
+ name: `${ns}__${tool.name}`,
90
+ description: `[${ns}] ${tool.description || ""}`.trim()
91
+ });
92
+ }
93
+ } catch (e) {
94
+ console.error(`Failed to list tools from extra MCP server "${ns}":`, e?.message || e);
95
+ }
96
+ }
97
+ return { ...base, tools: merged };
98
+ };
99
+ }
100
+ if (prop === "callTool") {
101
+ return async (params, options) => {
102
+ const name = String(params?.name || "");
103
+ const sep = name.indexOf("__");
104
+ if (sep > 0) {
105
+ const ns = name.slice(0, sep);
106
+ const rawTool = name.slice(sep + 2);
107
+ const client = byNamespace.get(ns);
108
+ if (client) {
109
+ return client.callTool({ ...params, name: rawTool }, options);
110
+ }
111
+ }
112
+ return target.callTool(params, options);
113
+ };
114
+ }
115
+ const value = Reflect.get(target, prop, target);
116
+ return typeof value === "function" ? value.bind(target) : value;
117
+ }
118
+ });
14
119
  }
15
- const require = createRequire(import.meta.url);
16
- const pkgFile = require.resolve("@wonderwhy-er/desktop-commander/package.json");
17
- const exe = path.join(path.dirname(pkgFile), "dist", "index.js");
18
- const transport = new StdioClientTransport({ command: process.execPath, args: [exe], stderr: "inherit" });
19
- const upstream = new Client({ name: "private-mcp-gateway", version: "0.1.0" }, { capabilities: {} });
20
- await upstream.connect(transport);
21
- const serverCapabilities = upstream.getServerCapabilities();
22
- const serverInfo = upstream.getServerVersion();
23
- const tools = await upstream.listTools();
24
- const port = Number(process.env.MCP_PORT || 8717);
25
- if (!Number.isInteger(port) || port < 1024 || port > 65535) throw Error("Invalid MCP_PORT");
26
- console.log("MCP upstream ready:", serverInfo?.name, "tools:", tools.tools?.length);
27
- const { close } = await startHTTPServer({
28
- host: "127.0.0.1",
29
- port,
30
- streamEndpoint: "/mcp",
31
- sseEndpoint: null,
32
- cors: false,
33
- maxBodySize: 1048576,
34
- eventStoreMaxEvents: 100,
35
- createServer: async () => {
36
- const downstream = new Server(serverInfo, { capabilities: serverCapabilities });
37
- await proxyServer({ client: upstream, server: downstream, serverCapabilities });
38
- return downstream;
120
+
121
+ async function main() {
122
+ if (process.platform === "win32" && !process.env.PUPPETEER_EXECUTABLE_PATH) {
123
+ const edge = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe";
124
+ if (fs.existsSync(edge)) process.env.PUPPETEER_EXECUTABLE_PATH = edge;
39
125
  }
40
- });
41
- console.log(`Local MCP gateway listening at http://127.0.0.1:${port}/mcp`);
42
- const stop = async () => { await close(); await upstream.close(); process.exit(0); };
43
- process.on("SIGINT", stop);
44
- process.on("SIGTERM", stop);
126
+
127
+ const port = Number(process.env.MCP_PORT || 8717);
128
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) throw Error("Invalid MCP_PORT");
129
+ const localToken = String(process.env.MCP_LOCAL_TOKEN || "");
130
+
131
+ const require = createRequire(import.meta.url);
132
+ const pkgFile = require.resolve("@wonderwhy-er/desktop-commander/package.json");
133
+ const exe = path.join(path.dirname(pkgFile), "dist", "index.js");
134
+ const transport = new StdioClientTransport({
135
+ command: process.execPath,
136
+ args: [exe, "--no-onboarding"],
137
+ stderr: "inherit"
138
+ });
139
+ const primary = new Client({ name: "private-mcp-gateway", version: "0.4.0" }, { capabilities: {} });
140
+ await primary.connect(transport);
141
+
142
+ const extras = [];
143
+ if (process.env.PCC_MCP_CONFIG) {
144
+ const configs = loadExtraServersConfig(process.env.PCC_MCP_CONFIG);
145
+ for (const cfg of configs) {
146
+ try {
147
+ const extraTransport = new StdioClientTransport({
148
+ command: cfg.command,
149
+ args: cfg.args,
150
+ env: cfg.env ? { ...process.env, ...cfg.env } : undefined,
151
+ cwd: cfg.cwd,
152
+ stderr: "inherit"
153
+ });
154
+ const extraClient = new Client({ name: `private-mcp-gateway-${cfg.namespace}`, version: "0.4.0" }, { capabilities: {} });
155
+ await extraClient.connect(extraTransport);
156
+ extras.push({ namespace: cfg.namespace, client: extraClient });
157
+ console.log("Attached extra MCP server:", cfg.namespace);
158
+ } catch (e) {
159
+ console.error(`Skipping extra MCP server "${cfg.namespace}":`, e?.message || e);
160
+ }
161
+ }
162
+ }
163
+
164
+ const upstream = createAggregatedClient(primary, extras);
165
+ const serverCapabilities = primary.getServerCapabilities();
166
+ const serverInfo = primary.getServerVersion();
167
+ const tools = await upstream.listTools();
168
+
169
+ console.log(
170
+ "MCP upstream ready:",
171
+ serverInfo?.name,
172
+ "tools:",
173
+ tools.tools?.length,
174
+ "extraServers:",
175
+ extras.length,
176
+ "localAuth:",
177
+ localToken ? "bearer+host" : "host-only"
178
+ );
179
+
180
+ const localGuard = createLocalAuthGuard({ port, localToken });
181
+ const { close } = await startHTTPServer({
182
+ host: "127.0.0.1",
183
+ port,
184
+ streamEndpoint: "/mcp",
185
+ sseEndpoint: null,
186
+ cors: false,
187
+ maxBodySize: 1048576,
188
+ eventStoreMaxEvents: 100,
189
+ authenticate: localGuard,
190
+ onUnhandledRequest: async (req, res) => {
191
+ if (req.method === "GET" && req.url === "/healthz") {
192
+ try {
193
+ const verdict = await localGuard(req);
194
+ if (!verdict?.authenticated) {
195
+ res.writeHead(401, { "content-type": "application/json" }).end('{"error":"Unauthorized"}');
196
+ return;
197
+ }
198
+ res
199
+ .writeHead(200, { "content-type": "application/json", "cache-control": "no-store" })
200
+ .end(JSON.stringify({ ok: true, tools: tools.tools?.length || 0, extraServers: extras.length }));
201
+ return;
202
+ } catch (err) {
203
+ const status = err instanceof Response ? err.status : 403;
204
+ res.writeHead(status, { "content-type": "application/json" }).end('{"error":"Forbidden"}');
205
+ return;
206
+ }
207
+ }
208
+ res.writeHead(404).end();
209
+ },
210
+ createServer: async () => {
211
+ const downstream = new Server(serverInfo, { capabilities: serverCapabilities });
212
+ await proxyServer({ client: upstream, server: downstream, serverCapabilities });
213
+ return downstream;
214
+ }
215
+ });
216
+
217
+ console.log(`Local MCP gateway listening at http://127.0.0.1:${port}/mcp`);
218
+
219
+ const stop = async () => {
220
+ try {
221
+ await close();
222
+ } catch {}
223
+ for (const extra of extras) {
224
+ try {
225
+ await extra.client.close();
226
+ } catch {}
227
+ }
228
+ try {
229
+ await primary.close();
230
+ } catch {}
231
+ process.exit(0);
232
+ };
233
+ process.on("SIGINT", stop);
234
+ process.on("SIGTERM", stop);
235
+ }
236
+
237
+ if (process.argv[1] && path.resolve(process.argv[1]) === __filename) {
238
+ main().catch((err) => {
239
+ console.error("Local MCP gateway fatal error:", err?.message || err);
240
+ process.exit(1);
241
+ });
242
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juexibobi/private-desktop-mcp",
3
- "version": "0.3.6",
3
+ "version": "0.5.0",
4
4
  "description": "Private multi-device Desktop Commander MCP connector for Cloudflare Workers with paired WebSocket relays",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -15,7 +15,12 @@
15
15
  "bin/activity.mjs",
16
16
  "bin/proxy.mjs",
17
17
  "bin/logging.mjs",
18
+ "bin/policy.mjs",
19
+ "bin/client-setup.mjs",
18
20
  "gateway.mjs",
21
+ "skills/private-desktop-mcp/SKILL.md",
22
+ "docs/agent-install.md",
23
+ "AGENTS.md",
19
24
  "README.md",
20
25
  "LICENSE"
21
26
  ],
@@ -25,16 +30,16 @@
25
30
  },
26
31
  "homepage": "https://github.com/KFCheems/private-desktop-mcp",
27
32
  "scripts": {
28
- "test": "node --check bin/cli.mjs && node --check gateway.mjs && node --test tests/*.test.mjs"
33
+ "test": "node --check bin/cli.mjs && node --check bin/policy.mjs && node --check bin/client-setup.mjs && node --check bin/proxy.mjs && node --check gateway.mjs && node --check worker/index.mjs && node --check worker/auth.mjs && node --test tests/*.test.mjs"
29
34
  },
30
35
  "dependencies": {
31
- "@wonderwhy-er/desktop-commander": "0.2.52",
32
- "mcp-proxy": "6.7.19",
33
- "ws": "8.18.3",
34
- "undici": "7.30.0",
36
+ "@modelcontextprotocol/client": "2.3.1",
37
+ "@modelcontextprotocol/server": "2.3.1",
38
+ "@wonderwhy-er/desktop-commander": "0.3.4",
35
39
  "https-proxy-agent": "9.1.0",
40
+ "mcp-proxy": "6.7.19",
36
41
  "proxy-from-env": "2.1.0",
37
- "@modelcontextprotocol/client": "2.3.1",
38
- "@modelcontextprotocol/server": "2.3.1"
42
+ "undici": "7.30.0",
43
+ "ws": "8.18.3"
39
44
  }
40
45
  }