@juexibobi/private-desktop-mcp 0.4.0 → 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/AGENTS.md ADDED
@@ -0,0 +1,116 @@
1
+ # AGENTS.md — Guide for AI Agents Operating and Maintaining Private Desktop MCP
2
+
3
+ This document defines the behavioral contracts for AI coding agents working with **Private Desktop MCP (`@juexibobi/private-desktop-mcp`)** in two roles:
4
+
5
+ 1. **Operator Mode (User Usage & Remote Multi-Device Orchestration)** — when a user asks you to connect their machine, configure an MCP client, inspect paired desktops, run commands across multiple computers, or manage read-only guardrails.
6
+ 2. **Developer Mode (Repository Maintenance & Evolution)** — when a user asks you to modify, test, release, or deploy the connector and Cloudflare Worker relay.
7
+
8
+ ---
9
+
10
+ ## Part 1: Operator Playbook (Using Private Desktop MCP for the User)
11
+
12
+ ### 1. Inspect Current State First (Machine-Readable Preflight)
13
+
14
+ Always run non-destructive JSON preflight checks before changing local configuration or starting a connector:
15
+
16
+ ```bash
17
+ npx --yes @juexibobi/private-desktop-mcp@latest doctor --json
18
+ npx --yes @juexibobi/private-desktop-mcp@latest status --json
19
+ npx --yes @juexibobi/private-desktop-mcp@latest report --json
20
+ ```
21
+
22
+ ### 2. Configuring an AI Client (`setup-client`)
23
+
24
+ Follow the preview-before-confirm contract in [docs/agent-install.md](docs/agent-install.md):
25
+
26
+ 1. Preview the exact configuration change with `--dry-run --json` first:
27
+ ```bash
28
+ npx --yes @juexibobi/private-desktop-mcp@latest setup-client <client> --dry-run --json
29
+ ```
30
+ Supported `<client>` values: `claude-code`, `claude-desktop`, `cursor`, `vscode`, `codex`, `gemini`, `windsurf`, `all`.
31
+ 2. Show the user the target file path and preview, wait for confirmation, then apply without `--dry-run`.
32
+
33
+ ### 3. Starting & Pairing a Device Connector
34
+
35
+ - **Default full mode**:
36
+ ```bash
37
+ npx --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --json
38
+ ```
39
+ - **Least-privilege read-only + directory jail mode (recommended for untrusted or exploratory sessions)**:
40
+ ```bash
41
+ npx --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --readonly --allow-dir <workspace_path> --json
42
+ ```
43
+ - **Aggregating additional local stdio MCP servers alongside Desktop Commander**:
44
+ ```bash
45
+ npx --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --servers ./client-configs/servers.example.json
46
+ ```
47
+ - When a machine is not paired yet, `--json` emits a structured event:
48
+ ```json
49
+ {"event":"pairing_required","deviceName":"...","code":"...","approvalUrl":"https://.../admin/devices","pairId":"...","expiresIn":3600}
50
+ ```
51
+ Present the `code` and `approvalUrl` to the user so they can approve it behind Cloudflare Access.
52
+
53
+ ### 4. Multi-Device Orchestration via MCP Tools, Resources & Prompts
54
+
55
+ When connected to the remote `/mcp` Streamable HTTP endpoint:
56
+
57
+ - **Resources (`resources/list`, `resources/read`)** — always available at the Cloudflare edge, even when 0 devices are online:
58
+ - `relay://devices`: Live inventory of paired devices, online state, OS/arch, read-only locks, and current selection.
59
+ - `relay://status`: Worker version, protocol features, and Access verification posture.
60
+ - `relay://audit`: Recent sanitized metadata-only audit log.
61
+ - **Built-in Edge Meta-Tools (`tools/call`)**:
62
+ - `relay_list_devices`: List all paired desktops and their live status.
63
+ - `relay_select_device`: Set the default active target desktop by `device_id` or `device_name`.
64
+ - `relay_ping_device`: Measure WebSocket RTT and verify local `gateway.mjs` health.
65
+ - `relay_set_device_policy`: Lock/unlock a device to read-only mode at the Cloudflare edge (`read_only: true|false`) or rename it (`new_name`).
66
+ - `relay_recent_activity`: Inspect sanitized audit entries (timestamps, actor, device, tool name, HTTP status, duration).
67
+ - **Per-Call Device Targeting (`_device`)**:
68
+ - Every upstream tool schema includes an optional `_device` string property. Pass `_device: "<device_name_or_id>"` on any tool call (e.g., `read_file`, `list_directory`, `start_process`) to route that single call to a specific machine without changing the global selection.
69
+ - **Self-Healing Tool Errors**:
70
+ - If a target device is offline or multiple devices are online without a selection, `tools/call` returns an `isError: true` structured payload containing `onlineDevices`, `selectedDeviceId`, and `nextActions`. Follow `nextActions` (e.g., call `relay_select_device` or pass `_device`) automatically.
71
+
72
+ ---
73
+
74
+ ## Part 2: Developer Playbook (Maintaining the Repository)
75
+
76
+ ### 1. Workspace Map
77
+
78
+ ```text
79
+ worker/
80
+ index.mjs Cloudflare Worker router & SQLite-backed DeviceHub Durable Object (MCP edge lifecycle, meta-tools, resources, prompts, WebSocket relay, audit log, admin UI)
81
+ auth.mjs Cryptographic Cloudflare Access RS256 JWT verifier (Web Crypto API, JWKS caching + key-rotation refresh)
82
+ bin/
83
+ cli.mjs Cross-platform device connector CLI (connect, status, doctor, report, setup-client, reset; --json, heartbeat watchdog, child gateway supervisor)
84
+ policy.mjs Local tool governance (--readonly, --allow-dir symlink-aware path jail, allow/deny lists, self-credential guard) & outbound DLP secret redaction
85
+ client-setup.mjs Non-destructive MCP client config generator/merger with --dry-run preview
86
+ proxy.mjs System proxy autodetection (Windows WinINET, macOS scutil, environment HTTPS_PROXY/NO_PROXY)
87
+ activity.mjs JSON-RPC/SSE parser, correlation IDs, and TRACE/DEBUG/LIVE terminal activity formatters
88
+ logging.mjs Terminal secret redaction and timestamped logging helpers
89
+ gateway.mjs Local loopback Streamable HTTP MCP gateway fronting @wonderwhy-er/desktop-commander + optional extra stdio MCP servers (Bearer + Host + Origin guard)
90
+ skills/
91
+ private-desktop-mcp/SKILL.md Bundled Agent Skill for coding agents
92
+ docs/
93
+ agent-install.md Canonical agent-driven setup & safety runbook
94
+ tests/
95
+ *.test.mjs Node.js built-in test runner suites covering worker auth, DeviceHub DO, gateway, policy/DLP, client setup, proxy, activity, and packaging
96
+ ```
97
+
98
+ ### 2. Boundary & Security Invariants
99
+
100
+ 1. **Zero secret leakage**: Never commit `device.json`, Cloudflare API keys/tokens (`cfk_`, `cfut_`, `cfat_`), Access cookies, or `.env` files. Never weaken `bin/policy.mjs` protection of the `PrivateDesktopMCP` credential directory.
101
+ 2. **Fail-closed edge authentication**: `worker/auth.mjs` must verify RS256 signatures, `iss`, `aud`, `exp`, and `nbf` against `CF_ACCESS_TEAM_DOMAIN` + `CF_ACCESS_AUD`.
102
+ 3. **Loopback gateway isolation**: `gateway.mjs` binds only to `127.0.0.1`, validates loopback `Host` headers (anti-DNS-rebinding), rejects browser `Origin` headers (anti-CSRF), and requires a per-launch 32-byte `MCP_LOCAL_TOKEN`.
103
+ 4. **Edge-always-alive MCP discovery**: `initialize`, `notifications/initialized`, `ping`, `server/discover`, `tools/list`, `resources/list`, `resources/read` (`relay://*`), `prompts/list`, and `prompts/get` must succeed at the Worker edge even when zero devices are connected.
104
+ 5. **Direct dependency declaration**: Every package imported by `bin/*.mjs` or `gateway.mjs` must be declared directly in `package.json` `dependencies` and listed in `package.json` `files` so `npx --install-strategy=nested` works on a clean machine.
105
+
106
+ ### 3. Verification & Release Workflow
107
+
108
+ Run the full verification gate before opening a PR or tagging a release:
109
+
110
+ ```bash
111
+ npm ci --ignore-scripts --no-audit --no-fund
112
+ npm test
113
+ npm pack --dry-run --json
114
+ ```
115
+
116
+ Releases are published automatically via GitHub Actions OIDC Trusted Publishing (`.github/workflows/release.yml`) when a `v*` tag matching `package.json` and `server.json` `version` is pushed.
package/README.md CHANGED
@@ -1,53 +1,69 @@
1
1
  # Private Desktop MCP
