lunisphere-mcp 1.0.0 → 1.2.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/README.md CHANGED
@@ -2,19 +2,22 @@
2
2
 
3
3
  Local PC agent for [Lunisphere MCP Relay](https://mcp.lunisphere.com). Connects your local workspace to remote MCP clients (Gemini, Claude, Cursor) via outbound HTTPS long-polling with zero tunnel or port-forwarding setup.
4
4
 
5
- ## Usage
5
+ ## One-Command Auto-Setup & Startup
6
6
 
7
- Run directly with `npx`:
7
+ Run once in your workspace folder (run from an **Administrator terminal** on Windows to register silent elevated startup without future UAC prompts):
8
8
 
9
9
  ```bash
10
- npx lunisphere-mcp --server="https://mcp.lunisphere.com" --key="YOUR_DEVICE_KEY" --dir="."
10
+ npx -y lunisphere-mcp@latest --server="https://mcp.lunisphere.com" --key="YOUR_DEVICE_KEY" --dir="." --allow-shell --setup
11
11
  ```
12
12
 
13
- Or install globally:
13
+ What `--setup` does:
14
+ 1. Installs or updates `lunisphere-mcp@latest` globally from npm.
15
+ 2. Saves configuration to `~/.lunisphere-mcp/config.json`.
16
+ 3. Registers silent OS startup (no console window popup) and starts the agent in the background immediately.
17
+ 4. Automatically checks npm for newer releases on every startup and updates silently.
18
+
19
+ ## Uninstall Startup
14
20
 
15
21
  ```bash
16
- npm install -g lunisphere-mcp
17
- lunisphere-mcp --server="https://mcp.lunisphere.com" --key="YOUR_DEVICE_KEY" --dir="."
22
+ lunisphere-mcp --uninstall
18
23
  ```
19
-
20
- Add `--allow-shell` to enable `cmd_execute` and `bg_*` background job tools.
package/bin/cli.js CHANGED
@@ -1,68 +1,183 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';
3
-
4
- const path = require('path');
5
- const { LocalToolkit } = require('../lib/tools');
6
- const { RelayPoller } = require('../lib/poller');
7
-
8
- function parseArgs(argv) {
9
- const args = {};
10
- for (let i = 0; i < argv.length; i++) {
11
- const token = argv[i];
12
- if (token.startsWith('--')) {
13
- const eq = token.indexOf('=');
14
- if (eq !== -1) {
15
- args[token.slice(2, eq)] = token.slice(eq + 1);
16
- } else {
17
- const key = token.slice(2);
18
- const next = argv[i + 1];
19
- if (next && !next.startsWith('--')) {
20
- args[key] = next;
21
- i++;
22
- } else {
23
- args[key] = true;
24
- }
25
- }
26
- }
27
- }
28
- return args;
29
- }
30
-
31
- const args = parseArgs(process.argv.slice(2));
32
-
33
- if (args.help || !args.key) {
34
- console.log(`
35
- Lunisphere MCP PC Client
36
- Usage:
37
- lunisphere-mcp --server="https://mcp.lunisphere.com" --key="dk_..." --dir="." [--allow-shell]
38
-
39
- Options:
40
- --server Relay server base URL (default: https://mcp.lunisphere.com)
41
- --key Device Key copied from your dashboard (required)
42
- --dir Workspace directory to expose (default: current directory)
43
- --allow-shell Enable cmd_execute and bg_* background job tools (off by default)
44
- `);
45
- process.exit(args.help ? 0 : 1);
46
- }
47
-
48
- const serverUrl = args.server || 'https://mcp.lunisphere.com';
49
- const rootDir = path.resolve(args.dir || process.cwd());
50
- const allowShell = Boolean(args['allow-shell']);
51
-
52
- console.log('===============================================');
53
- console.log(' Lunisphere MCP PC Client');
54
- console.log(` Server: ${serverUrl}`);
55
- console.log(` Workspace: ${rootDir}`);
56
- console.log(` Shell: ${allowShell ? 'ENABLED' : 'DISABLED (read/write sandbox only)'}`);
57
- console.log('===============================================');
58
-
59
- const toolkit = new LocalToolkit({ rootDir, allowShell });
60
- const poller = new RelayPoller({ serverUrl, deviceKey: args.key, toolkit });
61
-
62
- process.on('SIGINT', () => {
63
- console.log('\n[STOP] Shutting down Lunisphere MCP Client...');
64
- poller.stop();
65
- process.exit(0);
66
- });
67
-
68
- poller.start();
2
+ 'use strict';
3
+
4
+ const path = require('path');
5
+ const pkg = require('../package.json');
6
+ const { LocalToolkit } = require('../lib/tools');
7
+ const { RelayPoller } = require('../lib/poller');
8
+ const { ensureLatestAndMaybeRespawn } = require('../lib/updater');
9
+ const {
10
+ CONFIG_DIR,
11
+ CONFIG_FILE,
12
+ PID_FILE,
13
+ TRAY_PID_FILE,
14
+ LOG_FILE,
15
+ VBS_FILE,
16
+ loadConfig,
17
+ saveConfig,
18
+ writePid,
19
+ stopExistingAgent,
20
+ appendLog,
21
+ runSetup,
22
+ uninstallStartup,
23
+ writeStatusFile,
24
+ launchWindowsTray
25
+ } = require('../lib/autostart');
26
+
27
+ function parseArgs(argv) {
28
+ const args = {};
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const token = argv[i];
31
+ if (token.startsWith('--')) {
32
+ const eq = token.indexOf('=');
33
+ if (eq !== -1) {
34
+ args[token.slice(2, eq)] = token.slice(eq + 1);
35
+ } else {
36
+ const key = token.slice(2);
37
+ const next = argv[i + 1];
38
+ if (next && !next.startsWith('--')) {
39
+ args[key] = next;
40
+ i++;
41
+ } else {
42
+ args[key] = true;
43
+ }
44
+ }
45
+ }
46
+ }
47
+ return args;
48
+ }
49
+
50
+ async function main() {
51
+ const rawArgv = process.argv.slice(2);
52
+ const args = parseArgs(rawArgv);
53
+
54
+ if (args.help || args.h) {
55
+ console.log(`
56
+ Lunisphere MCP PC Client v${pkg.version}
57
+ Usage:
58
+ lunisphere-mcp --server="https://mcp.lunisphere.com" --key="dk_..." --dir="." [--allow-shell] [--setup]
59
+ lunisphere-mcp --service
60
+ lunisphere-mcp --uninstall
61
+
62
+ Options:
63
+ --server Relay server base URL (default: https://mcp.lunisphere.com)
64
+ --key Device Key copied from your dashboard
65
+ --dir Workspace directory to expose (default: current directory)
66
+ --allow-shell Enable cmd_execute and bg_* background job tools (off by default)
67
+ --setup Install latest globally, save config, register silent OS startup, and run in background
68
+ --service Run silently using saved configuration (used by OS startup)
69
+ --no-update Skip npm latest version check on startup
70
+ --uninstall Remove OS startup registration and saved config
71
+ `);
72
+ process.exit(0);
73
+ }
74
+
75
+ if (args.uninstall) {
76
+ uninstallStartup();
77
+ process.exit(0);
78
+ }
79
+
80
+ if (args.service) {
81
+ const origLog = console.log;
82
+ const origErr = console.error;
83
+ console.log = (...parts) => appendLog(parts.join(' '));
84
+ console.error = (...parts) => appendLog('[ERR] ' + parts.join(' '));
85
+ console.warn = (...parts) => appendLog('[WARN] ' + parts.join(' '));
86
+ void origLog;
87
+ void origErr;
88
+ }
89
+
90
+ const saved = loadConfig();
91
+ const deviceKey = args.key || (saved && saved.key);
92
+
93
+ if (!deviceKey) {
94
+ console.error('Missing --key. Copy your setup command from https://mcp.lunisphere.com.');
95
+ process.exit(1);
96
+ }
97
+
98
+ const serverUrl = args.server || (saved && saved.server) || 'https://mcp.lunisphere.com';
99
+ const rootDir = path.resolve(args.dir || (saved && saved.dir) || process.cwd());
100
+ const allowShell = args['allow-shell'] !== undefined
101
+ ? Boolean(args['allow-shell'])
102
+ : Boolean(saved && saved.allowShell);
103
+
104
+ if (args.setup) {
105
+ await runSetup({
106
+ serverUrl,
107
+ deviceKey,
108
+ rootDir,
109
+ allowShell,
110
+ currentVersion: pkg.version
111
+ });
112
+ process.exit(0);
113
+ }
114
+
115
+ // Auto-check latest version on startup unless disabled or already respawned
116
+ const updateState = await ensureLatestAndMaybeRespawn({
117
+ currentVersion: pkg.version,
118
+ argv: rawArgv,
119
+ skipUpdate: Boolean(args['no-update'])
120
+ });
121
+ if (updateState.respawning) {
122
+ return;
123
+ }
124
+
125
+ if (args.key && !args.service) {
126
+ saveConfig({
127
+ server: serverUrl,
128
+ key: deviceKey,
129
+ dir: rootDir,
130
+ allowShell,
131
+ autoUpdate: true,
132
+ updatedAt: new Date().toISOString()
133
+ });
134
+ }
135
+
136
+ stopExistingAgent();
137
+ writePid(process.pid);
138
+ writeStatusFile(CONFIG_DIR, { online: false, deviceName: '', toolsCount: 0, pid: process.pid });
139
+
140
+ if (args.service && process.platform === 'win32') {
141
+ launchWindowsTray({
142
+ configDir: CONFIG_DIR,
143
+ configFile: CONFIG_FILE,
144
+ pidFile: PID_FILE,
145
+ trayPidFile: TRAY_PID_FILE,
146
+ logFile: LOG_FILE,
147
+ vbsPath: VBS_FILE
148
+ });
149
+ }
150
+
151
+ console.log('===============================================');
152
+ console.log(` Lunisphere MCP PC Client v${pkg.version}`);
153
+ console.log(` Server: ${serverUrl}`);
154
+ console.log(` Workspace: ${rootDir}`);
155
+ console.log(` Shell: ${allowShell ? 'ENABLED' : 'DISABLED (read/write sandbox only)'}`);
156
+ console.log('===============================================');
157
+
158
+ const toolkit = new LocalToolkit({ rootDir, allowShell });
159
+ const poller = new RelayPoller({
160
+ serverUrl,
161
+ deviceKey,
162
+ toolkit,
163
+ onStatusChange: (status) => writeStatusFile(CONFIG_DIR, { ...status, pid: process.pid })
164
+ });
165
+
166
+ process.on('SIGINT', () => {
167
+ console.log('\n[STOP] Shutting down Lunisphere MCP Client...');
168
+ poller.stop();
169
+ process.exit(0);
170
+ });
171
+
172
+ process.on('SIGTERM', () => {
173
+ poller.stop();
174
+ process.exit(0);
175
+ });
176
+
177
+ poller.start();
178
+ }
179
+
180
+ main().catch((err) => {
181
+ console.error('[FATAL]', err.message);
182
+ process.exit(1);
183
+ });
@@ -0,0 +1,286 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const { execFileSync, spawn } = require('child_process');
7
+ const {
8
+ fetchLatestVersion,
9
+ compareSemver,
10
+ getGlobalCliPath,
11
+ getGlobalInstalledVersion,
12
+ installLatestGlobal
13
+ } = require('./updater');
14
+
15
+ const {
16
+ stopExistingTray,
17
+ writeStatusFile,
18
+ launchWindowsTray
19
+ } = require('./tray');
20
+
21
+ const CONFIG_DIR = path.join(os.homedir(), '.lunisphere-mcp');
22
+ const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
23
+ const PID_FILE = path.join(CONFIG_DIR, 'agent.pid');
24
+ const TRAY_PID_FILE = path.join(CONFIG_DIR, 'tray.pid');
25
+ const LOG_FILE = path.join(CONFIG_DIR, 'agent.log');
26
+ const VBS_FILE = path.join(CONFIG_DIR, 'launch.vbs');
27
+ const TASK_NAME = 'LunisphereMCPRelay';
28
+
29
+ function ensureConfigDir() {
30
+ if (!fs.existsSync(CONFIG_DIR)) {
31
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
32
+ }
33
+ }
34
+
35
+ function saveConfig(cfg) {
36
+ ensureConfigDir();
37
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2), 'utf8');
38
+ }
39
+
40
+ function loadConfig() {
41
+ if (!fs.existsSync(CONFIG_FILE)) return null;
42
+ try {
43
+ return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
44
+ } catch (_) {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ function writePid(pid) {
50
+ ensureConfigDir();
51
+ fs.writeFileSync(PID_FILE, String(pid), 'utf8');
52
+ }
53
+
54
+ function stopExistingAgent() {
55
+ if (!fs.existsSync(PID_FILE)) return;
56
+ try {
57
+ const oldPid = parseInt(fs.readFileSync(PID_FILE, 'utf8').trim(), 10);
58
+ if (oldPid && oldPid !== process.pid) {
59
+ try {
60
+ process.kill(oldPid, 'SIGTERM');
61
+ } catch (_) {}
62
+ }
63
+ } catch (_) {}
64
+ }
65
+
66
+ function appendLog(line) {
67
+ try {
68
+ ensureConfigDir();
69
+ if (fs.existsSync(LOG_FILE) && fs.statSync(LOG_FILE).size > 1024 * 1024) {
70
+ fs.truncateSync(LOG_FILE, 0);
71
+ }
72
+ fs.appendFileSync(LOG_FILE, `${new Date().toISOString()} ${line}\n`, 'utf8');
73
+ } catch (_) {}
74
+ }
75
+
76
+ function installWindowsStartup(cliPath) {
77
+ ensureConfigDir();
78
+ const vbsPath = path.join(CONFIG_DIR, 'launch.vbs');
79
+ const nodePath = process.execPath.replace(/"/g, '""');
80
+ const safeCli = cliPath.replace(/"/g, '""');
81
+ const vbsContent = [
82
+ 'Set sh = CreateObject("WScript.Shell")',
83
+ `sh.Run """${nodePath}"" ""${safeCli}"" --service", 0, False`,
84
+ ''
85
+ ].join('\r\n');
86
+ fs.writeFileSync(vbsPath, vbsContent, 'utf8');
87
+
88
+ const taskCmd = `wscript.exe "${vbsPath}"`;
89
+ let mode = 'user';
90
+
91
+ try {
92
+ execFileSync(
93
+ 'schtasks.exe',
94
+ ['/Create', '/TN', TASK_NAME, '/TR', taskCmd, '/SC', 'ONLOGON', '/RL', 'HIGHEST', '/F'],
95
+ { stdio: 'pipe', windowsHide: true }
96
+ );
97
+ mode = 'admin';
98
+ } catch (_) {
99
+ try {
100
+ execFileSync(
101
+ 'schtasks.exe',
102
+ ['/Create', '/TN', TASK_NAME, '/TR', taskCmd, '/SC', 'ONLOGON', '/F'],
103
+ { stdio: 'pipe', windowsHide: true }
104
+ );
105
+ mode = 'user-task';
106
+ } catch (_) {
107
+ execFileSync(
108
+ 'reg.exe',
109
+ ['ADD', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/V', TASK_NAME, '/T', 'REG_SZ', '/D', taskCmd, '/F'],
110
+ { stdio: 'pipe', windowsHide: true }
111
+ );
112
+ mode = 'user-registry';
113
+ }
114
+ }
115
+
116
+ stopExistingAgent();
117
+ const child = spawn('wscript.exe', [vbsPath], {
118
+ detached: true,
119
+ stdio: 'ignore',
120
+ windowsHide: true
121
+ });
122
+ child.unref();
123
+
124
+ return { mode, vbsPath };
125
+ }
126
+
127
+ function installMacStartup(cliPath) {
128
+ const agentsDir = path.join(os.homedir(), 'Library', 'LaunchAgents');
129
+ if (!fs.existsSync(agentsDir)) fs.mkdirSync(agentsDir, { recursive: true });
130
+ const plistPath = path.join(agentsDir, 'com.lunisphere.mcp.plist');
131
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
132
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
133
+ <plist version="1.0">
134
+ <dict>
135
+ <key>Label</key><string>com.lunisphere.mcp</string>
136
+ <key>ProgramArguments</key>
137
+ <array>
138
+ <string>${process.execPath}</string>
139
+ <string>${cliPath}</string>
140
+ <string>--service</string>
141
+ </array>
142
+ <key>RunAtLoad</key><true/>
143
+ <key>KeepAlive</key><true/>
144
+ <key>StandardOutPath</key><string>${LOG_FILE}</string>
145
+ <key>StandardErrorPath</key><string>${LOG_FILE}</string>
146
+ </dict>
147
+ </plist>
148
+ `;
149
+ fs.writeFileSync(plistPath, plist, 'utf8');
150
+ try { execFileSync('launchctl', ['unload', plistPath], { stdio: 'ignore' }); } catch (_) {}
151
+ execFileSync('launchctl', ['load', '-w', plistPath], { stdio: 'pipe' });
152
+ return { mode: 'launchd', plistPath };
153
+ }
154
+
155
+ function installLinuxStartup(cliPath) {
156
+ const systemdDir = path.join(os.homedir(), '.config', 'systemd', 'user');
157
+ fs.mkdirSync(systemdDir, { recursive: true });
158
+ const unitPath = path.join(systemdDir, 'lunisphere-mcp.service');
159
+ const unit = `[Unit]
160
+ Description=Lunisphere MCP Relay Client
161
+ After=network-online.target
162
+
163
+ [Service]
164
+ ExecStart="${process.execPath}" "${cliPath}" --service
165
+ Restart=always
166
+ RestartSec=5
167
+
168
+ [Install]
169
+ WantedBy=default.target
170
+ `;
171
+ fs.writeFileSync(unitPath, unit, 'utf8');
172
+ try {
173
+ execFileSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' });
174
+ execFileSync('systemctl', ['--user', 'enable', '--now', 'lunisphere-mcp.service'], { stdio: 'pipe' });
175
+ return { mode: 'systemd-user', unitPath };
176
+ } catch (_) {
177
+ stopExistingAgent();
178
+ const out = fs.openSync(LOG_FILE, 'a');
179
+ const child = spawn(process.execPath, [cliPath, '--service'], {
180
+ detached: true,
181
+ stdio: ['ignore', out, out]
182
+ });
183
+ child.unref();
184
+ return { mode: 'background', unitPath };
185
+ }
186
+ }
187
+
188
+ async function runSetup({ serverUrl, deviceKey, rootDir, allowShell, currentVersion }) {
189
+ console.log('[SETUP] Checking latest lunisphere-mcp version on npm...');
190
+ const latest = await fetchLatestVersion('lunisphere-mcp');
191
+ const globalVer = getGlobalInstalledVersion();
192
+ let globalCli = getGlobalCliPath();
193
+
194
+ const needsInstall =
195
+ !globalCli ||
196
+ !globalVer ||
197
+ (latest && compareSemver(latest, globalVer) > 0) ||
198
+ compareSemver(currentVersion, globalVer) > 0;
199
+
200
+ if (needsInstall) {
201
+ const targetVer = latest || currentVersion;
202
+ console.log(`[SETUP] Installing global lunisphere-mcp@${targetVer}...`);
203
+ try {
204
+ globalCli = installLatestGlobal('lunisphere-mcp');
205
+ } catch (err) {
206
+ console.warn(`[SETUP] Global npm install warning: ${err.message}`);
207
+ }
208
+ } else {
209
+ console.log(`[SETUP] Latest version (${globalVer}) is already installed globally.`);
210
+ }
211
+
212
+ const cliPath = globalCli || path.resolve(__dirname, '..', 'bin', 'cli.js');
213
+
214
+ saveConfig({
215
+ server: serverUrl,
216
+ key: deviceKey,
217
+ dir: rootDir,
218
+ allowShell: Boolean(allowShell),
219
+ autoUpdate: true,
220
+ updatedAt: new Date().toISOString()
221
+ });
222
+ console.log(`[SETUP] Configuration saved to ${CONFIG_FILE}`);
223
+
224
+ let startupInfo;
225
+ if (process.platform === 'win32') {
226
+ startupInfo = installWindowsStartup(cliPath);
227
+ } else if (process.platform === 'darwin') {
228
+ startupInfo = installMacStartup(cliPath);
229
+ } else {
230
+ startupInfo = installLinuxStartup(cliPath);
231
+ }
232
+
233
+ if (startupInfo.mode === 'admin') {
234
+ console.log('[STARTUP] Registered silently in Administrator mode (System Tray, zero popups).');
235
+ } else if (process.platform === 'win32') {
236
+ console.log(`[STARTUP] Registered silently in User mode (${startupInfo.mode}, System Tray, zero popups).`);
237
+ console.log('[NOTE] Run once from an Administrator terminal if you want elevated Admin mode on boot.');
238
+ } else {
239
+ console.log(`[STARTUP] Registered background service (${startupInfo.mode}).`);
240
+ }
241
+
242
+ console.log('[SETUP OK] Running in background & System Tray. You can close this window.');
243
+ }
244
+
245
+ function uninstallStartup() {
246
+ stopExistingAgent();
247
+ stopExistingTray(TRAY_PID_FILE);
248
+ if (process.platform === 'win32') {
249
+ try { execFileSync('schtasks.exe', ['/Delete', '/TN', TASK_NAME, '/F'], { stdio: 'ignore', windowsHide: true }); } catch (_) {}
250
+ try {
251
+ execFileSync(
252
+ 'reg.exe',
253
+ ['DELETE', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/V', TASK_NAME, '/F'],
254
+ { stdio: 'ignore', windowsHide: true }
255
+ );
256
+ } catch (_) {}
257
+ } else if (process.platform === 'darwin') {
258
+ const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', 'com.lunisphere.mcp.plist');
259
+ try { execFileSync('launchctl', ['unload', plistPath], { stdio: 'ignore' }); } catch (_) {}
260
+ try { fs.unlinkSync(plistPath); } catch (_) {}
261
+ } else {
262
+ try { execFileSync('systemctl', ['--user', 'disable', '--now', 'lunisphere-mcp.service'], { stdio: 'ignore' }); } catch (_) {}
263
+ }
264
+ if (fs.existsSync(CONFIG_FILE)) fs.unlinkSync(CONFIG_FILE);
265
+ if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE);
266
+ console.log('[UNINSTALL] Startup entry and saved configuration removed.');
267
+ }
268
+
269
+ module.exports = {
270
+ CONFIG_DIR,
271
+ CONFIG_FILE,
272
+ PID_FILE,
273
+ TRAY_PID_FILE,
274
+ LOG_FILE,
275
+ VBS_FILE,
276
+ saveConfig,
277
+ loadConfig,
278
+ writePid,
279
+ stopExistingAgent,
280
+ appendLog,
281
+ runSetup,
282
+ uninstallStartup,
283
+ writeStatusFile,
284
+ launchWindowsTray,
285
+ stopExistingTray
286
+ };
package/lib/poller.js CHANGED
@@ -3,14 +3,23 @@
3
3
  const os = require('os');
4
4
 
5
5
  class RelayPoller {
6
- constructor({ serverUrl, deviceKey, toolkit }) {
6
+ constructor({ serverUrl, deviceKey, toolkit, onStatusChange = null }) {
7
7
  this.serverUrl = serverUrl.replace(/\/+$/, '');
8
8
  this.deviceKey = deviceKey;
9
9
  this.toolkit = toolkit;
10
+ this.onStatusChange = onStatusChange;
10
11
  this.running = false;
11
12
  this.backoffMs = 2000;
12
13
  }
13
14
 
15
+ _notify(online, extra = {}) {
16
+ if (typeof this.onStatusChange === 'function') {
17
+ try {
18
+ this.onStatusChange({ online, ...extra });
19
+ } catch (_) {}
20
+ }
21
+ }
22
+
14
23
  _headers() {
15
24
  return {
16
25
  'Content-Type': 'application/json',
@@ -58,7 +67,9 @@ class RelayPoller {
58
67
  while (this.running) {
59
68
  try {
60
69
  const reg = await this.register();
61
- console.log(`[ONLINE] Connected as "${reg.deviceName}" (${reg.deviceId}) | Tools: ${this.toolkit.getToolSchemas().length}`);
70
+ const toolsCount = this.toolkit.getToolSchemas().length;
71
+ console.log(`[ONLINE] Connected as "${reg.deviceName}" (${reg.deviceId}) | Tools: ${toolsCount}`);
72
+ this._notify(true, { deviceName: reg.deviceName, deviceId: reg.deviceId, toolsCount });
62
73
  this.backoffMs = 2000;
63
74
 
64
75
  while (this.running) {
@@ -95,6 +106,7 @@ class RelayPoller {
95
106
  }
96
107
  } catch (err) {
97
108
  if (!this.running) break;
109
+ this._notify(false, { error: err.message });
98
110
  console.error(`[RECONNECT] ${err.message} — retrying in ${this.backoffMs / 1000}s...`);
99
111
  await new Promise((r) => setTimeout(r, this.backoffMs));
100
112
  this.backoffMs = Math.min(15000, this.backoffMs * 2);
package/lib/tray.js ADDED
@@ -0,0 +1,183 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { spawn } = require('child_process');
6
+
7
+ function buildTrayScript({ configDir, configFile, pidFile, trayPidFile, logFile, vbsPath }) {
8
+ const esc = (p) => String(p).replace(/'/g, "''");
9
+ return `
10
+ Add-Type -AssemblyName System.Windows.Forms
11
+ Add-Type -AssemblyName System.Drawing
12
+
13
+ $ErrorActionPreference = 'SilentlyContinue'
14
+ $configFile = '${esc(configFile)}'
15
+ $statusFile = '${esc(path.join(configDir, 'status.json'))}'
16
+ $pidFile = '${esc(pidFile)}'
17
+ $trayPidFile = '${esc(trayPidFile)}'
18
+ $logFile = '${esc(logFile)}'
19
+ $vbsPath = '${esc(vbsPath)}'
20
+
21
+ Set-Content -Path $trayPidFile -Value $PID
22
+
23
+ function New-BadgeIcon([bool]$isOnline) {
24
+ $bmp = New-Object System.Drawing.Bitmap 16, 16
25
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
26
+ $g.Clear([System.Drawing.Color]::FromArgb(255, 18, 18, 22))
27
+ $borderPen = New-Object System.Drawing.Pen ([System.Drawing.Color]::FromArgb(255, 70, 70, 80)), 1
28
+ $g.DrawRectangle($borderPen, 0, 0, 15, 15)
29
+ $dotBrush = if ($isOnline) {
30
+ New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(255, 34, 197, 94))
31
+ } else {
32
+ New-Object System.Drawing.SolidBrush ([System.Drawing.Color]::FromArgb(255, 234, 179, 8))
33
+ }
34
+ $g.FillEllipse($dotBrush, 4, 4, 8, 8)
35
+ $g.Dispose()
36
+ return [System.Drawing.Icon]::FromHandle($bmp.GetHicon())
37
+ }
38
+
39
+ $iconOnline = New-BadgeIcon $true
40
+ $iconOffline = New-BadgeIcon $false
41
+
42
+ $notify = New-Object System.Windows.Forms.NotifyIcon
43
+ $notify.Icon = $iconOffline
44
+ $notify.Text = 'Lunisphere MCP Relay (Starting...)'
45
+ $notify.Visible = $true
46
+
47
+ $menu = New-Object System.Windows.Forms.ContextMenuStrip
48
+ $statusItem = New-Object System.Windows.Forms.ToolStripMenuItem 'Status: Connecting...'
49
+ $statusItem.Enabled = $false
50
+ $openDashItem = New-Object System.Windows.Forms.ToolStripMenuItem 'Open Dashboard'
51
+ $viewLogItem = New-Object System.Windows.Forms.ToolStripMenuItem 'View Agent Log'
52
+ $restartItem = New-Object System.Windows.Forms.ToolStripMenuItem 'Restart & Check Updates'
53
+ $exitItem = New-Object System.Windows.Forms.ToolStripMenuItem 'Exit'
54
+
55
+ [void]$menu.Items.Add($statusItem)
56
+ [void]$menu.Items.Add((New-Object System.Windows.Forms.ToolStripSeparator))
57
+ [void]$menu.Items.Add($openDashItem)
58
+ [void]$menu.Items.Add($viewLogItem)
59
+ [void]$menu.Items.Add($restartItem)
60
+ [void]$menu.Items.Add((New-Object System.Windows.Forms.ToolStripSeparator))
61
+ [void]$menu.Items.Add($exitItem)
62
+ $notify.ContextMenuStrip = $menu
63
+
64
+ $openDashItem.Add_Click({
65
+ $url = 'https://mcp.lunisphere.com'
66
+ if (Test-Path $configFile) {
67
+ try {
68
+ $cfg = Get-Content $configFile -Raw | ConvertFrom-Json
69
+ if ($cfg.server) { $url = $cfg.server }
70
+ } catch {}
71
+ }
72
+ Start-Process $url
73
+ })
74
+
75
+ $viewLogItem.Add_Click({
76
+ if (Test-Path $logFile) { Start-Process 'notepad.exe' $logFile }
77
+ })
78
+
79
+ $restartItem.Add_Click({
80
+ if (Test-Path $pidFile) {
81
+ $agentPid = [int](Get-Content $pidFile -Raw).Trim()
82
+ if ($agentPid -gt 0) { Stop-Process -Id $agentPid -Force }
83
+ }
84
+ $notify.Visible = $false
85
+ $notify.Dispose()
86
+ if (Test-Path $vbsPath) { Start-Process 'wscript.exe' -ArgumentList "\`"$vbsPath\`"" }
87
+ [System.Windows.Forms.Application]::Exit()
88
+ })
89
+
90
+ $exitItem.Add_Click({
91
+ if (Test-Path $pidFile) {
92
+ $agentPid = [int](Get-Content $pidFile -Raw).Trim()
93
+ if ($agentPid -gt 0) { Stop-Process -Id $agentPid -Force }
94
+ }
95
+ $notify.Visible = $false
96
+ $notify.Dispose()
97
+ Remove-Item -Path $trayPidFile -Force
98
+ [System.Windows.Forms.Application]::Exit()
99
+ })
100
+
101
+ $timer = New-Object System.Windows.Forms.Timer
102
+ $timer.Interval = 2500
103
+ $timer.Add_Tick({
104
+ if (Test-Path $pidFile) {
105
+ $agentPid = [int](Get-Content $pidFile -Raw).Trim()
106
+ $proc = Get-Process -Id $agentPid
107
+ if (-not $proc) {
108
+ $notify.Visible = $false
109
+ $notify.Dispose()
110
+ Remove-Item -Path $trayPidFile -Force
111
+ [System.Windows.Forms.Application]::Exit()
112
+ return
113
+ }
114
+ }
115
+ if (Test-Path $statusFile) {
116
+ try {
117
+ $st = Get-Content $statusFile -Raw | ConvertFrom-Json
118
+ if ($st.online) {
119
+ $notify.Icon = $iconOnline
120
+ $txt = "Lunisphere MCP: Online ($($st.deviceName))"
121
+ if ($txt.Length -gt 63) { $txt = $txt.Substring(0, 63) }
122
+ $notify.Text = $txt
123
+ $statusItem.Text = "Online · $($st.deviceName) ($($st.toolsCount) tools)"
124
+ } else {
125
+ $notify.Icon = $iconOffline
126
+ $notify.Text = 'Lunisphere MCP: Reconnecting...'
127
+ $statusItem.Text = 'Reconnecting...'
128
+ }
129
+ } catch {}
130
+ }
131
+ })
132
+ $timer.Start()
133
+
134
+ [System.Windows.Forms.Application]::Run()
135
+ `;
136
+ }
137
+
138
+ function stopExistingTray(trayPidFile) {
139
+ if (!fs.existsSync(trayPidFile)) return;
140
+ try {
141
+ const oldPid = parseInt(fs.readFileSync(trayPidFile, 'utf8').trim(), 10);
142
+ if (oldPid) {
143
+ try { process.kill(oldPid, 'SIGTERM'); } catch (_) {}
144
+ }
145
+ } catch (_) {}
146
+ }
147
+
148
+ function writeStatusFile(configDir, status) {
149
+ try {
150
+ fs.writeFileSync(
151
+ path.join(configDir, 'status.json'),
152
+ JSON.stringify({ ...status, updatedAt: new Date().toISOString() }),
153
+ 'utf8'
154
+ );
155
+ } catch (_) {}
156
+ }
157
+
158
+ function launchWindowsTray({ configDir, configFile, pidFile, trayPidFile, logFile, vbsPath }) {
159
+ if (process.platform !== 'win32') return;
160
+ stopExistingTray(trayPidFile);
161
+ const psPath = path.join(configDir, 'tray.ps1');
162
+ fs.writeFileSync(
163
+ psPath,
164
+ buildTrayScript({ configDir, configFile, pidFile, trayPidFile, logFile, vbsPath }),
165
+ 'utf8'
166
+ );
167
+ const child = spawn(
168
+ 'powershell.exe',
169
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-File', psPath],
170
+ {
171
+ detached: true,
172
+ stdio: 'ignore',
173
+ windowsHide: true
174
+ }
175
+ );
176
+ child.unref();
177
+ }
178
+
179
+ module.exports = {
180
+ stopExistingTray,
181
+ writeStatusFile,
182
+ launchWindowsTray
183
+ };
package/lib/updater.js ADDED
@@ -0,0 +1,112 @@
1
+ 'use strict';
2
+
3
+ const { execFileSync, spawn } = require('child_process');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ function compareSemver(a, b) {
8
+ const pa = String(a || '0.0.0').replace(/^v/, '').split('.').map((n) => parseInt(n, 10) || 0);
9
+ const pb = String(b || '0.0.0').replace(/^v/, '').split('.').map((n) => parseInt(n, 10) || 0);
10
+ for (let i = 0; i < 3; i++) {
11
+ if ((pa[i] || 0) > (pb[i] || 0)) return 1;
12
+ if ((pa[i] || 0) < (pb[i] || 0)) return -1;
13
+ }
14
+ return 0;
15
+ }
16
+
17
+ function getNpmBin() {
18
+ return process.platform === 'win32' ? 'npm.cmd' : 'npm';
19
+ }
20
+
21
+ function getGlobalCliPath() {
22
+ try {
23
+ const npmRoot = execFileSync(getNpmBin(), ['root', '-g'], {
24
+ encoding: 'utf8',
25
+ timeout: 8000,
26
+ windowsHide: true,
27
+ shell: process.platform === 'win32'
28
+ }).trim();
29
+ const candidate = path.join(npmRoot, 'lunisphere-mcp', 'bin', 'cli.js');
30
+ if (fs.existsSync(candidate)) return candidate;
31
+ } catch (_) {}
32
+ return null;
33
+ }
34
+
35
+ function getGlobalInstalledVersion() {
36
+ try {
37
+ const cliPath = getGlobalCliPath();
38
+ if (!cliPath) return null;
39
+ const pkgPath = path.resolve(path.dirname(cliPath), '..', 'package.json');
40
+ if (!fs.existsSync(pkgPath)) return null;
41
+ return JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version || null;
42
+ } catch (_) {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ async function fetchLatestVersion(pkgName = 'lunisphere-mcp') {
48
+ const controller = new AbortController();
49
+ const timer = setTimeout(() => controller.abort(), 4500);
50
+ try {
51
+ const res = await fetch(`https://registry.npmjs.org/${pkgName}/latest`, {
52
+ signal: controller.signal,
53
+ headers: { Accept: 'application/json' }
54
+ });
55
+ if (!res.ok) return null;
56
+ const data = await res.json();
57
+ return data && data.version ? String(data.version).trim() : null;
58
+ } catch (_) {
59
+ return null;
60
+ } finally {
61
+ clearTimeout(timer);
62
+ }
63
+ }
64
+
65
+ function installLatestGlobal(pkgName = 'lunisphere-mcp') {
66
+ execFileSync(getNpmBin(), ['install', '-g', `${pkgName}@latest`], {
67
+ stdio: 'pipe',
68
+ timeout: 60000,
69
+ windowsHide: true,
70
+ shell: process.platform === 'win32'
71
+ });
72
+ return getGlobalCliPath();
73
+ }
74
+
75
+ async function ensureLatestAndMaybeRespawn({ currentVersion, argv, skipUpdate }) {
76
+ if (skipUpdate) return { updated: false };
77
+ const latest = await fetchLatestVersion('lunisphere-mcp');
78
+ if (!latest || compareSemver(latest, currentVersion) <= 0) {
79
+ return { updated: false, latest };
80
+ }
81
+
82
+ console.log(`[UPDATE] New version ${latest} found (current ${currentVersion}). Updating...`);
83
+ try {
84
+ const globalCli = installLatestGlobal('lunisphere-mcp');
85
+ const targetScript = globalCli || path.resolve(__dirname, '..', 'bin', 'cli.js');
86
+ const nextArgs = [targetScript, ...argv.filter((a) => a !== '--no-update'), '--no-update'];
87
+ const isService = argv.includes('--service');
88
+ const child = spawn(process.execPath, nextArgs, {
89
+ stdio: isService ? 'ignore' : 'inherit',
90
+ detached: isService,
91
+ windowsHide: isService
92
+ });
93
+ if (isService) {
94
+ child.unref();
95
+ process.exit(0);
96
+ }
97
+ child.on('exit', (code) => process.exit(code == null ? 0 : code));
98
+ return { updated: true, respawning: true, latest };
99
+ } catch (err) {
100
+ console.warn(`[UPDATE] Auto-update failed (${err.message}); continuing on ${currentVersion}.`);
101
+ return { updated: false, error: err.message };
102
+ }
103
+ }
104
+
105
+ module.exports = {
106
+ compareSemver,
107
+ fetchLatestVersion,
108
+ getGlobalCliPath,
109
+ getGlobalInstalledVersion,
110
+ installLatestGlobal,
111
+ ensureLatestAndMaybeRespawn
112
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lunisphere-mcp",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Local PC agent for Lunisphere MCP Relay — connect your local workspace to Gemini, Claude, or Cursor with zero tunnel setup.",
5
5
  "bin": {
6
6
  "lunisphere-mcp": "bin/cli.js"