lunisphere-mcp 0.0.0-stage → 1.1.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 +22 -2
- package/bin/cli.js +158 -0
- package/lib/autostart.js +271 -0
- package/lib/poller.js +110 -0
- package/lib/tools.js +346 -0
- package/lib/updater.js +112 -0
- package/package.json +33 -4
package/README.md
CHANGED
|
@@ -1,3 +1,23 @@
|
|
|
1
|
-
#
|
|
1
|
+
# lunisphere-mcp
|
|
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
|
+
|
|
5
|
+
## One-Command Auto-Setup & Startup
|
|
6
|
+
|
|
7
|
+
Run once in your workspace folder (run from an **Administrator terminal** on Windows to register silent elevated startup without future UAC prompts):
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx -y lunisphere-mcp@latest --server="https://mcp.lunisphere.com" --key="YOUR_DEVICE_KEY" --dir="." --allow-shell --setup
|
|
11
|
+
```
|
|
12
|
+
|
|
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
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
lunisphere-mcp --uninstall
|
|
23
|
+
```
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
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
|
+
loadConfig,
|
|
11
|
+
saveConfig,
|
|
12
|
+
writePid,
|
|
13
|
+
stopExistingAgent,
|
|
14
|
+
appendLog,
|
|
15
|
+
runSetup,
|
|
16
|
+
uninstallStartup
|
|
17
|
+
} = require('../lib/autostart');
|
|
18
|
+
|
|
19
|
+
function parseArgs(argv) {
|
|
20
|
+
const args = {};
|
|
21
|
+
for (let i = 0; i < argv.length; i++) {
|
|
22
|
+
const token = argv[i];
|
|
23
|
+
if (token.startsWith('--')) {
|
|
24
|
+
const eq = token.indexOf('=');
|
|
25
|
+
if (eq !== -1) {
|
|
26
|
+
args[token.slice(2, eq)] = token.slice(eq + 1);
|
|
27
|
+
} else {
|
|
28
|
+
const key = token.slice(2);
|
|
29
|
+
const next = argv[i + 1];
|
|
30
|
+
if (next && !next.startsWith('--')) {
|
|
31
|
+
args[key] = next;
|
|
32
|
+
i++;
|
|
33
|
+
} else {
|
|
34
|
+
args[key] = true;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return args;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function main() {
|
|
43
|
+
const rawArgv = process.argv.slice(2);
|
|
44
|
+
const args = parseArgs(rawArgv);
|
|
45
|
+
|
|
46
|
+
if (args.help || args.h) {
|
|
47
|
+
console.log(`
|
|
48
|
+
Lunisphere MCP PC Client v${pkg.version}
|
|
49
|
+
Usage:
|
|
50
|
+
lunisphere-mcp --server="https://mcp.lunisphere.com" --key="dk_..." --dir="." [--allow-shell] [--setup]
|
|
51
|
+
lunisphere-mcp --service
|
|
52
|
+
lunisphere-mcp --uninstall
|
|
53
|
+
|
|
54
|
+
Options:
|
|
55
|
+
--server Relay server base URL (default: https://mcp.lunisphere.com)
|
|
56
|
+
--key Device Key copied from your dashboard
|
|
57
|
+
--dir Workspace directory to expose (default: current directory)
|
|
58
|
+
--allow-shell Enable cmd_execute and bg_* background job tools (off by default)
|
|
59
|
+
--setup Install latest globally, save config, register silent OS startup, and run in background
|
|
60
|
+
--service Run silently using saved configuration (used by OS startup)
|
|
61
|
+
--no-update Skip npm latest version check on startup
|
|
62
|
+
--uninstall Remove OS startup registration and saved config
|
|
63
|
+
`);
|
|
64
|
+
process.exit(0);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (args.uninstall) {
|
|
68
|
+
uninstallStartup();
|
|
69
|
+
process.exit(0);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (args.service) {
|
|
73
|
+
const origLog = console.log;
|
|
74
|
+
const origErr = console.error;
|
|
75
|
+
console.log = (...parts) => appendLog(parts.join(' '));
|
|
76
|
+
console.error = (...parts) => appendLog('[ERR] ' + parts.join(' '));
|
|
77
|
+
console.warn = (...parts) => appendLog('[WARN] ' + parts.join(' '));
|
|
78
|
+
void origLog;
|
|
79
|
+
void origErr;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const saved = loadConfig();
|
|
83
|
+
const deviceKey = args.key || (saved && saved.key);
|
|
84
|
+
|
|
85
|
+
if (!deviceKey) {
|
|
86
|
+
console.error('Missing --key. Copy your setup command from https://mcp.lunisphere.com.');
|
|
87
|
+
process.exit(1);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const serverUrl = args.server || (saved && saved.server) || 'https://mcp.lunisphere.com';
|
|
91
|
+
const rootDir = path.resolve(args.dir || (saved && saved.dir) || process.cwd());
|
|
92
|
+
const allowShell = args['allow-shell'] !== undefined
|
|
93
|
+
? Boolean(args['allow-shell'])
|
|
94
|
+
: Boolean(saved && saved.allowShell);
|
|
95
|
+
|
|
96
|
+
if (args.setup) {
|
|
97
|
+
await runSetup({
|
|
98
|
+
serverUrl,
|
|
99
|
+
deviceKey,
|
|
100
|
+
rootDir,
|
|
101
|
+
allowShell,
|
|
102
|
+
currentVersion: pkg.version
|
|
103
|
+
});
|
|
104
|
+
process.exit(0);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Auto-check latest version on startup unless disabled or already respawned
|
|
108
|
+
const updateState = await ensureLatestAndMaybeRespawn({
|
|
109
|
+
currentVersion: pkg.version,
|
|
110
|
+
argv: rawArgv,
|
|
111
|
+
skipUpdate: Boolean(args['no-update'])
|
|
112
|
+
});
|
|
113
|
+
if (updateState.respawning) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (args.key && !args.service) {
|
|
118
|
+
saveConfig({
|
|
119
|
+
server: serverUrl,
|
|
120
|
+
key: deviceKey,
|
|
121
|
+
dir: rootDir,
|
|
122
|
+
allowShell,
|
|
123
|
+
autoUpdate: true,
|
|
124
|
+
updatedAt: new Date().toISOString()
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
stopExistingAgent();
|
|
129
|
+
writePid(process.pid);
|
|
130
|
+
|
|
131
|
+
console.log('===============================================');
|
|
132
|
+
console.log(` Lunisphere MCP PC Client v${pkg.version}`);
|
|
133
|
+
console.log(` Server: ${serverUrl}`);
|
|
134
|
+
console.log(` Workspace: ${rootDir}`);
|
|
135
|
+
console.log(` Shell: ${allowShell ? 'ENABLED' : 'DISABLED (read/write sandbox only)'}`);
|
|
136
|
+
console.log('===============================================');
|
|
137
|
+
|
|
138
|
+
const toolkit = new LocalToolkit({ rootDir, allowShell });
|
|
139
|
+
const poller = new RelayPoller({ serverUrl, deviceKey, toolkit });
|
|
140
|
+
|
|
141
|
+
process.on('SIGINT', () => {
|
|
142
|
+
console.log('\n[STOP] Shutting down Lunisphere MCP Client...');
|
|
143
|
+
poller.stop();
|
|
144
|
+
process.exit(0);
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
process.on('SIGTERM', () => {
|
|
148
|
+
poller.stop();
|
|
149
|
+
process.exit(0);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
poller.start();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
main().catch((err) => {
|
|
156
|
+
console.error('[FATAL]', err.message);
|
|
157
|
+
process.exit(1);
|
|
158
|
+
});
|
package/lib/autostart.js
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
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 CONFIG_DIR = path.join(os.homedir(), '.lunisphere-mcp');
|
|
16
|
+
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
|
17
|
+
const PID_FILE = path.join(CONFIG_DIR, 'agent.pid');
|
|
18
|
+
const LOG_FILE = path.join(CONFIG_DIR, 'agent.log');
|
|
19
|
+
const TASK_NAME = 'LunisphereMCPRelay';
|
|
20
|
+
|
|
21
|
+
function ensureConfigDir() {
|
|
22
|
+
if (!fs.existsSync(CONFIG_DIR)) {
|
|
23
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function saveConfig(cfg) {
|
|
28
|
+
ensureConfigDir();
|
|
29
|
+
fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2), 'utf8');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function loadConfig() {
|
|
33
|
+
if (!fs.existsSync(CONFIG_FILE)) return null;
|
|
34
|
+
try {
|
|
35
|
+
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
|
|
36
|
+
} catch (_) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function writePid(pid) {
|
|
42
|
+
ensureConfigDir();
|
|
43
|
+
fs.writeFileSync(PID_FILE, String(pid), 'utf8');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function stopExistingAgent() {
|
|
47
|
+
if (!fs.existsSync(PID_FILE)) return;
|
|
48
|
+
try {
|
|
49
|
+
const oldPid = parseInt(fs.readFileSync(PID_FILE, 'utf8').trim(), 10);
|
|
50
|
+
if (oldPid && oldPid !== process.pid) {
|
|
51
|
+
try {
|
|
52
|
+
process.kill(oldPid, 'SIGTERM');
|
|
53
|
+
} catch (_) {}
|
|
54
|
+
}
|
|
55
|
+
} catch (_) {}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function appendLog(line) {
|
|
59
|
+
try {
|
|
60
|
+
ensureConfigDir();
|
|
61
|
+
if (fs.existsSync(LOG_FILE) && fs.statSync(LOG_FILE).size > 1024 * 1024) {
|
|
62
|
+
fs.truncateSync(LOG_FILE, 0);
|
|
63
|
+
}
|
|
64
|
+
fs.appendFileSync(LOG_FILE, `${new Date().toISOString()} ${line}\n`, 'utf8');
|
|
65
|
+
} catch (_) {}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function installWindowsStartup(cliPath) {
|
|
69
|
+
ensureConfigDir();
|
|
70
|
+
const vbsPath = path.join(CONFIG_DIR, 'launch.vbs');
|
|
71
|
+
const nodePath = process.execPath.replace(/"/g, '""');
|
|
72
|
+
const safeCli = cliPath.replace(/"/g, '""');
|
|
73
|
+
const vbsContent = [
|
|
74
|
+
'Set sh = CreateObject("WScript.Shell")',
|
|
75
|
+
`sh.Run """${nodePath}"" ""${safeCli}"" --service", 0, False`,
|
|
76
|
+
''
|
|
77
|
+
].join('\r\n');
|
|
78
|
+
fs.writeFileSync(vbsPath, vbsContent, 'utf8');
|
|
79
|
+
|
|
80
|
+
const taskCmd = `wscript.exe "${vbsPath}"`;
|
|
81
|
+
let mode = 'user';
|
|
82
|
+
|
|
83
|
+
try {
|
|
84
|
+
execFileSync(
|
|
85
|
+
'schtasks.exe',
|
|
86
|
+
['/Create', '/TN', TASK_NAME, '/TR', taskCmd, '/SC', 'ONLOGON', '/RL', 'HIGHEST', '/F'],
|
|
87
|
+
{ stdio: 'pipe', windowsHide: true }
|
|
88
|
+
);
|
|
89
|
+
mode = 'admin';
|
|
90
|
+
} catch (_) {
|
|
91
|
+
try {
|
|
92
|
+
execFileSync(
|
|
93
|
+
'schtasks.exe',
|
|
94
|
+
['/Create', '/TN', TASK_NAME, '/TR', taskCmd, '/SC', 'ONLOGON', '/F'],
|
|
95
|
+
{ stdio: 'pipe', windowsHide: true }
|
|
96
|
+
);
|
|
97
|
+
mode = 'user-task';
|
|
98
|
+
} catch (_) {
|
|
99
|
+
execFileSync(
|
|
100
|
+
'reg.exe',
|
|
101
|
+
['ADD', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/V', TASK_NAME, '/T', 'REG_SZ', '/D', taskCmd, '/F'],
|
|
102
|
+
{ stdio: 'pipe', windowsHide: true }
|
|
103
|
+
);
|
|
104
|
+
mode = 'user-registry';
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
stopExistingAgent();
|
|
109
|
+
const child = spawn('wscript.exe', [vbsPath], {
|
|
110
|
+
detached: true,
|
|
111
|
+
stdio: 'ignore',
|
|
112
|
+
windowsHide: true
|
|
113
|
+
});
|
|
114
|
+
child.unref();
|
|
115
|
+
|
|
116
|
+
return { mode, vbsPath };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function installMacStartup(cliPath) {
|
|
120
|
+
const agentsDir = path.join(os.homedir(), 'Library', 'LaunchAgents');
|
|
121
|
+
if (!fs.existsSync(agentsDir)) fs.mkdirSync(agentsDir, { recursive: true });
|
|
122
|
+
const plistPath = path.join(agentsDir, 'com.lunisphere.mcp.plist');
|
|
123
|
+
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
124
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
125
|
+
<plist version="1.0">
|
|
126
|
+
<dict>
|
|
127
|
+
<key>Label</key><string>com.lunisphere.mcp</string>
|
|
128
|
+
<key>ProgramArguments</key>
|
|
129
|
+
<array>
|
|
130
|
+
<string>${process.execPath}</string>
|
|
131
|
+
<string>${cliPath}</string>
|
|
132
|
+
<string>--service</string>
|
|
133
|
+
</array>
|
|
134
|
+
<key>RunAtLoad</key><true/>
|
|
135
|
+
<key>KeepAlive</key><true/>
|
|
136
|
+
<key>StandardOutPath</key><string>${LOG_FILE}</string>
|
|
137
|
+
<key>StandardErrorPath</key><string>${LOG_FILE}</string>
|
|
138
|
+
</dict>
|
|
139
|
+
</plist>
|
|
140
|
+
`;
|
|
141
|
+
fs.writeFileSync(plistPath, plist, 'utf8');
|
|
142
|
+
try { execFileSync('launchctl', ['unload', plistPath], { stdio: 'ignore' }); } catch (_) {}
|
|
143
|
+
execFileSync('launchctl', ['load', '-w', plistPath], { stdio: 'pipe' });
|
|
144
|
+
return { mode: 'launchd', plistPath };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function installLinuxStartup(cliPath) {
|
|
148
|
+
const systemdDir = path.join(os.homedir(), '.config', 'systemd', 'user');
|
|
149
|
+
fs.mkdirSync(systemdDir, { recursive: true });
|
|
150
|
+
const unitPath = path.join(systemdDir, 'lunisphere-mcp.service');
|
|
151
|
+
const unit = `[Unit]
|
|
152
|
+
Description=Lunisphere MCP Relay Client
|
|
153
|
+
After=network-online.target
|
|
154
|
+
|
|
155
|
+
[Service]
|
|
156
|
+
ExecStart="${process.execPath}" "${cliPath}" --service
|
|
157
|
+
Restart=always
|
|
158
|
+
RestartSec=5
|
|
159
|
+
|
|
160
|
+
[Install]
|
|
161
|
+
WantedBy=default.target
|
|
162
|
+
`;
|
|
163
|
+
fs.writeFileSync(unitPath, unit, 'utf8');
|
|
164
|
+
try {
|
|
165
|
+
execFileSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' });
|
|
166
|
+
execFileSync('systemctl', ['--user', 'enable', '--now', 'lunisphere-mcp.service'], { stdio: 'pipe' });
|
|
167
|
+
return { mode: 'systemd-user', unitPath };
|
|
168
|
+
} catch (_) {
|
|
169
|
+
stopExistingAgent();
|
|
170
|
+
const out = fs.openSync(LOG_FILE, 'a');
|
|
171
|
+
const child = spawn(process.execPath, [cliPath, '--service'], {
|
|
172
|
+
detached: true,
|
|
173
|
+
stdio: ['ignore', out, out]
|
|
174
|
+
});
|
|
175
|
+
child.unref();
|
|
176
|
+
return { mode: 'background', unitPath };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function runSetup({ serverUrl, deviceKey, rootDir, allowShell, currentVersion }) {
|
|
181
|
+
console.log('[SETUP] Checking latest lunisphere-mcp version on npm...');
|
|
182
|
+
const latest = await fetchLatestVersion('lunisphere-mcp');
|
|
183
|
+
const globalVer = getGlobalInstalledVersion();
|
|
184
|
+
let globalCli = getGlobalCliPath();
|
|
185
|
+
|
|
186
|
+
const needsInstall =
|
|
187
|
+
!globalCli ||
|
|
188
|
+
!globalVer ||
|
|
189
|
+
(latest && compareSemver(latest, globalVer) > 0) ||
|
|
190
|
+
compareSemver(currentVersion, globalVer) > 0;
|
|
191
|
+
|
|
192
|
+
if (needsInstall) {
|
|
193
|
+
const targetVer = latest || currentVersion;
|
|
194
|
+
console.log(`[SETUP] Installing global lunisphere-mcp@${targetVer}...`);
|
|
195
|
+
try {
|
|
196
|
+
globalCli = installLatestGlobal('lunisphere-mcp');
|
|
197
|
+
} catch (err) {
|
|
198
|
+
console.warn(`[SETUP] Global npm install warning: ${err.message}`);
|
|
199
|
+
}
|
|
200
|
+
} else {
|
|
201
|
+
console.log(`[SETUP] Latest version (${globalVer}) is already installed globally.`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const cliPath = globalCli || path.resolve(__dirname, '..', 'bin', 'cli.js');
|
|
205
|
+
|
|
206
|
+
saveConfig({
|
|
207
|
+
server: serverUrl,
|
|
208
|
+
key: deviceKey,
|
|
209
|
+
dir: rootDir,
|
|
210
|
+
allowShell: Boolean(allowShell),
|
|
211
|
+
autoUpdate: true,
|
|
212
|
+
updatedAt: new Date().toISOString()
|
|
213
|
+
});
|
|
214
|
+
console.log(`[SETUP] Configuration saved to ${CONFIG_FILE}`);
|
|
215
|
+
|
|
216
|
+
let startupInfo;
|
|
217
|
+
if (process.platform === 'win32') {
|
|
218
|
+
startupInfo = installWindowsStartup(cliPath);
|
|
219
|
+
} else if (process.platform === 'darwin') {
|
|
220
|
+
startupInfo = installMacStartup(cliPath);
|
|
221
|
+
} else {
|
|
222
|
+
startupInfo = installLinuxStartup(cliPath);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (startupInfo.mode === 'admin') {
|
|
226
|
+
console.log('[STARTUP] Registered silently in Administrator mode (zero popups on boot).');
|
|
227
|
+
} else if (process.platform === 'win32') {
|
|
228
|
+
console.log(`[STARTUP] Registered silently in User mode (${startupInfo.mode}, zero popups on boot).`);
|
|
229
|
+
console.log('[NOTE] Run this setup command once from an Administrator terminal if you want elevated Admin mode on boot.');
|
|
230
|
+
} else {
|
|
231
|
+
console.log(`[STARTUP] Registered background service (${startupInfo.mode}).`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
console.log(`[ONLINE] Background agent started. Log: ${LOG_FILE}`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function uninstallStartup() {
|
|
238
|
+
stopExistingAgent();
|
|
239
|
+
if (process.platform === 'win32') {
|
|
240
|
+
try { execFileSync('schtasks.exe', ['/Delete', '/TN', TASK_NAME, '/F'], { stdio: 'ignore', windowsHide: true }); } catch (_) {}
|
|
241
|
+
try {
|
|
242
|
+
execFileSync(
|
|
243
|
+
'reg.exe',
|
|
244
|
+
['DELETE', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/V', TASK_NAME, '/F'],
|
|
245
|
+
{ stdio: 'ignore', windowsHide: true }
|
|
246
|
+
);
|
|
247
|
+
} catch (_) {}
|
|
248
|
+
} else if (process.platform === 'darwin') {
|
|
249
|
+
const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', 'com.lunisphere.mcp.plist');
|
|
250
|
+
try { execFileSync('launchctl', ['unload', plistPath], { stdio: 'ignore' }); } catch (_) {}
|
|
251
|
+
try { fs.unlinkSync(plistPath); } catch (_) {}
|
|
252
|
+
} else {
|
|
253
|
+
try { execFileSync('systemctl', ['--user', 'disable', '--now', 'lunisphere-mcp.service'], { stdio: 'ignore' }); } catch (_) {}
|
|
254
|
+
}
|
|
255
|
+
if (fs.existsSync(CONFIG_FILE)) fs.unlinkSync(CONFIG_FILE);
|
|
256
|
+
if (fs.existsSync(PID_FILE)) fs.unlinkSync(PID_FILE);
|
|
257
|
+
console.log('[UNINSTALL] Startup entry and saved configuration removed.');
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
module.exports = {
|
|
261
|
+
CONFIG_DIR,
|
|
262
|
+
CONFIG_FILE,
|
|
263
|
+
LOG_FILE,
|
|
264
|
+
saveConfig,
|
|
265
|
+
loadConfig,
|
|
266
|
+
writePid,
|
|
267
|
+
stopExistingAgent,
|
|
268
|
+
appendLog,
|
|
269
|
+
runSetup,
|
|
270
|
+
uninstallStartup
|
|
271
|
+
};
|
package/lib/poller.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const os = require('os');
|
|
4
|
+
|
|
5
|
+
class RelayPoller {
|
|
6
|
+
constructor({ serverUrl, deviceKey, toolkit }) {
|
|
7
|
+
this.serverUrl = serverUrl.replace(/\/+$/, '');
|
|
8
|
+
this.deviceKey = deviceKey;
|
|
9
|
+
this.toolkit = toolkit;
|
|
10
|
+
this.running = false;
|
|
11
|
+
this.backoffMs = 2000;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
_headers() {
|
|
15
|
+
return {
|
|
16
|
+
'Content-Type': 'application/json',
|
|
17
|
+
'X-Device-Key': this.deviceKey
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async register() {
|
|
22
|
+
const res = await fetch(`${this.serverUrl}/relay/register`, {
|
|
23
|
+
method: 'POST',
|
|
24
|
+
headers: this._headers(),
|
|
25
|
+
body: JSON.stringify({
|
|
26
|
+
tools: this.toolkit.getToolSchemas(),
|
|
27
|
+
meta: {
|
|
28
|
+
hostname: os.hostname(),
|
|
29
|
+
platform: os.platform(),
|
|
30
|
+
rootDir: this.toolkit.rootDir,
|
|
31
|
+
allowShell: this.toolkit.allowShell
|
|
32
|
+
}
|
|
33
|
+
})
|
|
34
|
+
});
|
|
35
|
+
const data = await res.json().catch(() => ({}));
|
|
36
|
+
if (!res.ok) {
|
|
37
|
+
throw new Error(data.error || `Register failed (${res.status})`);
|
|
38
|
+
}
|
|
39
|
+
return data;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async _executeAndReport(job) {
|
|
43
|
+
console.log(`[JOB] ${job.jobId} -> ${job.toolName}`);
|
|
44
|
+
const result = await this.toolkit.execute(job.toolName, job.arguments || {});
|
|
45
|
+
try {
|
|
46
|
+
await fetch(`${this.serverUrl}/relay/result`, {
|
|
47
|
+
method: 'POST',
|
|
48
|
+
headers: this._headers(),
|
|
49
|
+
body: JSON.stringify({ jobId: job.jobId, result })
|
|
50
|
+
});
|
|
51
|
+
} catch (err) {
|
|
52
|
+
console.error(`[ERROR] Failed to post result for ${job.jobId}:`, err.message);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async start() {
|
|
57
|
+
this.running = true;
|
|
58
|
+
while (this.running) {
|
|
59
|
+
try {
|
|
60
|
+
const reg = await this.register();
|
|
61
|
+
console.log(`[ONLINE] Connected as "${reg.deviceName}" (${reg.deviceId}) | Tools: ${this.toolkit.getToolSchemas().length}`);
|
|
62
|
+
this.backoffMs = 2000;
|
|
63
|
+
|
|
64
|
+
while (this.running) {
|
|
65
|
+
const controller = new AbortController();
|
|
66
|
+
const timeout = setTimeout(() => controller.abort(), 30000);
|
|
67
|
+
try {
|
|
68
|
+
const res = await fetch(`${this.serverUrl}/relay/poll`, {
|
|
69
|
+
method: 'GET',
|
|
70
|
+
headers: this._headers(),
|
|
71
|
+
signal: controller.signal
|
|
72
|
+
});
|
|
73
|
+
clearTimeout(timeout);
|
|
74
|
+
|
|
75
|
+
if (res.status === 401 || res.status === 403) {
|
|
76
|
+
const errData = await res.json().catch(() => ({}));
|
|
77
|
+
console.error(`[AUTH] ${errData.error || 'Key rejected'}. Stopping client.`);
|
|
78
|
+
this.running = false;
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (!res.ok) {
|
|
82
|
+
throw new Error(`Poll HTTP ${res.status}`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const payload = await res.json();
|
|
86
|
+
if (Array.isArray(payload.jobs) && payload.jobs.length > 0) {
|
|
87
|
+
for (const job of payload.jobs) {
|
|
88
|
+
this._executeAndReport(job);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
} catch (pollErr) {
|
|
92
|
+
clearTimeout(timeout);
|
|
93
|
+
throw pollErr;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
} catch (err) {
|
|
97
|
+
if (!this.running) break;
|
|
98
|
+
console.error(`[RECONNECT] ${err.message} — retrying in ${this.backoffMs / 1000}s...`);
|
|
99
|
+
await new Promise((r) => setTimeout(r, this.backoffMs));
|
|
100
|
+
this.backoffMs = Math.min(15000, this.backoffMs * 2);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
stop() {
|
|
106
|
+
this.running = false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
module.exports = { RelayPoller };
|
package/lib/tools.js
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const os = require('os');
|
|
6
|
+
const crypto = require('crypto');
|
|
7
|
+
const { exec, spawn } = require('child_process');
|
|
8
|
+
|
|
9
|
+
class LocalToolkit {
|
|
10
|
+
constructor({ rootDir, allowShell = false }) {
|
|
11
|
+
this.rootDir = path.resolve(rootDir || process.cwd());
|
|
12
|
+
this.allowShell = Boolean(allowShell);
|
|
13
|
+
this.bgJobs = new Map();
|
|
14
|
+
this.bgLogDir = path.join(os.tmpdir(), 'lunisphere-mcp-jobs');
|
|
15
|
+
if (!fs.existsSync(this.bgLogDir)) fs.mkdirSync(this.bgLogDir, { recursive: true });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
_resolveSafe(targetPath) {
|
|
19
|
+
const resolved = path.resolve(this.rootDir, targetPath || '.');
|
|
20
|
+
const normRoot = this.rootDir.toLowerCase();
|
|
21
|
+
const normTarget = resolved.toLowerCase();
|
|
22
|
+
if (normTarget !== normRoot && !normTarget.startsWith(normRoot + path.sep)) {
|
|
23
|
+
throw new Error(`Access denied: path escapes sandbox root (${this.rootDir})`);
|
|
24
|
+
}
|
|
25
|
+
return resolved;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
getToolSchemas() {
|
|
29
|
+
const tools = [
|
|
30
|
+
{
|
|
31
|
+
name: 'fs_read_file',
|
|
32
|
+
description: 'Reads full content or specified line range of a file inside the workspace.',
|
|
33
|
+
inputSchema: {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
path: { type: 'string', description: 'Relative or absolute path inside workspace.' },
|
|
37
|
+
start_line: { type: 'integer', description: 'Optional 1-based start line.' },
|
|
38
|
+
end_line: { type: 'integer', description: 'Optional 1-based end line.' }
|
|
39
|
+
},
|
|
40
|
+
required: ['path']
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
name: 'fs_write_file',
|
|
45
|
+
description: 'Writes or appends content to a file inside the workspace.',
|
|
46
|
+
inputSchema: {
|
|
47
|
+
type: 'object',
|
|
48
|
+
properties: {
|
|
49
|
+
path: { type: 'string' },
|
|
50
|
+
content: { type: 'string' },
|
|
51
|
+
append: { type: 'boolean', default: false }
|
|
52
|
+
},
|
|
53
|
+
required: ['path', 'content']
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
name: 'fs_list_directory',
|
|
58
|
+
description: 'Lists files and folders inside the workspace (max depth 2 recommended).',
|
|
59
|
+
inputSchema: {
|
|
60
|
+
type: 'object',
|
|
61
|
+
properties: {
|
|
62
|
+
path: { type: 'string', default: '.' },
|
|
63
|
+
depth: { type: 'integer', default: 1 }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
name: 'fs_search_files',
|
|
69
|
+
description: 'Searches filenames and optional text content inside a subfolder.',
|
|
70
|
+
inputSchema: {
|
|
71
|
+
type: 'object',
|
|
72
|
+
properties: {
|
|
73
|
+
path: { type: 'string', default: '.' },
|
|
74
|
+
pattern: { type: 'string', default: '' },
|
|
75
|
+
content_search: { type: 'string', default: '' }
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
name: 'fs_delete_file_or_dir',
|
|
81
|
+
description: 'Deletes a file or directory inside the workspace.',
|
|
82
|
+
inputSchema: {
|
|
83
|
+
type: 'object',
|
|
84
|
+
properties: {
|
|
85
|
+
path: { type: 'string' },
|
|
86
|
+
recursive: { type: 'boolean', default: false }
|
|
87
|
+
},
|
|
88
|
+
required: ['path']
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
name: 'fs_create_directory',
|
|
93
|
+
description: 'Creates a directory recursively inside the workspace.',
|
|
94
|
+
inputSchema: {
|
|
95
|
+
type: 'object',
|
|
96
|
+
properties: { path: { type: 'string' } },
|
|
97
|
+
required: ['path']
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
];
|
|
101
|
+
|
|
102
|
+
if (this.allowShell) {
|
|
103
|
+
tools.push(
|
|
104
|
+
{
|
|
105
|
+
name: 'cmd_execute',
|
|
106
|
+
description: 'Executes a quick shell command (<35s) in the workspace.',
|
|
107
|
+
inputSchema: {
|
|
108
|
+
type: 'object',
|
|
109
|
+
properties: {
|
|
110
|
+
command: { type: 'string' },
|
|
111
|
+
cwd: { type: 'string', default: '.' },
|
|
112
|
+
timeout_seconds: { type: 'integer', default: 35 }
|
|
113
|
+
},
|
|
114
|
+
required: ['command']
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
name: 'bg_start_job',
|
|
119
|
+
description: 'Starts a long-running command in the background and returns job_id immediately.',
|
|
120
|
+
inputSchema: {
|
|
121
|
+
type: 'object',
|
|
122
|
+
properties: {
|
|
123
|
+
command: { type: 'string' },
|
|
124
|
+
cwd: { type: 'string', default: '.' },
|
|
125
|
+
name: { type: 'string' }
|
|
126
|
+
},
|
|
127
|
+
required: ['command']
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
name: 'bg_check_job',
|
|
132
|
+
description: 'Checks status and recent log lines of a background job.',
|
|
133
|
+
inputSchema: {
|
|
134
|
+
type: 'object',
|
|
135
|
+
properties: {
|
|
136
|
+
job_id: { type: 'string' },
|
|
137
|
+
tail_lines: { type: 'integer', default: 40 }
|
|
138
|
+
},
|
|
139
|
+
required: ['job_id']
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
name: 'bg_list_jobs',
|
|
144
|
+
description: 'Lists recent background jobs.',
|
|
145
|
+
inputSchema: { type: 'object', properties: {} }
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
name: 'bg_stop_job',
|
|
149
|
+
description: 'Stops a running background job.',
|
|
150
|
+
inputSchema: {
|
|
151
|
+
type: 'object',
|
|
152
|
+
properties: { job_id: { type: 'string' } },
|
|
153
|
+
required: ['job_id']
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return tools;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async execute(toolName, args = {}) {
|
|
163
|
+
try {
|
|
164
|
+
const text = await this._runTool(toolName, args);
|
|
165
|
+
return { content: [{ type: 'text', text: typeof text === 'string' ? text : JSON.stringify(text, null, 2) }] };
|
|
166
|
+
} catch (err) {
|
|
167
|
+
return { isError: true, content: [{ type: 'text', text: `Error: ${err.message}` }] };
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async _runTool(name, args) {
|
|
172
|
+
if (name === 'fs_read_file') {
|
|
173
|
+
const p = this._resolveSafe(args.path);
|
|
174
|
+
const raw = fs.readFileSync(p, 'utf8');
|
|
175
|
+
if (args.start_line || args.end_line) {
|
|
176
|
+
const lines = raw.split(/\r?\n/);
|
|
177
|
+
const start = Math.max(1, parseInt(args.start_line || 1, 10)) - 1;
|
|
178
|
+
const end = args.end_line ? parseInt(args.end_line, 10) : lines.length;
|
|
179
|
+
return lines.slice(start, end).join('\n');
|
|
180
|
+
}
|
|
181
|
+
return raw.slice(0, 200000);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (name === 'fs_write_file') {
|
|
185
|
+
const p = this._resolveSafe(args.path);
|
|
186
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
187
|
+
if (args.append) {
|
|
188
|
+
fs.appendFileSync(p, args.content, 'utf8');
|
|
189
|
+
} else {
|
|
190
|
+
fs.writeFileSync(p, args.content, 'utf8');
|
|
191
|
+
}
|
|
192
|
+
return `Wrote ${args.content.length} chars to ${path.relative(this.rootDir, p) || '.'}`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (name === 'fs_list_directory') {
|
|
196
|
+
const p = this._resolveSafe(args.path || '.');
|
|
197
|
+
const maxDepth = Math.min(3, Math.max(1, parseInt(args.depth || 1, 10)));
|
|
198
|
+
const results = [];
|
|
199
|
+
const ignore = new Set(['node_modules', '.git', '.next', 'dist', 'build', 'vendor', '__pycache__']);
|
|
200
|
+
|
|
201
|
+
const walk = (dir, curDepth, prefix) => {
|
|
202
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
203
|
+
for (const e of entries) {
|
|
204
|
+
if (results.length >= 400) return;
|
|
205
|
+
if (ignore.has(e.name)) continue;
|
|
206
|
+
const rel = prefix ? `${prefix}/${e.name}` : e.name;
|
|
207
|
+
results.push({ name: e.isDirectory() ? `${rel}/` : rel, type: e.isDirectory() ? 'directory' : 'file' });
|
|
208
|
+
if (e.isDirectory() && curDepth < maxDepth) {
|
|
209
|
+
walk(path.join(dir, e.name), curDepth + 1, rel);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
walk(p, 1, '');
|
|
214
|
+
return { directory: p, entries: results };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (name === 'fs_search_files') {
|
|
218
|
+
const p = this._resolveSafe(args.path || '.');
|
|
219
|
+
const pattern = String(args.pattern || '').toLowerCase();
|
|
220
|
+
const needle = String(args.content_search || '');
|
|
221
|
+
const matches = [];
|
|
222
|
+
const ignore = new Set(['node_modules', '.git', '.next', 'dist', 'build', 'vendor', '__pycache__']);
|
|
223
|
+
|
|
224
|
+
const walk = (dir, depth) => {
|
|
225
|
+
if (depth > 5 || matches.length >= 100) return;
|
|
226
|
+
let entries;
|
|
227
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; }
|
|
228
|
+
for (const e of entries) {
|
|
229
|
+
if (matches.length >= 100) return;
|
|
230
|
+
if (ignore.has(e.name)) continue;
|
|
231
|
+
const full = path.join(dir, e.name);
|
|
232
|
+
if (e.isDirectory()) {
|
|
233
|
+
walk(full, depth + 1);
|
|
234
|
+
} else {
|
|
235
|
+
const rel = path.relative(this.rootDir, full);
|
|
236
|
+
if (pattern && !e.name.toLowerCase().includes(pattern.replace(/\*/g, ''))) continue;
|
|
237
|
+
if (needle) {
|
|
238
|
+
try {
|
|
239
|
+
const stat = fs.statSync(full);
|
|
240
|
+
if (stat.size > 512 * 1024) continue;
|
|
241
|
+
const txt = fs.readFileSync(full, 'utf8');
|
|
242
|
+
if (txt.includes(needle)) matches.push(rel);
|
|
243
|
+
} catch (_) {}
|
|
244
|
+
} else {
|
|
245
|
+
matches.push(rel);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
walk(p, 0);
|
|
251
|
+
return { matches };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (name === 'fs_create_directory') {
|
|
255
|
+
const p = this._resolveSafe(args.path);
|
|
256
|
+
fs.mkdirSync(p, { recursive: true });
|
|
257
|
+
return `Created directory: ${p}`;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (name === 'fs_delete_file_or_dir') {
|
|
261
|
+
const p = this._resolveSafe(args.path);
|
|
262
|
+
if (p === this.rootDir) throw new Error('Cannot delete workspace root.');
|
|
263
|
+
fs.rmSync(p, { recursive: Boolean(args.recursive), force: true });
|
|
264
|
+
return `Deleted: ${p}`;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
if (!this.allowShell) {
|
|
268
|
+
throw new Error(`Tool '${name}' requires --allow-shell flag on PC client.`);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
if (name === 'cmd_execute') {
|
|
272
|
+
const cwd = this._resolveSafe(args.cwd || '.');
|
|
273
|
+
const timeoutMs = Math.min(38000, Math.max(1000, (parseInt(args.timeout_seconds || 35, 10)) * 1000));
|
|
274
|
+
return await new Promise((resolve) => {
|
|
275
|
+
exec(args.command, { cwd, timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024 }, (err, stdout, stderr) => {
|
|
276
|
+
resolve({
|
|
277
|
+
exit_code: err ? (err.code || 1) : 0,
|
|
278
|
+
stdout: String(stdout || '').slice(0, 60000),
|
|
279
|
+
stderr: String(stderr || '').slice(0, 20000)
|
|
280
|
+
});
|
|
281
|
+
});
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (name === 'bg_start_job') {
|
|
286
|
+
const cwd = this._resolveSafe(args.cwd || '.');
|
|
287
|
+
const jobId = `bg_${crypto.randomBytes(4).toString('hex')}`;
|
|
288
|
+
const logFile = path.join(this.bgLogDir, `${jobId}.log`);
|
|
289
|
+
const outFd = fs.openSync(logFile, 'w');
|
|
290
|
+
const child = spawn(args.command, {
|
|
291
|
+
cwd,
|
|
292
|
+
shell: true,
|
|
293
|
+
detached: true,
|
|
294
|
+
stdio: ['ignore', outFd, outFd]
|
|
295
|
+
});
|
|
296
|
+
const job = {
|
|
297
|
+
jobId,
|
|
298
|
+
name: args.name || args.command.slice(0, 40),
|
|
299
|
+
command: args.command,
|
|
300
|
+
pid: child.pid,
|
|
301
|
+
logFile,
|
|
302
|
+
status: 'running',
|
|
303
|
+
startedAt: new Date().toISOString(),
|
|
304
|
+
exitCode: null
|
|
305
|
+
};
|
|
306
|
+
child.on('exit', (code) => {
|
|
307
|
+
job.status = 'finished';
|
|
308
|
+
job.exitCode = code;
|
|
309
|
+
try { fs.closeSync(outFd); } catch (_) {}
|
|
310
|
+
});
|
|
311
|
+
child.unref();
|
|
312
|
+
this.bgJobs.set(jobId, job);
|
|
313
|
+
return { job_id: jobId, pid: child.pid, status: 'running' };
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
if (name === 'bg_check_job') {
|
|
317
|
+
const job = this.bgJobs.get(args.job_id);
|
|
318
|
+
if (!job) throw new Error(`Job not found: ${args.job_id}`);
|
|
319
|
+
const tail = Math.max(5, parseInt(args.tail_lines || 40, 10));
|
|
320
|
+
let logs = '';
|
|
321
|
+
if (fs.existsSync(job.logFile)) {
|
|
322
|
+
const lines = fs.readFileSync(job.logFile, 'utf8').split(/\r?\n/);
|
|
323
|
+
logs = lines.slice(-tail).join('\n');
|
|
324
|
+
}
|
|
325
|
+
return { ...job, logs };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (name === 'bg_list_jobs') {
|
|
329
|
+
return Array.from(this.bgJobs.values());
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
if (name === 'bg_stop_job') {
|
|
333
|
+
const job = this.bgJobs.get(args.job_id);
|
|
334
|
+
if (!job) throw new Error(`Job not found: ${args.job_id}`);
|
|
335
|
+
try {
|
|
336
|
+
process.kill(job.pid);
|
|
337
|
+
job.status = 'stopped';
|
|
338
|
+
} catch (_) {}
|
|
339
|
+
return { job_id: job.jobId, status: job.status };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
module.exports = { LocalToolkit };
|
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,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lunisphere-mcp",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Local PC agent for Lunisphere MCP Relay — connect your local workspace to Gemini, Claude, or Cursor with zero tunnel setup.",
|
|
5
|
+
"bin": {
|
|
6
|
+
"lunisphere-mcp": "bin/cli.js"
|
|
7
|
+
},
|
|
8
|
+
"files": [
|
|
9
|
+
"bin/",
|
|
10
|
+
"lib/",
|
|
11
|
+
"README.md"
|
|
12
|
+
],
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/mrahatcreations/lunisphere-mcp-relay.git",
|
|
16
|
+
"directory": "client"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://mcp.lunisphere.com",
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/mrahatcreations/lunisphere-mcp-relay/issues"
|
|
21
|
+
},
|
|
22
|
+
"author": "Lunisphere",
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=18.0.0"
|
|
25
|
+
},
|
|
26
|
+
"keywords": [
|
|
27
|
+
"mcp",
|
|
28
|
+
"gemini",
|
|
29
|
+
"claude",
|
|
30
|
+
"cursor",
|
|
31
|
+
"relay",
|
|
32
|
+
"lunisphere"
|
|
33
|
+
],
|
|
34
|
+
"license": "MIT"
|
|
35
|
+
}
|