2
2
 
3
- Self-hosted multi-device [Model Context Protocol](https://modelcontextprotocol.io/) bridge for Desktop Commander (and optional additional local MCP servers) using Cloudflare Workers, SQLite-backed Durable Objects, and a one-command cross-platform connector.
3
+ Self-hosted, **Agent-Native** multi-device [Model Context Protocol](https://modelcontextprotocol.io/) bridge for Desktop Commander (and optional additional local MCP servers) using Cloudflare Workers, SQLite-backed Durable Objects, and a one-command cross-platform connector.
4
4
 
5
5
  **Transport:** Streamable HTTP (`POST` + `DELETE`, supporting both MCP `2025-*` and stateless `2026-07-28`) to AI clients; outgoing WebSocket with zero-cost hibernation heartbeat from each device to the relay.
6
6
 
7
- ## Public npm release
7
+ ## Quick Start: Install with Your Coding Agent
8
8
 
9
- ```powershell
10
- npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect
9
+ Paste the block below into Claude Code, Codex, Cursor, VS Code Copilot, Gemini CLI, OpenClaw, or Antigravity:
10
+
11
+ ```text
12
+ Install and configure Private Desktop MCP for me using the official instructions at:
13
+ https://github.com/KFCheems/private-desktop-mcp/blob/main/docs/agent-install.md
14
+ Before changing anything, identify my OS and AI client, run `npx --yes @juexibobi/private-desktop-mcp@latest doctor --json`, preview client config changes with `setup-client <client> --dry-run --json`, and wait for my confirmation.
11
15
  ```
12
16
 
13
- Each release gets its own immutable npm version. **Do not overwrite a fixed `.tgz` at a stable URL**: npm caching might start an old version.
17
+ Or install directly via native agent plugin / extension marketplaces:
14
18
 
15
- ## What's new in v0.4.0
19
+ ```bash
20
+ # Claude Code
21
+ /plugin marketplace add KFCheems/private-desktop-mcp
22
+ /plugin install private-desktop-mcp@private-desktop-mcp
23
+
24
+ # Codex
25
+ codex plugin marketplace add KFCheems/private-desktop-mcp
16
26
 
17
- ### Security & Governance
18
- - **Cryptographic Cloudflare Access JWT verification (`worker/auth.mjs`)**: Verifies RS256 signatures against `https://<team>.cloudflareaccess.com/cdn-cgi/access/certs` (with automatic `kid` key-rotation refresh), `aud`, `iss`, `exp`, and `nbf`. Fails closed if unconfigured (with an explicit temporary `ALLOW_UNVERIFIED_ACCESS_HEADER=true` migration opt-in).
19
- - **Hardened local gateway (`gateway.mjs`)**: Enforces per-launch ephemeral Bearer authentication (`MCP_LOCAL_TOKEN`), loopback `Host` validation (anti-DNS-rebinding), and browser `Origin` rejection (anti-CSRF).
20
- - **Local policy guardrails (`bin/policy.mjs`)**:
21
- - `--readonly` (or `PCC_READONLY=1`): allows read-only tools only and hides mutating tools from `tools/list`.
22
- - `--allow-dir <dir>` (repeatable, or `PCC_ALLOW_DIRS`): jails file tool paths to allowed directories (resolving symlinks and blocking `..` traversal).
23
- - `--allow-tools <csv>` / `--deny-tools <csv>`: explicit tool allowlist/denylist.
24
- - Always blocks remote access to the connector's own credential directory (`PrivateDesktopMCP/device.json`).
25
- - **Outbound DLP secret redaction (enabled by default, `--no-dlp` to opt out)**: Redacts PEM private keys, AWS/GitHub/OpenAI/Slack/Google tokens, and the active device/gateway bearer tokens from tool responses before sending them back to the cloud LLM.
26
- - **Edge read-only lock & emergency kill-switch**: Toggle per-device read-only lock or revoke all devices at once from `/admin/devices`.
27
- - **Removed hardcoded diagnostic file path**: `/relay/diagnostic` now permits read-only MCP introspection methods only.
27
+ # Gemini CLI
28
+ gemini extensions install https://github.com/KFCheems/private-desktop-mcp
28
29
 
29
- ### Reliability & Multi-Device Experience
30
- - **Zero-cost WebSocket hibernation heartbeat**: Durable Object `setWebSocketAutoResponse("ping", "pong")` paired with a 25s client heartbeat watchdog detects half-open sockets after OS sleep or Wi-Fi switches without waking hibernated DOs.
31
- - **Fixed reconnect backoff & jitter**: Resets exponential backoff once a session stays healthy and applies random jitter.
32
- - **Local gateway auto-recovery & fast-fail**: Supervises the local `gateway.mjs` child process, immediately fails in-flight calls if it exits unexpectedly, and restarts it automatically with bounded backoff.
33
- - **In-chat multi-device meta-tools**: Built-in `relay_list_devices`, `relay_select_device`, `relay_ping_device`, and `relay_recent_activity` tools let AI clients inspect online machines, switch targets, measure RTT latency, and view sanitized metadata audit logs without leaving chat. Individual tool calls can also target a specific machine via `_device` argument or `X-Target-Device` header.
34
- - **SQLite audit log & upgraded admin dashboard**: Uses Durable Object SQLite (`audit_logs`) to record metadata-only call history (never file contents or command output), plus device platform, CLI version, mode, rename, read-only toggle, and revoke-all controls.
35
- - **Streamable HTTP improvements**: Forwards `DELETE /mcp` session teardown and propagates client `AbortSignal` cancellations (`{ kind: "cancel" }`) all the way to the local gateway.
36
- - **Optional multi-MCP aggregation**: Pass `--servers <config.json>` (or `PCC_MCP_CONFIG`, see [client-configs/servers.example.json](client-configs/servers.example.json)) to aggregate additional local stdio MCP servers under `<server>__<tool>` namespaces alongside Desktop Commander.
37
- - **Upgraded Desktop Commander**: Bumped `@wonderwhy-er/desktop-commander` to `0.3.4` (security patches, Windows process-tree termination, lazy PDF/Office loading, explicit MCP tool annotations).
38
- - **Diagnostics & cross-platform proxy**: Added `doctor` and `report` CLI subcommands, macOS `scutil --proxy` autodetection alongside Windows WinINET, rotating user-private gateway logs (`PrivateDesktopMCP/logs/gateway.log`), and `--relay`/`--port`/`--name` overrides for clean self-hosting.
30
+ # Antigravity
31
+ agy plugin install https://github.com/KFCheems/private-desktop-mcp
39
32
 
40
- ## Terminal logging
33
+ # Agent Skill only (npx skills)
34
+ npx --yes skills add KFCheems/private-desktop-mcp
35
+ ```
41
36
 
42
- PCC uses **TRACE logging by default**. The normal `connect` command prints MCP call IDs, sanitized/truncated command and response previews, timings, connection details, and errors.
37
+ ## Public npm release (Device Connector)
43
38
 
44
- **Privacy:** TRACE can reveal sensitive file contents or command output locally in your terminal. Redaction is best effort; avoid sharing or recording the terminal. Use `--debug` for detailed metadata without content previews, or `--safe` for compact logs. The child gateway log is stored in the user-private `PrivateDesktopMCP/logs/gateway.log` directory and rotates automatically at 5 MB.
39
+ ```powershell
40
+ npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect
41
+ ```
45
42
 
46
- ## System proxy detection (Windows & macOS)
43
+ Each release gets its own immutable npm version. **Do not overwrite a fixed `.tgz` at a stable URL**: npm caching might start an old version.
47
44
 
48
- - **Windows**: Automatically uses the current user's effective WinINET system proxy (static HTTP/Mixed proxies, bypass rules, PAC/WPAD).
49
- - **macOS**: Automatically queries `scutil --proxy` (HTTPS/HTTP proxies and `ExceptionsList`).
50
- - **Environment override**: Explicit `HTTPS_PROXY`, `HTTP_PROXY`, or `ALL_PROXY` settings take precedence on all platforms (`NO_PROXY` respected). Supported proxy transport is HTTP/HTTPS CONNECT.
45
+ ## What's new in v0.5.0 (Agent-Native Edition)
46
+
47
+ ### Agent-Native MCP Protocol & Multi-Device Self-Healing
48
+ - **Edge-Always-Alive MCP Lifecycle**: `initialize`, `notifications/initialized`, `ping`, `server/discover`, `tools/list`, `resources/list`, `resources/read` (`relay://*`), `prompts/list`, and `prompts/get` succeed at the Cloudflare Worker edge **even when zero devices are online or multiple devices are online without a selection**, allowing agents to connect, inspect inventory, and guide the user instead of failing with HTTP transport errors.
49
+ - **Dynamic Server Instructions**: `initialize` / `server/discover` automatically injects live paired-device inventory (`online/offline`, OS, read-only status, selected target) and multi-device routing guidance into MCP `instructions`.
50
+ - **Schema-Native `_device` Parameter**: Every upstream tool in `tools/list` (`read_file`, `start_process`, `write_file`, etc.) has an optional `_device` string property injected into its `inputSchema.properties`, enabling schema-strict agents to target any paired computer per call without mutating global selection.
51
+ - **Built-in Edge Meta-Tools, Resources & Prompts**:
52
+ - **Tools**: `relay_list_devices`, `relay_select_device`, `relay_ping_device`, `relay_set_device_policy` (lock/unlock read-only mode or rename a device in chat), and `relay_recent_activity`.
53
+ - **Resources**: `relay://devices`, `relay://status`, and `relay://audit` (`application/json`).
54
+ - **Prompts**: `multi-device-triage` and `safe-remote-maintenance`.
55
+ - **Self-Healing Tool Errors**: When a `tools/call` targets an offline or ambiguous device, the relay returns a structured JSON-RPC `isError: true` result containing `errorCode`, `onlineDevices`, `selectedDeviceId`, and `nextActions` so the agent recovers autonomously.
56
+
57
+ ### Agent-Native CLI & Ecosystem Manifests
58
+ - **Universal `--json` Mode**: `doctor --json`, `status --json`, `report --json`, `reset --json`, `setup-client --json`, and `connect --json` (emits `{"event":"pairing_required",...}` and `{"event":"pairing_approved",...}`).
59
+ - **Automated Client Configurator (`setup-client`)**: Non-destructively merges the remote MCP endpoint into `claude-code`, `claude-desktop`, `cursor`, `vscode`, `codex`, `gemini`, `windsurf`, or `all`, with `--dry-run` preview support.
60
+ - **Cross-Platform Agent Manifests & Playbooks**: Ships [AGENTS.md](AGENTS.md), [CLAUDE.md](CLAUDE.md), [docs/agent-install.md](docs/agent-install.md), [skills/private-desktop-mcp/SKILL.md](skills/private-desktop-mcp/SKILL.md), `plugin.json`, `.claude-plugin/`, `gemini-extension.json`, and `.antigravity-plugin/`.
61
+
62
+ ### Security, Governance & Reliability (v0.4.0+)
63
+ - **Cryptographic Cloudflare Access JWT verification (`worker/auth.mjs`)**: Verifies RS256 signatures against `https://<team>.cloudflareaccess.com/cdn-cgi/access/certs` (with automatic `kid` key-rotation refresh), `aud`, `iss`, `exp`, and `nbf`.
64
+ - **Hardened local gateway (`gateway.mjs`)**: Per-launch ephemeral Bearer authentication (`MCP_LOCAL_TOKEN`), loopback `Host` validation (anti-DNS-rebinding), browser `Origin` rejection (anti-CSRF), and authenticated `/healthz`.
65
+ - **Local policy guardrails & Outbound DLP (`bin/policy.mjs`)**: `--readonly`, `--allow-dir <dir>` (symlink-aware path jail), `--allow-tools` / `--deny-tools`, self-credential protection (`PrivateDesktopMCP/device.json`), and automatic outbound secret redaction (PEM keys, AWS/GitHub/OpenAI/Slack/Google tokens, and active relay tokens).
66
+ - **Zero-cost WebSocket hibernation heartbeat & auto-recovery**: RFC 6455 `ws.ping()` + DO `setWebSocketAutoResponse("ping", "pong")`, jittered backoff reset, `DELETE /mcp` + client `AbortSignal` cancel propagation, and automatic local `gateway.mjs` crash recovery.
51
67
 
52
68
  ## CLI commands & flags
53
69
 
@@ -58,17 +74,18 @@ private-desktop-mcp connect
58
74
  # Safe read-only mode jailed to a workspace directory
59
75
  private-desktop-mcp connect --readonly --allow-dir C:\workspace
60
76
 
61
- # Connect to your own self-hosted Cloudflare Worker
62
- private-desktop-mcp connect --relay https://my-relay.example.workers.dev --name WorkPC
77
+ # Configure MCP clients (with --dry-run preview and --json for agents)
78
+ private-desktop-mcp setup-client claude-code --dry-run --json
79
+ private-desktop-mcp setup-client cursor
63
80
 
64
81
  # Aggregate extra local MCP servers alongside Desktop Commander
65
82
  private-desktop-mcp connect --servers ./client-configs/servers.example.json
66
83
 
67
- # Diagnostics & status
68
- private-desktop-mcp doctor
69
- private-desktop-mcp report
70
- private-desktop-mcp status
71
- private-desktop-mcp reset
84
+ # Machine-readable diagnostics & status
85
+ private-desktop-mcp doctor --json
86
+ private-desktop-mcp report --json
87
+ private-desktop-mcp status --json
88
+ private-desktop-mcp reset --json
72
89
  ```
73
90
 
74
91
  ## Current canonical endpoint
@@ -77,8 +94,6 @@ private-desktop-mcp reset
77
94
  https://private-desktop-device-relay.ljx2043979076.workers.dev/mcp
78
95
  ```
79
96
 
80
- Client configuration templates are available in `.mcp.json` and `client-configs/` (`vscode-mcp.json`, `mcpServers.json`, `cursor-mcp.json`, `codex.toml.example`).
81
-
82
97
  ## Pairing devices
83
98
 
84
99
  1. On a machine with Node.js 20.18.1+ run `private-desktop-mcp connect`.
@@ -92,25 +107,15 @@ Client configuration templates are available in `.mcp.json` and `client-configs/
92
107
 
93
108
  The Worker source is in `worker/index.mjs` and `worker/auth.mjs`. Infrastructure is described in `wrangler.toml`.
94
109
 
95
- 1. Configure a Cloudflare Access self-hosted application protecting `/mcp` and `/admin/*` with an Owner-only policy. Never protect `/relay/*` with Access (otherwise device WebSocket connections are blocked).
110
+ 1. Configure a Cloudflare Access self-hosted application protecting `/mcp` and `/admin/*` with an Owner-only policy. Never protect `/relay/*` with Access.
96
111
  2. Configure cryptographic Access JWT verification on the Worker before deploying:
97
112
 
98
113
  ```bash
99
114
  wrangler secret put CF_ACCESS_TEAM_DOMAIN # e.g. https://your-team.cloudflareaccess.com
100
115
  wrangler secret put CF_ACCESS_AUD # Access application AUD tag
101
- ```
102
-
103
- 3. For self-hosted custom domains/workers, optionally configure `SHARED_HOSTS`, `ALLOWED_OWNER_HOSTS`, `ALLOWED_RELAY_HOSTS`, and `PUBLIC_BASE_URL` (see comments in `wrangler.toml`).
104
- 4. Deploy with `wrangler deploy`.
105
-
106
- ## Running from source
107
-
108
- ```bash
109
- npm install
110
- npm test
111
- node bin/cli.mjs connect
116
+ wrangler deploy
112
117
  ```
113
118
 
114
119
  ## Security
115
120
 
116
- This tool provides remote filesystem and command-execution capabilities. Restrict Cloudflare Access to your own identity, configure `CF_ACCESS_TEAM_DOMAIN` + `CF_ACCESS_AUD`, approve only devices you control, and consider running `--readonly` or `--allow-dir` for day-to-day workflows. See [SECURITY.md](SECURITY.md).
121
+ This tool provides remote filesystem and command-execution capabilities. Restrict Cloudflare Access to your own identity, configure `CF_ACCESS_TEAM_DOMAIN` + `CF_ACCESS_AUD`, approve only devices you control, and consider running `--readonly` or `--allow-dir` for day-to-day workflows. See [SECURITY.md](SECURITY.md) and [AGENTS.md](AGENTS.md).
package/bin/cli.mjs CHANGED
@@ -28,13 +28,14 @@ import {
28
28
  redactOutboundResponse,
29
29
  buildPolicyBlockedResponse
30
30
  } from "./policy.mjs";
31
+ import { SUPPORTED_CLIENTS, configureMcpClient } from "./client-setup.mjs";
31
32
 
32
33
  const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
33
34
  const PKG_VERSION = (() => {
34
35
  try {
35
- return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version || "0.4.0";
36
+ return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version || "0.5.0";
36
37
  } catch {
37
- return "0.4.0";
38
+ return "0.5.0";
38
39
  }
39
40
  })();
40
41
 
@@ -44,12 +45,17 @@ const MAX_GATEWAY_LOG_BYTES = 5 * 1024 * 1024;
44
45
 
45
46
  function parseArgs(argv) {
46
47
  let command = "";
48
+ let subarg = "";
47
49
  let relay = process.env.PCC_RELAY_URL || DEFAULT_RELAY;
48
50
  let port = Number(process.env.MCP_PORT || 8717);
49
51
  let deviceName = os.hostname();
50
52
  let readonly = /^(1|true|yes)$/i.test(String(process.env.PCC_READONLY || ""));
51
53
  let dlp = !/^(0|false|no)$/i.test(String(process.env.PCC_DLP || "true"));
52
54
  let autoOpen = true;
55
+ let jsonOutput = false;
56
+ let dryRun = false;
57
+ let targetClient = "";
58
+ let clientConfigPath = "";
53
59
  let serversConfig = process.env.PCC_MCP_CONFIG || "";
54
60
  const allowDirs = String(process.env.PCC_ALLOW_DIRS || "")
55
61
  .split(path.delimiter)
@@ -68,6 +74,7 @@ function parseArgs(argv) {
68
74
  const arg = argv[i];
69
75
  if (!arg.startsWith("-")) {
70
76
  if (!command) command = arg;
77
+ else if (!subarg) subarg = arg;
71
78
  continue;
72
79
  }
73
80
  const eq = arg.indexOf("=");
@@ -82,6 +89,10 @@ function parseArgs(argv) {
82
89
  else if (flag === "--readonly") readonly = true;
83
90
  else if (flag === "--no-dlp") dlp = false;
84
91
  else if (flag === "--no-open") autoOpen = false;
92
+ else if (flag === "--json") jsonOutput = true;
93
+ else if (flag === "--dry-run") dryRun = true;
94
+ else if (flag === "--client") targetClient = nextVal();
95
+ else if (flag === "--config") clientConfigPath = nextVal();
85
96
  else if (flag === "--servers") serversConfig = nextVal();
86
97
  else if (flag === "--allow-dir") {
87
98
  const v = nextVal().trim();
@@ -95,12 +106,17 @@ function parseArgs(argv) {
95
106
 
96
107
  return {
97
108
  command: command || "connect",
109
+ subarg,
98
110
  relay: relay.replace(/\/+$/, ""),
99
111
  port,
100
112
  deviceName: deviceName || "Desktop",
101
113
  readonly,
102
114
  dlp,
103
115
  autoOpen,
116
+ json: jsonOutput,
117
+ dryRun,
118
+ targetClient: targetClient || subarg,
119
+ clientConfigPath,
104
120
  serversConfig,
105
121
  allowDirs,
106
122
  allowTools,
@@ -263,15 +279,28 @@ async function post(route, data) {
263
279
  async function pair() {
264
280
  const v = await post("/relay/pair/start", { name: opts.deviceName });
265
281
  logLine("info", "🔑 New device pairing requested");
266
- console.log(
267
- "\nNEW DEVICE: " +
268
- opts.deviceName +
269
- "\nPAIRING CODE: " +
270
- v.code +
271
- "\nPlease visit " +
272
- v.approvalUrl +
273
- " and approve the matching code.\nWaiting for approval (60 minutes)...\n"
274
- );
282
+ if (opts.json) {
283
+ console.log(
284
+ JSON.stringify({
285
+ event: "pairing_required",
286
+ deviceName: opts.deviceName,
287
+ code: v.code,
288
+ approvalUrl: v.approvalUrl,
289
+ pairId: v.pairId,
290
+ expiresIn: v.expiresIn || 3600
291
+ })
292
+ );
293
+ } else {
294
+ console.log(
295
+ "\nNEW DEVICE: " +
296
+ opts.deviceName +
297
+ "\nPAIRING CODE: " +
298
+ v.code +
299
+ "\nPlease visit " +
300
+ v.approvalUrl +
301
+ " and approve the matching code.\nWaiting for approval (60 minutes)...\n"
302
+ );
303
+ }
275
304
  tryOpenBrowser(v.approvalUrl);
276
305
  for (let i = 0; i < 720 && !stopping; i++) {
277
306
  await sleep(5000);
@@ -286,6 +315,9 @@ async function pair() {
286
315
  const credentials = { deviceId: r.deviceId, token: r.token };
287
316
  store(credentials);
288
317
  logLine("info", "✅ Device approved; credentials saved locally.");
318
+ if (opts.json) {
319
+ console.log(JSON.stringify({ event: "pairing_approved", deviceId: r.deviceId, deviceName: opts.deviceName }));
320
+ }
289
321
  return credentials;
290
322
  }
291
323
  }
@@ -716,22 +748,19 @@ async function connect(creds, { onHealthy } = {}) {
716
748
 
717
749
  async function runDoctor() {
718
750
  let healthy = true;
719
- console.log(`Private Desktop MCP Doctor (v${PKG_VERSION})`);
720
- console.log("─".repeat(48));
721
- console.log("Node.js:", process.version, `(${process.platform}/${process.arch})`);
722
- console.log("Relay URL:", opts.relay);
723
-
751
+ let proxyInfo = { mode: "unknown", source: "unknown" };
724
752
  let transport = {};
725
753
  try {
726
754
  const p = resolveProxyForUrl(opts.relay);
727
- console.log("Proxy:", p.mode === "proxy" ? `${p.source} (${p.description})` : `${p.mode} (${p.source}${p.reason ? ": " + p.reason : ""})`);
755
+ proxyInfo = { mode: p.mode, source: p.source, description: p.description || "", reason: p.reason || "" };
728
756
  if (p.mode === "unsupported") healthy = false;
729
757
  else if (p.mode === "proxy") transport = { dispatcher: new ProxyAgent(p.url) };
730
758
  } catch (e) {
731
- console.log("Proxy: error -", e.message);
759
+ proxyInfo = { mode: "error", source: "system", reason: e.message };
732
760
  healthy = false;
733
761
  }
734
762
 
763
+ let relayStatus = { ok: false };
735
764
  try {
736
765
  const t0 = Date.now();
737
766
  const res = await fetch(opts.relay + "/relay/status", {
@@ -739,22 +768,77 @@ async function runDoctor() {
739
768
  ...transport
740
769
  });
741
770
  const body = await res.json();
742
- console.log(
743
- `Relay Status: OK (HTTP ${res.status}, ${Date.now() - t0}ms, worker v${body.version || "unknown"}, features: ${(body.features || []).join(",") || "legacy"})`
744
- );
771
+ relayStatus = {
772
+ ok: res.ok && Boolean(body?.ok),
773
+ httpStatus: res.status,
774
+ latencyMs: Date.now() - t0,
775
+ workerVersion: body?.version || "unknown",
776
+ protocol: body?.protocol || 1,
777
+ features: Array.isArray(body?.features) ? body.features : []
778
+ };
779
+ if (!relayStatus.ok) healthy = false;
745
780
  } catch (e) {
746
- console.log("Relay Status: UNREACHABLE -", sanitizeText(e.message, 140));
781
+ relayStatus = { ok: false, error: sanitizeText(e.message, 140) };
747
782
  healthy = false;
748
783
  }
749
784
 
750
785
  const creds = saved();
751
- console.log("Device Pairing:", creds ? `paired (id=${String(creds.deviceId || "").slice(0, 8)}…)` : "not paired");
786
+ let localPortOccupied = false;
787
+ let localHttpStatus = 0;
752
788
  try {
753
- const st = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(1500) })).status;
754
- console.log(`Local Port ${opts.port}: occupied (HTTP ${st})`);
789
+ localHttpStatus = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(1500) })).status;
790
+ localPortOccupied = localHttpStatus > 0;
755
791
  } catch {
756
- console.log(`Local Port ${opts.port}: free`);
792
+ localPortOccupied = false;
793
+ }
794
+
795
+ if (opts.json) {
796
+ console.log(
797
+ JSON.stringify(
798
+ {
799
+ ok: healthy,
800
+ version: PKG_VERSION,
801
+ runtime: { node: process.version, platform: process.platform, arch: process.arch },
802
+ relay: opts.relay,
803
+ proxy: proxyInfo,
804
+ relayStatus,
805
+ paired: Boolean(creds?.deviceId),
806
+ deviceId: creds?.deviceId ? String(creds.deviceId).slice(0, 8) + "…" : null,
807
+ localPort: opts.port,
808
+ localPortOccupied,
809
+ policy: {
810
+ readonly: policy.readonly,
811
+ dlp: policy.dlp,
812
+ allowDirsCount: policy.allowDirs.length
813
+ }
814
+ },
815
+ null,
816
+ 2
817
+ )
818
+ );
819
+ if (!healthy) process.exitCode = 1;
820
+ return;
821
+ }
822
+
823
+ console.log(`Private Desktop MCP Doctor (v${PKG_VERSION})`);
824
+ console.log("─".repeat(48));
825
+ console.log("Node.js:", process.version, `(${process.platform}/${process.arch})`);
826
+ console.log("Relay URL:", opts.relay);
827
+ console.log(
828
+ "Proxy:",
829
+ proxyInfo.mode === "proxy"
830
+ ? `${proxyInfo.source} (${proxyInfo.description})`
831
+ : `${proxyInfo.mode} (${proxyInfo.source}${proxyInfo.reason ? ": " + proxyInfo.reason : ""})`
832
+ );
833
+ if (relayStatus.ok) {
834
+ console.log(
835
+ `Relay Status: OK (HTTP ${relayStatus.httpStatus}, ${relayStatus.latencyMs}ms, worker v${relayStatus.workerVersion}, features: ${relayStatus.features.join(",") || "legacy"})`
836
+ );
837
+ } else {
838
+ console.log("Relay Status: UNREACHABLE -", relayStatus.error || `HTTP ${relayStatus.httpStatus || 0}`);
757
839
  }
840
+ console.log("Device Pairing:", creds ? `paired (id=${String(creds.deviceId || "").slice(0, 8)}…)` : "not paired");
841
+ console.log(`Local Port ${opts.port}:`, localPortOccupied ? `occupied (HTTP ${localHttpStatus})` : "free");
758
842
  console.log("Policy:", policy.readonly ? "READONLY" : "FULL", "| DLP:", policy.dlp ? "ON" : "OFF");
759
843
  if (!healthy) process.exitCode = 1;
760
844
  }
@@ -797,6 +881,50 @@ function runReport() {
797
881
  console.log(JSON.stringify(report, null, 2));
798
882
  }
799
883
 
884
+ function runSetupClient() {
885
+ const target = String(opts.targetClient || "").toLowerCase().trim();
886
+ if (!target) {
887
+ const msg = `Specify a target client: ${SUPPORTED_CLIENTS.join(", ")} or "all"`;
888
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: msg, supportedClients: SUPPORTED_CLIENTS }, null, 2));
889
+ else console.error(msg);
890
+ process.exitCode = 2;
891
+ return;
892
+ }
893
+
894
+ const clients = target === "all" ? SUPPORTED_CLIENTS : [target];
895
+ const results = [];
896
+ for (const client of clients) {
897
+ try {
898
+ const res = configureMcpClient({
899
+ client,
900
+ relayUrl: opts.relay,
901
+ configPath: clients.length === 1 && opts.clientConfigPath ? opts.clientConfigPath : undefined,
902
+ dryRun: opts.dryRun
903
+ });
904
+ results.push(res);
905
+ } catch (e) {
906
+ results.push({ ok: false, client, error: e.message });
907
+ process.exitCode = 1;
908
+ }
909
+ }
910
+
911
+ if (opts.json) {
912
+ console.log(JSON.stringify(clients.length === 1 ? results[0] : { ok: results.every((r) => r.ok), results }, null, 2));
913
+ return;
914
+ }
915
+
916
+ for (const r of results) {
917
+ if (!r.ok) {
918
+ console.error(`❌ [${r.client}] ${r.error}`);
919
+ continue;
920
+ }
921
+ console.log(`${r.dryRun ? "🔍 [DRY-RUN]" : "✅"} [${r.client}] ${r.action.toUpperCase()} → ${r.path}`);
922
+ if (r.dryRun) {
923
+ console.log(r.preview.trimEnd());
924
+ }
925
+ }
926
+ }
927
+
800
928
  function stop() {
801
929
  if (stopping) return;
802
930
  stopping = true;
@@ -813,38 +941,78 @@ process.on("SIGTERM", stop);
813
941
 
814
942
  if (opts.command === "help") {
815
943
  console.log(
816
- `Private Desktop MCP v${PKG_VERSION}: connect | status | doctor | report | reset\n` +
944
+ `Private Desktop MCP v${PKG_VERSION}: connect | status | doctor | report | setup-client | reset\n` +
945
+ "Subcommands:\n" +
946
+ " connect Pair (if needed), start local gateway, and connect to relay\n" +
947
+ " status [--json] Check local pairing and gateway port state\n" +
948
+ " doctor [--json] End-to-end preflight check (proxy, relay health, pairing, port)\n" +
949
+ " report [--json] Generate sanitized JSON diagnostic bundle\n" +
950
+ ` setup-client <client|all> Configure MCP client (${SUPPORTED_CLIENTS.join(", ")})\n` +
951
+ " reset [--json] Clear local device pairing credentials\n" +
817
952
  "Options:\n" +
818
- " --relay <url> Custom Cloudflare Worker relay URL (env: PCC_RELAY_URL)\n" +
819
- " --port <port> Local MCP gateway port (default: 8717, env: MCP_PORT)\n" +
820
- " --name <name> Device display name when pairing (default: hostname)\n" +
821
- " --readonly Allow read-only tools only and hide mutating tools\n" +
822
- " --allow-dir <dir> Restrict file tool paths to allowed directories (repeatable)\n" +
823
- " --allow-tools <csv> Explicit allowlist of MCP tool names\n" +
824
- " --deny-tools <csv> Explicit denylist of MCP tool names\n" +
825
- " --servers <file.json> Aggregate additional local stdio MCP servers (env: PCC_MCP_CONFIG)\n" +
826
- " --no-dlp Disable outbound secret redaction on responses (enabled by default)\n" +
827
- " --no-open Do not auto-open browser during device pairing\n" +
828
- " --safe | --debug | --trace Terminal logging verbosity (default: TRACE)\n" +
953
+ " --relay <url> Custom Cloudflare Worker relay URL (env: PCC_RELAY_URL)\n" +
954
+ " --port <port> Local MCP gateway port (default: 8717, env: MCP_PORT)\n" +
955
+ " --name <name> Device display name when pairing (default: hostname)\n" +
956
+ " --readonly Allow read-only tools only and hide mutating tools\n" +
957
+ " --allow-dir <dir> Restrict file tool paths to allowed directories (repeatable)\n" +
958
+ " --allow-tools <csv> Explicit allowlist of MCP tool names\n" +
959
+ " --deny-tools <csv> Explicit denylist of MCP tool names\n" +
960
+ " --servers <file.json> Aggregate additional local stdio MCP servers (env: PCC_MCP_CONFIG)\n" +
961
+ " --no-dlp Disable outbound secret redaction on responses (enabled by default)\n" +
962
+ " --no-open Do not auto-open browser during device pairing\n" +
963
+ " --dry-run Preview client config changes without writing to disk (for setup-client)\n" +
964
+ " --config <path> Custom client config file path override (for setup-client)\n" +
965
+ " --json Emit machine-readable JSON output for agents\n" +
966
+ " --safe | --debug | --trace Terminal logging verbosity (default: TRACE)\n" +
829
967
  `Default relay: ${DEFAULT_RELAY}\n` +
830
968
  `Approval page: ${opts.relay}/admin/devices\n` +
831
969
  "Ctrl+C to disconnect. No automatic startup."
832
970
  );
833
971
  } else if (opts.command === "status") {
834
- console.log("Paired:", !!saved());
835
- console.log("Relay:", opts.relay);
972
+ const creds = saved();
973
+ let localHttpStatus = null;
836
974
  try {
837
- console.log("Local HTTP:", (await fetch(localBaseUrl, { signal: AbortSignal.timeout(2000) })).status);
975
+ localHttpStatus = (await fetch(localBaseUrl, { signal: AbortSignal.timeout(2000) })).status;
838
976
  } catch {
839
- console.log("Local MCP offline");
977
+ localHttpStatus = null;
978
+ }
979
+ if (opts.json) {
980
+ console.log(
981
+ JSON.stringify(
982
+ {
983
+ ok: true,
984
+ version: PKG_VERSION,
985
+ paired: Boolean(creds?.deviceId),
986
+ deviceId: creds?.deviceId ? String(creds.deviceId).slice(0, 8) + "…" : null,
987
+ relay: opts.relay,
988
+ localPort: opts.port,
989
+ localGatewayRunning: localHttpStatus !== null,
990
+ localHttpStatus,
991
+ policy: { readonly: policy.readonly, dlp: policy.dlp }
992
+ },
993
+ null,
994
+ 2
995
+ )
996
+ );
997
+ } else {
998
+ console.log("Paired:", !!creds);
999
+ console.log("Relay:", opts.relay);
1000
+ if (localHttpStatus !== null) console.log("Local HTTP:", localHttpStatus);
1001
+ else console.log("Local MCP offline");
840
1002
  }
841
1003
  } else if (opts.command === "doctor") {
842
1004
  await runDoctor();
843
1005
  } else if (opts.command === "report") {
844
1006
  runReport();
1007
+ } else if (opts.command === "setup-client") {
1008
+ runSetupClient();
845
1009
  } else if (opts.command === "reset") {
846
1010
  forget();
847
- console.log("Local credentials cleared. Revoke old credentials in the admin page too.");
1011
+ if (opts.json) {
1012
+ console.log(JSON.stringify({ ok: true, cleared: true, configPath: config }, null, 2));
1013
+ } else {
1014
+ console.log("Local credentials cleared. Revoke old credentials in the admin page too.");
1015
+ }
848
1016
  } else if (opts.command === "connect") {
849
1017
  logLine("info", `╔══════════════ PCC REMOTE v${PKG_VERSION} ══════════════╗`);
850
1018
  logLine(
@@ -0,0 +1,151 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ export const SUPPORTED_CLIENTS = [
6
+ "claude-code",
7
+ "claude-desktop",
8
+ "cursor",
9
+ "vscode",
10
+ "codex",
11
+ "gemini",
12
+ "windsurf"
13
+ ];
14
+
15
+ export function resolveClientConfigPath(
16
+ client,
17
+ { platform = process.platform, homedir = os.homedir(), env = process.env, cwd = process.cwd() } = {}
18
+ ) {
19
+ const c = String(client || "").toLowerCase().trim();
20
+ const appData = env.APPDATA || path.join(homedir, "AppData", "Roaming");
21
+
22
+ switch (c) {
23
+ case "claude-code":
24
+ return path.join(cwd, ".mcp.json");
25
+ case "claude-desktop":
26
+ if (platform === "win32") return path.join(appData, "Claude", "claude_desktop_config.json");
27
+ if (platform === "darwin") {
28
+ return path.join(homedir, "Library", "Application Support", "Claude", "claude_desktop_config.json");
29
+ }
30
+ return path.join(env.XDG_CONFIG_HOME || path.join(homedir, ".config"), "Claude", "claude_desktop_config.json");
31
+ case "cursor":
32
+ return path.join(homedir, ".cursor", "mcp.json");
33
+ case "vscode":
34
+ return path.join(cwd, ".vscode", "mcp.json");
35
+ case "codex":
36
+ return path.join(homedir, ".codex", "config.toml");
37
+ case "gemini":
38
+ return path.join(homedir, ".gemini", "settings.json");
39
+ case "windsurf":
40
+ return path.join(homedir, ".codeium", "windsurf", "mcp_config.json");
41
+ default:
42
+ throw new Error(`Unsupported client "${client}". Supported clients: ${SUPPORTED_CLIENTS.join(", ")}`);
43
+ }
44
+ }
45
+
46
+ export function normalizeMcpEndpointUrl(relayUrl) {
47
+ const trimmed = String(relayUrl || "").trim().replace(/\/+$/, "");
48
+ if (!trimmed) throw new Error("Empty relay URL");
49
+ return trimmed.endsWith("/mcp") ? trimmed : `${trimmed}/mcp`;
50
+ }
51
+
52
+ function mergeJsonClientConfig(client, existingText, mcpUrl, serverName = "private-desktop") {
53
+ let root = {};
54
+ if (String(existingText || "").trim()) {
55
+ const parsed = JSON.parse(existingText);
56
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
57
+ root = { ...parsed };
58
+ }
59
+ }
60
+
61
+ if (client === "vscode") {
62
+ const servers = root.servers && typeof root.servers === "object" ? { ...root.servers } : {};
63
+ servers[serverName] = { type: "http", url: mcpUrl };
64
+ root.servers = servers;
65
+ } else if (client === "gemini") {
66
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
67
+ mcpServers[serverName] = { httpUrl: mcpUrl, oauth: { enabled: true } };
68
+ root.mcpServers = mcpServers;
69
+ } else if (client === "cursor" || client === "windsurf") {
70
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
71
+ mcpServers[serverName] = { url: mcpUrl };
72
+ root.mcpServers = mcpServers;
73
+ } else {
74
+ // claude-code, claude-desktop, standard mcpServers
75
+ const mcpServers = root.mcpServers && typeof root.mcpServers === "object" ? { ...root.mcpServers } : {};
76
+ mcpServers[serverName] = { type: "http", url: mcpUrl };
77
+ root.mcpServers = mcpServers;
78
+ }
79
+
80
+ return JSON.stringify(root, null, 2) + "\n";
81
+ }
82
+
83
+ function mergeCodexTomlConfig(existingText, mcpUrl, serverName = "private_desktop") {
84
+ const sectionHeader = `[mcp_servers.${serverName}]`;
85
+ const block = `${sectionHeader}\nurl = "${mcpUrl}"\n`;
86
+ const raw = String(existingText || "");
87
+ if (!raw.trim()) return block;
88
+
89
+ const escapedHeader = sectionHeader.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
90
+ const sectionRegex = new RegExp(`(^|\\r?\\n)${escapedHeader}\\r?\\n[\\s\\S]*?(?=(\\r?\\n\\[[^\\]]+\\])|$)`);
91
+ if (sectionRegex.test(raw)) {
92
+ return raw.replace(sectionRegex, `$1${block.trimEnd()}`).replace(/\s*$/, "\n");
93
+ }
94
+ return raw.replace(/\s*$/, "\n\n") + block;
95
+ }
96
+
97
+ export function configureMcpClient({
98
+ client,
99
+ relayUrl,
100
+ serverName,
101
+ configPath,
102
+ dryRun = false,
103
+ platform = process.platform,
104
+ homedir = os.homedir(),
105
+ env = process.env,
106
+ cwd = process.cwd()
107
+ } = {}) {
108
+ const normalizedClient = String(client || "").toLowerCase().trim();
109
+ if (!SUPPORTED_CLIENTS.includes(normalizedClient)) {
110
+ throw new Error(`Unsupported client "${client}". Supported clients: ${SUPPORTED_CLIENTS.join(", ")}`);
111
+ }
112
+
113
+ const mcpUrl = normalizeMcpEndpointUrl(relayUrl);
114
+ const targetPath = configPath
115
+ ? path.resolve(configPath)
116
+ : resolveClientConfigPath(normalizedClient, { platform, homedir, env, cwd });
117
+
118
+ let existingText = "";
119
+ let existed = false;
120
+ try {
121
+ existingText = fs.readFileSync(targetPath, "utf8");
122
+ existed = true;
123
+ } catch {
124
+ existingText = "";
125
+ existed = false;
126
+ }
127
+
128
+ const nextContent =
129
+ normalizedClient === "codex"
130
+ ? mergeCodexTomlConfig(existingText, mcpUrl, serverName ? serverName.replace(/-/g, "_") : "private_desktop")
131
+ : mergeJsonClientConfig(normalizedClient, existingText, mcpUrl, serverName || "private-desktop");
132
+
133
+ const changed = nextContent !== existingText;
134
+ const action = !existed ? "create" : changed ? "update" : "unchanged";
135
+
136
+ if (!dryRun && changed) {
137
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
138
+ fs.writeFileSync(targetPath, nextContent, "utf8");
139
+ }
140
+
141
+ return {
142
+ ok: true,
143
+ client: normalizedClient,
144
+ path: targetPath,
145
+ mcpUrl,
146
+ action,
147
+ changed,
148
+ dryRun: Boolean(dryRun),
149
+ preview: nextContent
150
+ };
151
+ }
package/bin/policy.mjs CHANGED
@@ -26,7 +26,10 @@ const PATH_ARG_KEYS = [
26
26
  "destination",
27
27
  "cwd",
28
28
  "workingDirectory",
29
+ "working_directory",
29
30
  "filePath",
31
+ "file_path",
32
+ "file_paths",
30
33
  "directory",
31
34
  "dir"
32
35
  ];
@@ -111,6 +114,7 @@ export function createPolicy({
111
114
  allowDirs: allowDirs.map((d) => path.resolve(String(d).trim())).filter(Boolean),
112
115
  protectedDirs: protectedDirs.map((d) => path.resolve(String(d).trim())).filter(Boolean),
113
116
  learnedReadOnlyTools: new Set(),
117
+ toolAnnotations: new Map(),
114
118
  dlp: Boolean(dlp)
115
119
  };
116
120
  }
@@ -132,7 +136,10 @@ export function evaluateToolCall(rpc, policy, { platform = process.platform } =
132
136
  const toolName = typeof rpc.params?.name === "string" ? rpc.params.name : "";
133
137
  const args = rpc.params?.arguments && typeof rpc.params.arguments === "object" ? rpc.params.arguments : {};
134
138
 
135
- if (!isToolAllowedByName(toolName, policy)) {
139
+ // Only trust annotations learned from the upstream tools/list response. A caller can
140
+ // freely put whatever it likes in params._meta, so those hints are not authoritative.
141
+ const annotations = policy.toolAnnotations?.get(toolName) || null;
142
+ if (!isToolAllowedByName(toolName, policy, annotations)) {
136
143
  const modeReason = policy.readonly ? "connector is running in --readonly mode" : "tool is disallowed by local policy";
137
144
  return { allowed: false, reason: `Blocked locally: "${toolName}" is not permitted (${modeReason}).` };
138
145
  }
@@ -214,8 +221,14 @@ export function filterToolsListBody(bodyText, contentType, policy) {
214
221
  return transformRpcPayload(bodyText, contentType, (obj) => {
215
222
  if (!Array.isArray(obj?.result?.tools)) return null;
216
223
  const filtered = obj.result.tools.filter((tool) => {
217
- if (tool?.name && tool?.annotations?.readOnlyHint === true && tool?.annotations?.destructiveHint !== true) {
218
- policy.learnedReadOnlyTools?.add(tool.name);
224
+ if (tool?.name && tool?.annotations && typeof tool.annotations === "object") {
225
+ // Remember discovered annotations so a later tools/call can be authorized against
226
+ // the same readOnlyHint/destructiveHint that tools/list advertised, even if the
227
+ // client does not echo annotations back on the call itself.
228
+ policy.toolAnnotations?.set(tool.name, tool.annotations);
229
+ if (tool.annotations.readOnlyHint === true && tool.annotations.destructiveHint !== true) {
230
+ policy.learnedReadOnlyTools?.add(tool.name);
231
+ }
219
232
  }
220
233
  return isToolAllowedByName(tool?.name, policy, tool?.annotations || null);
221
234
  });
@@ -252,24 +265,61 @@ export function redactSecretsInText(text, extraSecrets = []) {
252
265
  return { text: out, redactedCount: count };
253
266
  }
254
267
 
268
+ // Recursively redact string values inside arbitrary JSON (handles structuredContent,
269
+ // nested objects/arrays and JSON-encoded strings). Returns a clone + count of hits.
270
+ function redactValueDeep(value, extraSecrets) {
271
+ let redactedCount = 0;
272
+ const walk = (v) => {
273
+ if (typeof v === "string") {
274
+ const res = redactSecretsInText(v, extraSecrets);
275
+ redactedCount += res.redactedCount;
276
+ return res.text;
277
+ }
278
+ if (Array.isArray(v)) return v.map(walk);
279
+ if (v && typeof v === "object") {
280
+ const out = {};
281
+ for (const [k, val] of Object.entries(v)) out[k] = walk(val);
282
+ return out;
283
+ }
284
+ return v;
285
+ };
286
+ return { value: walk(value), redactedCount };
287
+ }
288
+
255
289
  export function redactOutboundResponse(bodyText, contentType = "", { enabled = true, extraSecrets = [] } = {}) {
256
290
  if (!enabled || !bodyText) return { body: bodyText, redactedCount: 0 };
257
291
  let total = 0;
258
292
  const body = transformRpcPayload(bodyText, contentType, (obj) => {
259
- if (!Array.isArray(obj?.result?.content)) return null;
293
+ const hasContent = Array.isArray(obj?.result?.content);
294
+ const hasStructured = obj?.result?.structuredContent !== undefined && obj.result.structuredContent !== null;
295
+ if (!hasContent && !hasStructured) return null;
260
296
  let modified = false;
261
- const content = obj.result.content.map((block) => {
262
- if (block?.type === "text" && typeof block.text === "string") {
263
- const res = redactSecretsInText(block.text, extraSecrets);
264
- if (res.redactedCount > 0) {
265
- total += res.redactedCount;
266
- modified = true;
267
- return { ...block, text: res.text };
297
+ let content = obj.result.content;
298
+ if (hasContent) {
299
+ content = obj.result.content.map((block) => {
300
+ if (block?.type === "text" && typeof block.text === "string") {
301
+ const res = redactSecretsInText(block.text, extraSecrets);
302
+ if (res.redactedCount > 0) {
303
+ total += res.redactedCount;
304
+ modified = true;
305
+ return { ...block, text: res.text };
306
+ }
268
307
  }
308
+ return block;
309
+ });
310
+ }
311
+ let result = hasContent ? { ...obj.result, content } : obj.result;
312
+ // Redact secrets embedded in machine-readable structured output too; otherwise a
313
+ // secret returned via result.structuredContent would still reach the relay/LLM.
314
+ if (hasStructured) {
315
+ const deep = redactValueDeep(obj.result.structuredContent, extraSecrets);
316
+ if (deep.redactedCount > 0) {
317
+ total += deep.redactedCount;
318
+ modified = true;
319
+ result = { ...result, structuredContent: deep.value };
269
320
  }
270
- return block;
271
- });
272
- return modified ? { ...obj, result: { ...obj.result, content } } : null;
321
+ }
322
+ return modified ? { ...obj, result } : null;
273
323
  });
274
324
  return { body, redactedCount: total };
275
325
  }
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juexibobi/private-desktop-mcp",
3
- "version": "0.4.0",
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",
@@ -16,7 +16,11 @@
16
16
  "bin/proxy.mjs",
17
17
  "bin/logging.mjs",
18
18
  "bin/policy.mjs",
19
+ "bin/client-setup.mjs",
19
20
  "gateway.mjs",
21
+ "skills/private-desktop-mcp/SKILL.md",
22
+ "docs/agent-install.md",
23
+ "AGENTS.md",
20
24
  "README.md",
21
25
  "LICENSE"
22
26
  ],
@@ -26,7 +30,7 @@
26
30
  },
27
31
  "homepage": "https://github.com/KFCheems/private-desktop-mcp",
28
32
  "scripts": {
29
- "test": "node --check bin/cli.mjs && node --check bin/policy.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"
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"
30
34
  },
31
35
  "dependencies": {
32
36
  "@modelcontextprotocol/client": "2.3.1",
@@ -0,0 +1,71 @@
1
+ ---
2
+ name: private-desktop-mcp
3
+ description: Operate and orchestrate remote Windows, macOS, and Linux desktops through Private Desktop MCP (Cloudflare Worker + Durable Object WebSocket relay + local Desktop Commander gateway). Use when the user wants to inspect or switch paired desktop devices, run cross-machine commands or file operations, configure MCP clients, diagnose relay/proxy connectivity, or manage read-only and DLP guardrails.
4
+ ---
5
+
6
+ # Private Desktop MCP Skill
7
+
8
+ Use this skill when interacting with a **Private Desktop MCP** remote server (`/mcp`) or managing the local `@juexibobi/private-desktop-mcp` connector CLI.
9
+
10
+ ## 1. Multi-Device Orchestration (Remote MCP Tools & Resources)
11
+
12
+ Private Desktop MCP can pair and keep multiple computers online simultaneously. Never assume which computer is active without checking first when multiple machines exist.
13
+
14
+ ### Always-Available Edge Resources
15
+ Even when zero desktop devices are online, the Cloudflare Worker edge serves:
16
+ - `relay://devices` — JSON inventory of all paired devices (`id`, `name`, `online`, `platform`, `arch`, `cliVersion`, `clientMode`, `readOnly`, `selected`, `lastSeen`).
17
+ - `relay://status` — Worker version, protocol features, and Cloudflare Access JWT verification status.
18
+ - `relay://audit` — Recent metadata-only tool execution audit log.
19
+
20
+ ### Built-In Edge Meta-Tools
21
+ - `relay_list_devices` — Call first in multi-machine workflows to inspect online devices and check which device is `selected`.
22
+ - `relay_select_device` — Switch the default target device by `device_id` or case-insensitive `device_name`.
23
+ - `relay_ping_device` — Measure end-to-end WebSocket RTT (`rttMs`) and verify the device's local MCP gateway (`gatewayReady: true`, `uptimeMs`, `mode`).
24
+ - `relay_set_device_policy` — Lock or unlock a device in edge read-only mode (`read_only: true | false`) or rename it (`new_name`).
25
+ - `relay_recent_activity` — Inspect recent sanitized tool call audit records (`ts`, `actor`, `deviceName`, `mcpName`, `status`, `durationMs`, `ok`).
26
+
27
+ ### Per-Call Device Targeting (`_device`)
28
+ Every upstream tool (`read_file`, `list_directory`, `start_process`, `write_file`, `edit_block`, `start_search`, etc.) accepts an optional `_device` string argument:
29
+
30
+ ```json
31
+ {
32
+ "name": "read_file",
33
+ "arguments": {
34
+ "path": "C:\\Users\\Alice\\logs\\app.log",
35
+ "_device": "WorkPC"
36
+ }
37
+ }
38
+ ```
39
+
40
+ - The Worker routes that single call to `WorkPC` and strips `_device` before forwarding to the local MCP server.
41
+ - Prefer `_device` over `relay_select_device` when comparing files, logs, or processes across two machines in the same turn so you don't mutate global selection state.
42
+
43
+ ### Handling Self-Healing Tool Errors
44
+ When a `tools/call` fails with `errorCode: "NO_DEVICE_ONLINE"`, `"SELECTED_DEVICE_OFFLINE"`, or `"MULTIPLE_DEVICES_ONLINE"`:
45
+ 1. Inspect `structuredContent.onlineDevices` and `structuredContent.nextActions` in the tool response.
46
+ 2. If other devices are online, call `relay_select_device` or retry with `_device`.
47
+ 3. If no device is online, give the user the exact connector command:
48
+ ```powershell
49
+ npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect
50
+ ```
51
+
52
+ ## 2. Local Connector CLI & Client Setup (Machine-Readable `--json`)
53
+
54
+ When running local shell commands on a machine to diagnose, pair, or configure Private Desktop MCP, always pass `--json`:
55
+
56
+ | Task | Command |
57
+ |---|---|
58
+ | End-to-end health & proxy check | `npx --yes @juexibobi/private-desktop-mcp@latest doctor --json` |
59
+ | Check local pairing & port state | `npx --yes @juexibobi/private-desktop-mcp@latest status --json` |
60
+ | Export sanitized diagnostic bundle | `npx --yes @juexibobi/private-desktop-mcp@latest report --json` |
61
+ | Preview client config (`--dry-run`) | `npx --yes @juexibobi/private-desktop-mcp@latest setup-client <client> --dry-run --json` |
62
+ | Apply client config | `npx --yes @juexibobi/private-desktop-mcp@latest setup-client <client> --json` |
63
+ | Connect in read-only jailed mode | `npx --yes @juexibobi/private-desktop-mcp@latest connect --readonly --allow-dir <dir> --json` |
64
+
65
+ Supported `<client>` targets for `setup-client`: `claude-code`, `claude-desktop`, `cursor`, `vscode`, `codex`, `gemini`, `windsurf`, `all`.
66
+
67
+ ## 3. Safety & Guardrails
68
+
69
+ - **Least privilege**: When the user only needs code reading, log inspection, or diagnostics, recommend `--readonly` (or lock the device via `relay_set_device_policy` with `read_only: true`).
70
+ - **Credential boundary**: Never attempt to read or modify `PrivateDesktopMCP/device.json` via remote tools (the local policy engine blocks it automatically).
71
+ - **DLP redaction**: Outbound responses automatically redact PEM private keys, AWS/GitHub/OpenAI/Slack/Google tokens, and active relay tokens as `[REDACTED_BY_PCC_DLP]`. Never write `[REDACTED_BY_PCC_DLP]` back into user files when editing.