@juexibobi/private-desktop-mcp 0.3.4 → 0.3.5

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
@@ -72,3 +72,24 @@ Never protect the **entire Worker** with Worker-level Access: this would prevent
72
72
  ## Security
73
73
 
74
74
  This tool has Windows filesystem and command-execution capabilities. Restrict Cloudflare Access to your own identity, approve only devices you control and never expose a naked HTTP MCP endpoint. See [SECURITY.md](SECURITY.md).
75
+
76
+
77
+ ## Detailed live console (v0.3.5)
78
+
79
+ PCC now displays an expanded terminal startup banner with computer, device ID, Node version, gateway PID, local MCP URL, Cloudflare relay state and logging mode. Every incoming MCP method/tool call has a short correlation ID, safe parameter summary, MCP/HTTP outcome, duration and structured result summaries (process PID, exit code, line count and output size when available). WebSocket disconnections include close code, connection uptime, total calls and failures. A tool can fail at the MCP layer even when HTTP returns 200; this is reported as an **MCP tool error**.
80
+
81
+ Logging has three levels:
82
+
83
+ | Command option | Terminal contents | Privacy |
84
+ | --- | --- | --- |
85
+ | No option | Rich startup, call and response summaries; no raw files/commands | Default |
86
+ | \`--debug\` | Adds redacted request metadata, result sizes and aggregate counters | Safe diagnostic metadata |
87
+ | \`--trace\` | Also shows sanitized, truncated command and response previews | **Local opt-in; may expose confidential user text** |
88
+
89
+ Example for full local previews (not recommended when screen sharing or saving terminal transcripts):
90
+
91
+ \`\`\`powershell
92
+ npx.cmd --yes --prefer-online --package=@juexibobi/private-desktop-mcp@latest -- private-desktop-mcp connect --trace
93
+ \`\`\`
94
+
95
+ **Important:** \`--trace\` is best-effort redaction, not a guarantee that arbitrary secrets embedded in file contents or command results will be removed. Use normal logging or \`--debug\` for everyday use. All logs print to the local terminal and are not transmitted to third-party logging services by this feature. The underlying gateway's diagnostics remain in \`%TEMP%\private-desktop-mcp-device.log\`.
@@ -0,0 +1,112 @@
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
+ }
package/bin/cli.mjs CHANGED
@@ -8,10 +8,11 @@ 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 } 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",trace=process.argv.includes("--trace"),debug=process.argv.includes("--debug")||trace,relay="https://private-desktop-device-relay.ljx2043979076.workers.dev";
15
16
  const config=path.join(process.env.APPDATA||path.join(os.homedir(),".config"),"PrivateDesktopMCP","device.json");
16
17
  const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
17
18
  let currentProxy=null,proxyCheckedAt=0,lastProxyNotice="";
@@ -35,6 +36,16 @@ function remoteTransport(){
35
36
  return transport;
36
37
  }
37
38
  let stopping=false,child=null,socket=null;
39
+ let connectionAttempt=0,connectedSince=0,sessionCalls=0,sessionFails=0,allCalls=0,allFails=0,lastError="";
40
+ function reportDevice(creds){
41
+ logLine("info","━━━━━━━━━━━━━━━━ PCC DEVICE READY ━━━━━━━━━━━━━━━━");
42
+ logLine("info","Computer: "+os.hostname()+" | User: "+os.userInfo().username+" | Node: "+process.version);
43
+ logLine("info","Device ID: "+creds.deviceId+" | Gateway PID: "+(child?.pid||"unknown"));
44
+ logLine("info","Relay: "+relay+" | Local MCP: http://127.0.0.1:8717/mcp");
45
+ logLine("info","Mode: "+(trace?"TRACE":debug?"DEBUG":"LIVE"));
46
+ logLine("info","Return to ChatGPT; keep this terminal running. Ctrl+C to disconnect.");
47
+ logLine("info","━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
48
+ }
38
49
  function saved(){try{return JSON.parse(fs.readFileSync(config,"utf8"))}catch{return null}}
39
50
  function store(x){fs.mkdirSync(path.dirname(config),{recursive:true,mode:0o700});fs.writeFileSync(config,JSON.stringify(x,null,2),{mode:0o600});}
40
51
  function forget(){try{fs.unlinkSync(config)}catch{}}
@@ -55,15 +66,18 @@ async function startGateway(){
55
66
  logLine("info","🚀 Starting local Desktop Commander gateway...");
56
67
  const fd=fs.openSync(path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"),"a");
57
68
  child=spawn(process.execPath,[path.join(root,"gateway.mjs")],{cwd:root,stdio:["ignore",fd,fd],windowsHide:true});fs.closeSync(fd);
69
+ logLine("info","Gateway PID: "+child.pid+" | diagnostic log: "+path.join(process.env.TEMP||os.tmpdir(),"private-desktop-mcp-device.log"));
58
70
  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
71
  throw Error("Gateway failed to listen on port 8717.");
60
72
  }
61
73
  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
74
  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));
75
+ const started=Date.now(),call=callInfo(msg.body,msg.id),callId=shortCallId(call.requestId);
76
+ const name=call.label,isTool=call.method==="tools/call";
77
+ allCalls++;sessionCalls++;
78
+ logLine("info","🔧 ["+callId+"] "+(isTool?"Tool: ":"MCP: ")+name+" | "+requestBrief(call));
79
+ if(debug)logLine("debug"," ↳ Metadata: "+requestDebug(call));
80
+ if(trace)logLine("warn"," ↳ Trace args (locally visible): "+safeTraceRequest(call));
67
81
  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
82
  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
83
  let response;
@@ -72,30 +86,57 @@ async function respond(ws,msg){
72
86
  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
87
  response={kind:"response",id:msg.id,status:r.status,headers:forward,body:body.slice(0,8*1024*1024)};
74
88
  }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}));
89
+ const result=responseBrief(response.body,response.headers?.["content-type"]||"",response.status);
90
+ const failed=result.failed;
91
+ if(failed){allFails++;sessionFails++;}
92
+ logLine(failed?"error":"info",(failed?"❌":"✅")+" ["+callId+"] "+name+
93
+ " | "+result.kind+" | HTTP "+response.status+" | "+formatElapsed(Date.now()-started));
94
+ logLine(failed?"warn":"info"," ↳ "+result.summary);
95
+ if(result.error)logLine("error"," ↳ JSON-RPC: "+result.error);
96
+ if(debug)logLine("debug"," ↳ Response size: "+result.bytes+" bytes | Total calls: "+allCalls+" | Errors: "+allFails);
97
+ if(trace)logLine("warn"," ↳ Trace output (may contain private data): "+safeTraceOutput(result));
79
98
  if(ws.readyState===WebSocket.OPEN)ws.send(JSON.stringify(response));
99
+ else logLine("warn"," ↳ Response cannot be delivered: relay socket is not open");
80
100
  }
81
101
  async function connect(creds){return new Promise(resolve=>{
82
102
  const {wsAgent}=remoteTransport();
83
- logLine("info","🌐 Connecting to Cloudflare relay...");
103
+ const attempt=++connectionAttempt,opening=Date.now();
104
+ logLine("info","🌐 Connecting to Cloudflare relay (attempt #"+attempt+")...");
84
105
  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
106
  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})});
107
+ ws.on("open",()=>{
108
+ connectedSince=Date.now();sessionCalls=0;sessionFails=0;lastError="";
109
+ logLine("info","✅ Cloudflare relay connected in "+formatElapsed(Date.now()-opening));
110
+ reportDevice(creds);
111
+ console.log("CONNECTED. ChatGPT can now use this device. Ctrl+C to disconnect.");
112
+ });
113
+ ws.on("unexpected-response",(_req,res)=>{status=res.statusCode;res.resume();lastError="HTTP "+status;logLine("error","Relay handshake rejected: HTTP "+status)});
114
+ ws.on("message",data=>{
115
+ let m;try{m=JSON.parse(String(data))}catch{if(debug)logLine("debug","Ignored invalid relay JSON message");return}
116
+ if(m.kind==="request")respond(ws,m).catch(e=>logLine("error","Request handler: "+sanitizeText(e.message,240)));
117
+ });
118
+ ws.on("error",e=>{lastError=sanitizeText(e.message,180);logLine("error","Relay network error: "+lastError)});
119
+ ws.on("close",(code,reason)=>{
120
+ socket=null;
121
+ const uptime=connectedSince?formatElapsed(Date.now()-connectedSince):"not established";
122
+ logLine("warn","🔌 Relay disconnected | code="+code+" | session uptime="+uptime+
123
+ " | calls="+sessionCalls+" | failures="+sessionFails);
124
+ if(lastError)logLine("warn"," ↳ Last network error: "+lastError);
125
+ if(reason?.length)logLine("warn"," ↳ Close reason: "+sanitizeText(reason.toString(),100));
126
+ connectedSince=0;
127
+ resolve({unauthorized:status===401});
128
+ });
91
129
  })}
92
130
  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
131
  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.");}
132
+ if(["help","--help","-h"].includes(command)){console.log("Private Desktop MCP: connect | status | reset [--debug | --trace]\nUse --debug for safe metadata; --trace shows redacted/truncated content previews (may contain private data).\nFirst connect requires approval at https://private-desktop-device-relay.ljx2043979076.workers.dev/admin/devices\nCtrl+C to disconnect. No automatic startup.");}
95
133
  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
134
  else if(command==="reset"){forget();console.log("Local credentials cleared. Revoke old credentials in the admin page too.");}
97
135
  else if(command==="connect"){
98
- logLine("info","PCC v0.3.4 starting ("+(debug?"debug":"normal")+" logging)");
136
+ logLine("info","╔══════════════ PCC REMOTE v0.3.5 ══════════════╗");
137
+ logLine("info","Logging: "+(trace?"TRACE":debug?"DEBUG":"LIVE")+" | Gateway: Desktop Commander MCP");
138
+ if(trace)logLine("warn","TRACE mode can display private user content in this terminal; do not share these logs.");
139
+ logLine("info","╚═══════════════════════════════════════════════╝");
99
140
  try{const credentials=saved()||await pair();if(saved())logLine("info","💾 Stored device pairing found");await startGateway();let retries=0;
100
141
  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
142
  }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.5",
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",