@juexibobi/private-desktop-mcp 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,11 +7,23 @@ Self-hosted multi-device [Model Context Protocol](https://modelcontextprotocol.i
7
7
  ## Public npm release
8
8
 
9
9
  ```powershell
10
- npx.cmd --yes --prefer-online @juexibobi/private-desktop-mcp@latest connect
10
+ npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect
11
11
  ```
12
12
 
13
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.
14
14
 
15
+ ### Terminal logging
16
+
17
+ The default `connect` command displays timestamped connection events, local gateway startup, incoming MCP method/tool names, HTTP/RPC success or failure, execution durations and reconnect activity. The terminal stays open for live monitoring.
18
+
19
+ For more details, use `--debug`:
20
+
21
+ ```powershell
22
+ npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --debug
23
+ ```
24
+
25
+ Debug mode prints **redacted parameter metadata and response size/type**, not command contents, file contents or raw tool results. Sensitive fields and inline tokens are masked, but local paths and other non-sensitive metadata may still appear, so avoid sharing debug logs publicly. The child gateway's detailed stderr/stdout is still stored at `%TEMP%\private-desktop-mcp-device.log`. Neither logging mode changes device pairing, OAuth or startup behavior.
26
+
15
27
  ## Current independent endpoint
16
28
 
17
29
  ```text
package/bin/cli.mjs CHANGED
@@ -8,9 +8,10 @@ import WebSocket from "ws";
8
8
  import { EnvHttpProxyAgent, setGlobalDispatcher } from "undici";
9
9
  import { getProxyForUrl } from "proxy-from-env";
10
10
  import { HttpsProxyAgent } from "https-proxy-agent";
11
+ import { logLine, rpcDescription, rpcOutcome, sanitizeText } from "./logging.mjs";
11
12
  setGlobalDispatcher(new EnvHttpProxyAgent());
12
13
  const root=path.dirname(path.dirname(fileURLToPath(import.meta.url)));
13
- const command=process.argv[2]||"connect",relay="https://private-desktop-device-relay.ljx2043979076.workers.dev";
14
+ const command=process.argv.slice(2).find(a=>!a.startsWith("--"))||"connect",debug=process.argv.includes("--debug"),relay="https://private-desktop-device-relay.ljx2043979076.workers.dev";
14
15
  const config=path.join(process.env.APPDATA||path.join(os.homedir(),".config"),"PrivateDesktopMCP","device.json");
15
16
  const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
16
17
  let stopping=false,child=null,socket=null;
@@ -20,23 +21,29 @@ function forget(){try{fs.unlinkSync(config)}catch{}}
20
21
  async function post(route,data){const r=await fetch(relay+route,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(data),signal:AbortSignal.timeout(12000)});const j=await r.json();if(!r.ok)throw Error(j.error||"HTTP "+r.status);return j;}
21
22
  async function pair(){
22
23
  const v=await post("/relay/pair/start",{name:os.hostname()});
24
+ logLine("info","🔑 New device pairing requested");
23
25
  console.log("\nNEW DEVICE: "+os.hostname()+"\nPAIRING CODE: "+v.code+"\nPlease visit "+v.approvalUrl+" and approve the matching code.\nWaiting for approval (60 minutes)...\n");
24
26
  for(let i=0;i<720&&!stopping;i++){
25
27
  await sleep(5000);let r;try{r=await post("/relay/pair/poll",{pairId:v.pairId,proof:v.proof})}catch(e){if(/expired|invalid/i.test(e.message))throw e;continue}
26
- if(r.status==="approved"){const credentials={deviceId:r.deviceId,token:r.token};store(credentials);console.log("Device approved and credentials saved.");return credentials}
28
+ if(r.status==="approved"){const credentials={deviceId:r.deviceId,token:r.token};store(credentials);logLine("info","✅ Device approved; credentials saved locally.");return credentials}
27
29
  }
28
30
  throw Error("Pairing timed out. Re-run the command.");
29
31
  }
30
32
  async function portOpen(){const r=await fetch("http://127.0.0.1:8717/mcp",{signal:AbortSignal.timeout(1500)});return r.status>0;}
31
33
  async function startGateway(){
32
34
  try{if(await portOpen())throw Error("Port 8717 is already occupied. Stop the other MCP gateway before connecting.")}catch(e){if(/occupied/.test(e.message))throw e}
35
+ logLine("info","🚀 Starting local Desktop Commander gateway...");
33
36
  const fd=fs.openSync(path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"),"a");
34
37
  child=spawn(process.execPath,[path.join(root,"gateway.mjs")],{cwd:root,stdio:["ignore",fd,fd],windowsHide:true});fs.closeSync(fd);
35
- for(let i=0;i<40;i++){if(child.exitCode!==null)throw Error("Gateway exited unexpectedly. See private-desktop-mcp-device.log");try{if(await portOpen())return}catch{}await sleep(500)}
38
+ for(let i=0;i<40;i++){if(child.exitCode!==null)throw Error("Gateway exited unexpectedly. See private-desktop-mcp-device.log");try{if(await portOpen()){logLine("info","🔌 Local Desktop Commander gateway ready (127.0.0.1:8717)");return}}catch{}await sleep(500)}
36
39
  throw Error("Gateway failed to listen on port 8717.");
37
40
  }
38
41
  function stopGateway(){if(child?.pid){if(process.platform==="win32")spawnSync("taskkill.exe",["/PID",String(child.pid),"/T","/F"],{windowsHide:true,timeout:8000});else child.kill("SIGTERM");child=null;}}
39
42
  async function respond(ws,msg){
43
+ const started=Date.now(),request=rpcDescription(msg.body);
44
+ const title=request.name?request.method+" "+request.name:request.method;
45
+ logLine("info","🔧 Received "+title);
46
+ if(debug)logLine("debug","Request parameters: "+JSON.stringify(request.params));
40
47
  const headers={};for(const k of ["accept","content-type","mcp-session-id","mcp-protocol-version","last-event-id","mcp-method","mcp-name"])if(msg.headers?.[k])headers[k]=msg.headers[k];
41
48
  try{const rpc=JSON.parse(String(msg.body||""));if(typeof rpc.method==="string"){headers["mcp-method"]=rpc.method;if(rpc.method==="tools/call"&&typeof rpc.params?.name==="string")headers["mcp-name"]=rpc.params.name;}}catch{}
42
49
  let response;
@@ -45,25 +52,31 @@ async function respond(ws,msg){
45
52
  const body=await r.text(),forward={};for(const k of ["content-type","mcp-session-id","mcp-protocol-version"])if(r.headers.has(k))forward[k]=r.headers.get(k);
46
53
  response={kind:"response",id:msg.id,status:r.status,headers:forward,body:body.slice(0,8*1024*1024)};
47
54
  }catch(e){response={kind:"response",id:msg.id,status:502,headers:{"content-type":"application/json"},body:JSON.stringify({error:"Local gateway error",message:String(e.message).slice(0,180)})}}
55
+ const details=rpcOutcome(response.body,response.headers?.["content-type"]||"");
56
+ const failed=response.status>=400||details.failed;
57
+ logLine(failed?"error":"info",(failed?"❌ Failed ":"✅ Completed ")+title+" | HTTP "+response.status+" | "+(Date.now()-started)+"ms");
58
+ if(debug)logLine("debug","Response metadata: "+JSON.stringify({kind:details.kind,bytes:details.size,resultFields:details.resultFields}));
48
59
  if(ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify(response));
49
60
  }
50
61
  async function connect(creds){return new Promise(resolve=>{
51
62
  const proxyUrl=getProxyForUrl(relay);
63
+ logLine("info","🌐 Connecting to Cloudflare relay...");
52
64
  const ws=new WebSocket(relay.replace(/^https:/,"wss:")+"/relay/ws",{headers:{"Authorization":"Bearer "+creds.token,"X-Device-ID":creds.deviceId},handshakeTimeout:15000,...(proxyUrl?{agent:new HttpsProxyAgent(proxyUrl)}:{})});socket=ws;
53
65
  let status=0;
54
- ws.on("open",()=>console.log("CONNECTED. ChatGPT can now use this device. Ctrl+C to disconnect."));
55
- ws.on("unexpected-response",(req,res)=>{status=res.statusCode;res.resume();console.error("Relay refused:",status)});
66
+ ws.on("open",()=>{logLine("info","✅ Connected to Cloudflare relay");logLine("info","🟢 Device online: "+os.hostname());console.log("CONNECTED. ChatGPT can now use this device. Ctrl+C to disconnect.");});
67
+ ws.on("unexpected-response",(req,res)=>{status=res.statusCode;res.resume();logLine("error","Relay refused: HTTP "+status)});
56
68
  ws.on("message",data=>{let m;try{m=JSON.parse(String(data))}catch{return}if(m.kind==="request")respond(ws,m).catch(e=>console.error(e.message))});
57
- ws.on("error",e=>console.error("Relay:",e.message));
58
- ws.on("close",()=>{socket=null;resolve({unauthorized:status===401})});
69
+ ws.on("error",e=>logLine("error","Relay: "+sanitizeText(e.message,200)));
70
+ ws.on("close",(code)=>{socket=null;logLine("warn","🔌 Relay disconnected (code "+code+")");resolve({unauthorized:status===401})});
59
71
  })}
60
- function stop(){if(stopping)return;stopping=true;try{socket?.close(1000,"Manual disconnect")}catch{}stopGateway();setTimeout(()=>process.exit(0),200).unref();}
72
+ function stop(){if(stopping)return;stopping=true;logLine("info","Disconnecting PCC...");try{socket?.close(1000,"Manual disconnect")}catch{}stopGateway();setTimeout(()=>process.exit(0),200).unref();}
61
73
  process.on("SIGINT",stop);process.on("SIGTERM",stop);
62
- if(["help","--help","-h"].includes(command)){console.log("Private Desktop MCP: connect | status | reset\nFirst connect requires approval at https://private-desktop-device-relay.ljx2043979076.workers.dev/admin/devices\nCtrl+C to disconnect. No automatic startup.");}
74
+ if(["help","--help","-h"].includes(command)){console.log("Private Desktop MCP: connect | status | reset [--debug]\nUse --debug for redacted request/response metadata.\nFirst connect requires approval at https://private-desktop-device-relay.ljx2043979076.workers.dev/admin/devices\nCtrl+C to disconnect. No automatic startup.");}
63
75
  else if(command==="status"){console.log("Paired:",!!saved());try{console.log("Local HTTP:",(await fetch("http://127.0.0.1:8717/mcp",{signal:AbortSignal.timeout(2000)})).status)}catch{console.log("Local MCP offline")}}
64
76
  else if(command==="reset"){forget();console.log("Local credentials cleared. Revoke old credentials in the admin page too.");}
65
77
  else if(command==="connect"){
66
- try{const credentials=saved()||await pair();await startGateway();let retries=0;
67
- while(!stopping){const r=await connect(credentials);if(r.unauthorized){forget();console.error("Credentials revoked; run again to pair.");break}if(stopping)break;retries++;const ms=Math.min(30000,1500*2**Math.min(5,retries));console.log("Reconnecting in "+Math.ceil(ms/1000)+"s");await sleep(ms);}
68
- }catch(e){console.error("ERROR:",e.message);process.exitCode=1}finally{stopGateway()}
78
+ logLine("info","PCC v0.3.3 starting ("+(debug?"debug":"normal")+" logging)");
79
+ try{const credentials=saved()||await pair();if(saved())logLine("info","💾 Stored device pairing found");await startGateway();let retries=0;
80
+ while(!stopping){const r=await connect(credentials);if(r.unauthorized){forget();logLine("error","Credentials revoked; run again to pair.");break}if(stopping)break;retries++;const ms=Math.min(30000,1500*2**Math.min(5,retries));logLine("warn","Reconnecting in "+Math.ceil(ms/1000)+"s");await sleep(ms);}
81
+ }catch(e){logLine("error","ERROR: "+sanitizeText(e.message,250));process.exitCode=1}finally{stopGateway()}
69
82
  }else{console.error("Unknown command. Use help");process.exitCode=2}
@@ -0,0 +1,55 @@
1
+ const secretKey=/^(?:authorization|cookie|set-cookie|password|passwd|passphrase|token|access[_-]?token|refresh[_-]?token|api[_-]?key|secret|private[_-]?key|credential|credentials|session[_-]?id|proof|pair[_-]?code|client[_-]?secret)$/i;
2
+ const contentKey=/^(?:command|body|content|text|stdin|script|source|data|payload|file_contents|file_content|new_string|old_string)$/i;
3
+ const secretInline=[
4
+ /(Bearer\s+)[A-Za-z0-9._~+/-]+/gi,
5
+ /((?:password|passwd|passphrase|token|api[_-]?key|client[_-]?secret|access[_-]?token|refresh[_-]?token)\s*[:=]\s*["']?)[^\s"'&,;]+/gi
6
+ ];
7
+ export function timestamp(date=new Date()){
8
+ return [date.getHours(),date.getMinutes(),date.getSeconds()].map(n=>String(n).padStart(2,"0")).join(":");
9
+ }
10
+ export function sanitizeText(value,max=200){
11
+ let s=String(value).replace(/[\r\n\t]+/g," ");
12
+ for(const re of secretInline)s=s.replace(re,"$1[REDACTED]");
13
+ return s.length>max?s.slice(0,max)+"…":s;
14
+ }
15
+ export function safeValue(value,key="",depth=0){
16
+ if(secretKey.test(key))return "[REDACTED]";
17
+ if(contentKey.test(key))return "[omitted "+(typeof value==="string"?value.length:JSON.stringify(value??null).length)+" chars]";
18
+ if(depth>=5)return "[nested]";
19
+ if(typeof value==="string")return sanitizeText(value,160);
20
+ if(typeof value==="number"||typeof value==="boolean"||value===null)return value;
21
+ if(Array.isArray(value))return value.slice(0,8).map(v=>safeValue(v,"",depth+1));
22
+ if(value&&typeof value==="object"){
23
+ const out={};
24
+ for(const [k,v] of Object.entries(value).slice(0,18))out[k]=safeValue(v,k,depth+1);
25
+ return out;
26
+ }
27
+ return "[unknown]";
28
+ }
29
+ export function rpcDescription(body){
30
+ try{
31
+ const req=JSON.parse(String(body||""));
32
+ const method=typeof req.method==="string"?sanitizeText(req.method,90):"unknown";
33
+ const name=method==="tools/call"&&typeof req.params?.name==="string"?sanitizeText(req.params.name,100):"";
34
+ return {method,name,params:safeValue(req.params??{},"params")};
35
+ }catch{return {method:"unparseable",name:"",params:{}}}
36
+ }
37
+ export function rpcOutcome(body,contentType=""){
38
+ let payload=String(body||"");
39
+ if(contentType.includes("text/event-stream")){
40
+ const data=payload.split(/\r?\n/).find(x=>x.startsWith("data:"));
41
+ if(data)payload=data.slice(5).trim();
42
+ }
43
+ try{
44
+ const rpc=JSON.parse(payload);
45
+ const failed=Boolean(rpc.error||rpc.result?.isError);
46
+ return {failed,size:Buffer.byteLength(String(body||""),"utf8"),kind:failed?"rpc-error":"rpc-ok",resultFields:rpc.result&&typeof rpc.result==="object"?Object.keys(rpc.result).slice(0,10):[]};
47
+ }catch{
48
+ return {failed:false,size:Buffer.byteLength(String(body||""),"utf8"),kind:"non-json",resultFields:[]};
49
+ }
50
+ }
51
+ export function logLine(level,message){
52
+ const tag={info:"INFO",warn:"WARN",error:"ERROR",debug:"DEBUG"}[level]||"INFO";
53
+ const output="["+timestamp()+"] ["+tag+"] "+sanitizeText(message,800);
54
+ if(level==="error")console.error(output);else console.log(output);
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juexibobi/private-desktop-mcp",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
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",
@@ -12,6 +12,7 @@
12
12
  },
13
13
  "files": [
14
14
  "bin/cli.mjs",
15
+ "bin/logging.mjs",
15
16
  "gateway.mjs",
16
17
  "README.md",
17
18
  "LICENSE"