@juexibobi/private-desktop-mcp 0.3.4 → 0.3.6

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
@@ -12,15 +12,11 @@ npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest --
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
15
+ ### Terminal logging (v0.3.6)
16
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.
17
+ PCC now uses **TRACE logging by default**. The normal `connect` command prints MCP call IDs, sanitized/truncated command and response previews, timings, connection details, and errors. There is no need for `--trace`.
18
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
- ```
19
+ **Privacy:** TRACE can reveal sensitive file contents or command output. Redaction is best effort; avoid sharing or recording the terminal. Use `--debug` for detailed metadata without content previews, or `--safe` for compact logs. The former `--trace` flag remains supported for compatibility.
24
20
 
25
21
  ### Windows system proxy detection (v0.3.4)
26
22
 
@@ -0,0 +1,122 @@
1
+ import path from "node:path";
2
+ import { sanitizeText, safeValue } from "./logging.mjs";
3
+
4
+ const OMIT="[hidden; use --trace to inspect local content]";
5
+ const safeId=value=>typeof value==="string"?sanitizeText(value,70):typeof value==="number"?String(value):"unknown";
6
+ const byteSize=value=>Buffer.byteLength(String(value??""),"utf8");
7
+ function compact(value,limit=140){
8
+ return sanitizeText(String(value??""),limit);
9
+ }
10
+ export function parseRpc(body,contentType=""){
11
+ let text=String(body||"");
12
+ if(contentType.toLowerCase().includes("text/event-stream")){
13
+ const candidates=text.split(/\r?\n/).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trim()).filter(s=>s&&s!=="[DONE]");
14
+ for(let i=candidates.length-1;i>=0;i--){try{return JSON.parse(candidates[i])}catch{}}
15
+ }
16
+ try{return JSON.parse(text)}catch{return null}
17
+ }
18
+ export function callInfo(body,requestId=""){
19
+ const r=parseRpc(body)||{},params=r.params&&typeof r.params==="object"?r.params:{};
20
+ const name=typeof params.name==="string"?compact(params.name,80):"";
21
+ const args=params.arguments&&typeof params.arguments==="object"?params.arguments:{};
22
+ return {
23
+ requestId:safeId(requestId),
24
+ method:typeof r.method==="string"?compact(r.method,80):"unknown",
25
+ name,
26
+ jsonRpcId:safeId(r.id),
27
+ args,
28
+ label:name||compact(r.method||"unknown",80)
29
+ };
30
+ }
31
+ export function requestBrief(call){
32
+ const {args,name,method}=call;
33
+ if(method==="tools/list")return "Discover available tools";
34
+ if(method==="initialize")return "MCP session initialization";
35
+ if(method==="notifications/initialized")return "MCP session established";
36
+ if(method!=="tools/call")return method;
37
+ const fields=[];
38
+ if(typeof args.path==="string"){
39
+ const filepath=args.path.replace(/\\/g,"/");
40
+ fields.push("file="+compact(filepath.split("/").at(-1),72));
41
+ }
42
+ if(typeof args.pid==="number")fields.push("pid="+args.pid);
43
+ if(typeof args.timeout_ms==="number")fields.push("timeout="+args.timeout_ms+"ms");
44
+ if(typeof args.length==="number")fields.push("length="+args.length);
45
+ if(typeof args.offset==="number")fields.push("offset="+args.offset);
46
+ if(typeof args.shell==="string")fields.push("shell="+compact(args.shell,48));
47
+ if(typeof args.command==="string")fields.push("command="+OMIT+" ("+args.command.length+" chars)");
48
+ if(typeof args.content==="string")fields.push("content=[hidden] ("+args.content.length+" chars)");
49
+ if(typeof args.name==="string")fields.push("name="+compact(args.name,56));
50
+ return fields.join(" | ")||"parameters="+Object.keys(args).length+" fields";
51
+ }
52
+ export function requestDebug(call){
53
+ return JSON.stringify({method:call.method,id:call.jsonRpcId,tool:call.name,arguments:safeValue(call.args,"arguments")});
54
+ }
55
+ function getTextBlocks(result){
56
+ return Array.isArray(result?.content)?result.content.filter(x=>x?.type==="text"&&typeof x.text==="string").map(x=>x.text):[];
57
+ }
58
+ function safeResultSummary(result,textBlocks){
59
+ if(Array.isArray(result?.tools))return "tools="+result.tools.length;
60
+ if(result?.serverInfo&&typeof result.serverInfo.name==="string")return "server="+compact(result.serverInfo.name,56);
61
+ const joined=textBlocks.join("\n");
62
+ const hints=[];
63
+ const process=joined.match(/Process started with PID\s+(\d+)/i);
64
+ const complete=joined.match(/Process (?:completed|finished)(?: with exit code\s+(-?\d+))?/i);
65
+ const reading=joined.match(/\[Reading\s+(\d+)\s+(?:new\s+)?lines?/i);
66
+ if(process)hints.push("process PID="+process[1]);
67
+ if(complete)hints.push(complete[1]===undefined?"process finished":"exit="+complete[1]);
68
+ if(reading)hints.push("lines="+reading[1]);
69
+ if(textBlocks.length)hints.push("text blocks="+textBlocks.length);
70
+ if(joined)hints.push("output="+byteSize(joined)+" bytes");
71
+ if(!hints.length&&result&&typeof result==="object")hints.push("fields="+Object.keys(result).length);
72
+ return hints.join(" | ")||"no result";
73
+ }
74
+ export function responseBrief(body,contentType="",status=200){
75
+ const rpc=parseRpc(body,contentType);
76
+ const payloadSize=byteSize(body);
77
+ if(!rpc)return {failed:status>=400,kind:"non-JSON response",summary:"response="+payloadSize+" bytes",error:"",bytes:payloadSize,trace:""};
78
+ const error=rpc.error&&typeof rpc.error==="object"?rpc.error:null;
79
+ const result=rpc.result&&typeof rpc.result==="object"?rpc.result:null;
80
+ const blocks=getTextBlocks(result);
81
+ const failed=Boolean(status>=400||error||result?.isError);
82
+ const kind=error?"JSON-RPC error":result?.isError?"MCP tool error":failed?"HTTP error":"MCP response";
83
+ const errorText=error?.message?compact(error.message,155):"";
84
+ return {
85
+ failed,kind,
86
+ summary:result?safeResultSummary(result,blocks):"response="+payloadSize+" bytes",
87
+ error:errorText,
88
+ bytes:payloadSize,
89
+ trace:blocks.join("\n")
90
+ };
91
+ }
92
+ export function safeTraceRequest(call,limit=1200){
93
+ const value=call.args;
94
+ if(!value||typeof value!=="object")return "{}";
95
+ const output={};
96
+ for(const [key,entry] of Object.entries(value).slice(0,20)){
97
+ if(/authorization|token|password|secret|credential|cookie|proof|api.?key/i.test(key))output[key]="[REDACTED]";
98
+ else if(typeof entry==="string")output[key]=compact(entry,500);
99
+ else output[key]=safeValue(entry,key);
100
+ }
101
+ return compact(JSON.stringify(output),limit);
102
+ }
103
+ export function safeTraceOutput(info,limit=1200){
104
+ return info.trace?compact(info.trace,limit):"(no text content)";
105
+ }
106
+ export function shortCallId(id){
107
+ const text=safeId(id);
108
+ return text==="unknown"?"unknown":text.slice(0,8);
109
+ }
110
+ export function formatElapsed(ms){
111
+ return ms>=1000?(ms/1000).toFixed(2)+"s":ms+"ms";
112
+ }
113
+
114
+ /** Terminal logging defaults to TRACE unless explicitly reduced. */
115
+ export function loggingOptions(args=[]){
116
+ const flags=new Set(args);
117
+ const safe=flags.has("--safe");
118
+ const debugOnly=flags.has("--debug")&&!flags.has("--trace");
119
+ const trace=!safe&&!debugOnly;
120
+ const debug=!safe&&(debugOnly||trace);
121
+ return {trace,debug,mode:trace?"TRACE":debug?"DEBUG":"LIVE"};
122
+ }
package/bin/cli.mjs CHANGED
@@ -8,10 +8,12 @@ import WebSocket from "ws";
8
8
  import { ProxyAgent } from "undici";
9
9
  import { resolveProxyForUrl } from "./proxy.mjs";
10
10
  import { HttpsProxyAgent } from "https-proxy-agent";
11
- import { logLine, rpcDescription, rpcOutcome, sanitizeText } from "./logging.mjs";
11
+ import { logLine, sanitizeText } from "./logging.mjs";
12
+ import { callInfo, requestBrief, requestDebug, responseBrief, safeTraceRequest, safeTraceOutput, shortCallId, formatElapsed, loggingOptions } from "./activity.mjs";
12
13
 
13
14
  const root=path.dirname(path.dirname(fileURLToPath(import.meta.url)));
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";
15
+ const command=process.argv.slice(2).find(a=>!a.startsWith("--"))||"connect",relay="https://private-desktop-device-relay.ljx2043979076.workers.dev";
16
+ const {trace,debug}=loggingOptions(process.argv.slice(2));
15
17
  const config=path.join(process.env.APPDATA||path.join(os.homedir(),".config"),"PrivateDesktopMCP","device.json");
16
18
  const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
17
19
  let currentProxy=null,proxyCheckedAt=0,lastProxyNotice="";
@@ -35,6 +37,16 @@ function remoteTransport(){
35
37
  return transport;
36
38
  }
37
39
  let stopping=false,child=null,socket=null;
40
+ let connectionAttempt=0,connectedSince=0,sessionCalls=0,sessionFails=0,allCalls=0,allFails=0,lastError="";
41
+ function reportDevice(creds){
42
+ logLine("info","━━━━━━━━━━━━━━━━ PCC DEVICE READY ━━━━━━━━━━━━━━━━");
43
+ logLine("info","Computer: "+os.hostname()+" | User: "+os.userInfo().username+" | Node: "+process.version);
44
+ logLine("info","Device ID: "+creds.deviceId+" | Gateway PID: "+(child?.pid||"unknown"));
45
+ logLine("info","Relay: "+relay+" | Local MCP: http://127.0.0.1:8717/mcp");
46
+ logLine("info","Mode: "+(trace?"TRACE":debug?"DEBUG":"LIVE"));
47
+ logLine("info","Return to ChatGPT; keep this terminal running. Ctrl+C to disconnect.");
48
+ logLine("info","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
49
+ }
38
50
  function saved(){try{return JSON.parse(fs.readFileSync(config,"utf8"))}catch{return null}}
39
51
  function store(x){fs.mkdirSync(path.dirname(config),{recursive:true,mode:0o700});fs.writeFileSync(config,JSON.stringify(x,null,2),{mode:0o600});}
40
52
  function forget(){try{fs.unlinkSync(config)}catch{}}
@@ -55,15 +67,18 @@ async function startGateway(){
55
67
  logLine("info","🚀 Starting local Desktop Commander gateway...");
56
68
  const fd=fs.openSync(path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"),"a");
57
69
  child=spawn(process.execPath,[path.join(root,"gateway.mjs")],{cwd:root,stdio:["ignore",fd,fd],windowsHide:true});fs.closeSync(fd);
70
+ logLine("info","Gateway PID: "+child.pid+" | diagnostic log: "+path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"));
58
71
  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)}
59
72
  throw Error("Gateway failed to listen on port 8717.");
60
73
  }
61
74
  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;}}
62
75
  async function respond(ws,msg){
63
- const started=Date.now(),request=rpcDescription(msg.body);
64
- const title=request.name?request.method+" "+request.name:request.method;
65
- logLine("info","🔧 Received "+title);
66
- if(debug)logLine("debug","Request parameters: "+JSON.stringify(request.params));
76
+ const started=Date.now(),call=callInfo(msg.body,msg.id),callId=shortCallId(call.requestId);
77
+ const name=call.label,isTool=call.method==="tools/call";
78
+ allCalls++;sessionCalls++;
79
+ logLine("info","🔧 ["+callId+"] "+(isTool?"Tool: ":"MCP: ")+name+" | "+requestBrief(call));
80
+ if(debug)logLine("debug"," ↳ Metadata: "+requestDebug(call));
81
+ if(trace)logLine("warn"," ↳ Trace args (locally visible): "+safeTraceRequest(call));
67
82
  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];
68
83
  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{}
69
84
  let response;
@@ -72,30 +87,57 @@ async function respond(ws,msg){
72
87
  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);
73
88
  response={kind:"response",id:msg.id,status:r.status,headers:forward,body:body.slice(0,8*1024*1024)};
74
89
  }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)})}}
75
- const details=rpcOutcome(response.body,response.headers?.["content-type"]||"");
76
- const failed=response.status>=400||details.failed;
77
- logLine(failed?"error":"info",(failed?"❌ Failed ":"✅ Completed ")+title+" | HTTP "+response.status+" | "+(Date.now()-started)+"ms");
78
- if(debug)logLine("debug","Response metadata: "+JSON.stringify({kind:details.kind,bytes:details.size,resultFields:details.resultFields}));
90
+ const result=responseBrief(response.body,response.headers?.["content-type"]||"",response.status);
91
+ const failed=result.failed;
92
+ if(failed){allFails++;sessionFails++;}
93
+ logLine(failed?"error":"info",(failed?"❌":"✅")+" ["+callId+"] "+name+
94
+ " | "+result.kind+" | HTTP "+response.status+" | "+formatElapsed(Date.now()-started));
95
+ logLine(failed?"warn":"info"," ↳ "+result.summary);
96
+ if(result.error)logLine("error"," ↳ JSON-RPC: "+result.error);
97
+ if(debug)logLine("debug"," ↳ Response size: "+result.bytes+" bytes | Total calls: "+allCalls+" | Errors: "+allFails);
98
+ if(trace)logLine("warn"," ↳ Trace output (may contain private data): "+safeTraceOutput(result));
79
99
  if(ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify(response));
100
+ else logLine("warn"," ↳ Response cannot be delivered: relay socket is not open");
80
101
  }
81
102
  async function connect(creds){return new Promise(resolve=>{
82
103
  const {wsAgent}=remoteTransport();
83
- logLine("info","🌐 Connecting to Cloudflare relay...");
104
+ const attempt=++connectionAttempt,opening=Date.now();
105
+ logLine("info","🌐 Connecting to Cloudflare relay (attempt #"+attempt+")...");
84
106
  const ws=new WebSocket(relay.replace(/^https:/,"wss:")+"/relay/ws",{headers:{"Authorization":"Bearer "+creds.token,"X-Device-ID":creds.deviceId},handshakeTimeout:15000,...(wsAgent?{agent:wsAgent}:{})});socket=ws;
85
107
  let status=0;
86
- 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.");});
87
- ws.on("unexpected-response",(req,res)=>{status=res.statusCode;res.resume();logLine("error","Relay refused: HTTP "+status)});
88
- 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))});
89
- ws.on("error",e=>logLine("error","Relay: "+sanitizeText(e.message,200)));
90
- ws.on("close",(code)=>{socket=null;logLine("warn","🔌 Relay disconnected (code "+code+")");resolve({unauthorized:status===401})});
108
+ ws.on("open",()=>{
109
+ connectedSince=Date.now();sessionCalls=0;sessionFails=0;lastError="";
110
+ logLine("info","✅ Cloudflare relay connected in "+formatElapsed(Date.now()-opening));
111
+ reportDevice(creds);
112
+ console.log("CONNECTED. ChatGPT can now use this device. Ctrl+C to disconnect.");
113
+ });
114
+ ws.on("unexpected-response",(_req,res)=>{status=res.statusCode;res.resume();lastError="HTTP "+status;logLine("error","Relay handshake rejected: HTTP "+status)});
115
+ ws.on("message",data=>{
116
+ let m;try{m=JSON.parse(String(data))}catch{if(debug)logLine("debug","Ignored invalid relay JSON message");return}
117
+ if(m.kind==="request")respond(ws,m).catch(e=>logLine("error","Request handler: "+sanitizeText(e.message,240)));
118
+ });
119
+ ws.on("error",e=>{lastError=sanitizeText(e.message,180);logLine("error","Relay network error: "+lastError)});
120
+ ws.on("close",(code,reason)=>{
121
+ socket=null;
122
+ const uptime=connectedSince?formatElapsed(Date.now()-connectedSince):"not established";
123
+ logLine("warn","🔌 Relay disconnected | code="+code+" | session uptime="+uptime+
124
+ " | calls="+sessionCalls+" | failures="+sessionFails);
125
+ if(lastError)logLine("warn"," ↳ Last network error: "+lastError);
126
+ if(reason?.length)logLine("warn"," ↳ Close reason: "+sanitizeText(reason.toString(),100));
127
+ connectedSince=0;
128
+ resolve({unauthorized:status===401});
129
+ });
91
130
  })}
92
131
  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();}
93
132
  process.on("SIGINT",stop);process.on("SIGTERM",stop);
94
- 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.");}
133
+ if(["help","--help","-h"].includes(command)){console.log("Private Desktop MCP: connect | status | reset [--safe | --debug | --trace]\nDefault: TRACE logs with redacted/truncated command and response previews (may contain private data).\nUse --safe for compact metadata-only logs, or --debug for detailed metadata without content previews.\nFirst connect requires approval at https://private-desktop-device-relay.ljx2043979076.workers.dev/admin/devices\nCtrl+C to disconnect. No automatic startup.");}
95
134
  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")}}
96
135
  else if(command==="reset"){forget();console.log("Local credentials cleared. Revoke old credentials in the admin page too.");}
97
136
  else if(command==="connect"){
98
- logLine("info","PCC v0.3.4 starting ("+(debug?"debug":"normal")+" logging)");
137
+ logLine("info","╔══════════════ PCC REMOTE v0.3.6 ══════════════╗");
138
+ logLine("info","Logging: "+(trace?"TRACE":debug?"DEBUG":"LIVE")+" | Gateway: Desktop Commander MCP");
139
+ if(trace)logLine("warn","TRACE mode can display private user content in this terminal; do not share these logs.");
140
+ logLine("info","╚═══════════════════════════════════════════════╝");
99
141
  try{const credentials=saved()||await pair();if(saved())logLine("info","💾 Stored device pairing found");await startGateway();let retries=0;
100
142
  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);}
101
143
  }catch(e){logLine("error","ERROR: "+sanitizeText(e.message,250));process.exitCode=1}finally{stopGateway()}
package/bin/logging.mjs CHANGED
@@ -50,6 +50,6 @@ export function rpcOutcome(body,contentType=""){
50
50
  }
51
51
  export function logLine(level,message){
52
52
  const tag={info:"INFO",warn:"WARN",error:"ERROR",debug:"DEBUG"}[level]||"INFO";
53
- const output="["+timestamp()+"] ["+tag+"] "+sanitizeText(message,800);
53
+ const output="["+timestamp()+"] ["+tag+"] "+sanitizeText(message,1550);
54
54
  if(level==="error")console.error(output);else console.log(output);
55
55
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juexibobi/private-desktop-mcp",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
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/activity.mjs",
15
16
  "bin/proxy.mjs",
16
17
  "bin/logging.mjs",
17
18
  "gateway.mjs",