-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
executable file
Β·340 lines (283 loc) Β· 10.2 KB
/
index.js
File metadata and controls
executable file
Β·340 lines (283 loc) Β· 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#!/usr/bin/env node
// SPDX-License-Identifier: MIT
/**
* ββββββ βββββββ ββββββ ββββββββ
* ββββββββββββββββββββββββββββββββ
* ββββββββββββββββββββββββββββββββ
* ββββββββββββββββββββββββββββββββ
* βββ ββββββ ββββββ βββββββββββ
* βββ ββββββ ββββββ βββββββββββ
*
* Copyright (c) 2026 RΔ±za Emre ARAS <r.emrearas@proton.me>
*
* This file is part of Claude KVM.
* Released under the MIT License β see LICENSE for details.
*
* MCP proxy server β spawns a native VNC daemon (claude-kvm-daemon)
* and exposes a single vnc_command tool to Claude.
* Communication: PC (Procedure Call) over stdin/stdout NDJSON.
*/
import { spawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { vncCommandTool, actionQueueTool, controlTools } from './tools/index.js';
// ββ Configuration βββββββββββββββββββββββββββββββββββββββββββ
const env = (key, fallback) => process.env[key] ?? fallback;
const DAEMON_PATH = env('CLAUDE_KVM_DAEMON_PATH', 'claude-kvm-daemon');
const DAEMON_PARAMS = env('CLAUDE_KVM_DAEMON_PARAMETERS', '');
const VNC_HOST = env('VNC_HOST', '127.0.0.1');
const VNC_PORT = env('VNC_PORT', '5900');
const VNC_USERNAME = env('VNC_USERNAME', '');
const VNC_PASSWORD = env('VNC_PASSWORD', '');
// ββ Logging βββββββββββββββββββββββββββββββββββββββββββββββββ
function log(msg) {
const ts = new Date().toISOString().slice(11, 23);
process.stderr.write(`[MCP ${ts}] ${msg}\n`);
}
// ββ Daemon Process Manager ββββββββββββββββββββββββββββββββββ
let daemon = null;
let daemonReady = false;
const display = { width: 1280, height: 800 };
const pendingRequests = new Map();
let lineBuffer = '';
function buildDaemonArgs() {
const args = ['--host', VNC_HOST, '--port', VNC_PORT];
if (VNC_USERNAME) args.push('--username', VNC_USERNAME);
if (VNC_PASSWORD) args.push('--password', VNC_PASSWORD);
// Extra parameters β passed directly to daemon CLI
if (DAEMON_PARAMS) {
const extra = DAEMON_PARAMS.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) || [];
args.push(...extra.map((s) => s.replace(/^['"]|['"]$/g, '')));
}
return args;
}
function spawnDaemon() {
const args = buildDaemonArgs();
log(`Spawning daemon: ${DAEMON_PATH} ${args.join(' ')}`);
daemon = spawn(DAEMON_PATH, args, {
stdio: ['pipe', 'pipe', 'pipe'],
});
daemon.stdout.on('data', (chunk) => {
lineBuffer += chunk.toString();
let idx;
while ((idx = lineBuffer.indexOf('\n')) !== -1) {
const line = lineBuffer.slice(0, idx).trim();
lineBuffer = lineBuffer.slice(idx + 1);
if (line) handleDaemonMessage(line);
}
});
daemon.stderr.on('data', (chunk) => {
process.stderr.write(chunk);
});
daemon.on('exit', (code) => {
log(`Daemon exited with code ${code}`);
daemonReady = false;
daemon = null;
for (const [, req] of pendingRequests) {
clearTimeout(req.timer);
req.reject(new Error('Daemon exited'));
}
pendingRequests.clear();
});
daemon.on('error', (err) => {
log(`Daemon spawn error: ${err.message}`);
});
}
function handleDaemonMessage(line) {
let msg;
try {
msg = JSON.parse(line);
} catch {
log(`Invalid daemon JSON: ${line}`);
return;
}
// PC notification β has method, no id
if (msg.method) {
const { scaledWidth, scaledHeight, state } = msg.params || {};
if (msg.method === 'ready') {
daemonReady = true;
if (scaledWidth) display.width = scaledWidth;
if (scaledHeight) display.height = scaledHeight;
log(`Daemon ready β display ${display.width}Γ${display.height}`);
} else if (msg.method === 'vnc_state') {
log(`VNC state: ${state}`);
}
return;
}
// PC response β has id
if (msg.id !== undefined && pendingRequests.has(msg.id)) {
const req = pendingRequests.get(msg.id);
pendingRequests.delete(msg.id);
clearTimeout(req.timer);
req.resolve(msg);
}
}
/**
* Send a PC request to the daemon and wait for response.
* @param {string} method - PC method name
* @param {object} [params] - Method parameters
* @param {number} [timeoutMs=30000] - Timeout in milliseconds
* @returns {Promise<object>} - Daemon PC response
*/
function sendRequest(method, params, timeoutMs = 30000) {
return new Promise((resolve, reject) => {
if (!daemon || !daemonReady) {
reject(new Error('Daemon not ready. Check CLAUDE_KVM_DAEMON_PATH and VNC credentials.'));
return;
}
const id = randomUUID();
const timer = setTimeout(() => {
pendingRequests.delete(id);
reject(new Error(`Daemon request timed out after ${timeoutMs}ms`));
}, timeoutMs);
pendingRequests.set(id, { resolve, reject, timer });
const request = { method, id };
if (params && Object.keys(params).length > 0) request.params = params;
daemon.stdin.write(JSON.stringify(request) + '\n');
});
}
// ββ Wait for daemon ready βββββββββββββββββββββββββββββββββββ
function waitForReady(timeoutMs = 30000) {
return new Promise((resolve, reject) => {
if (daemonReady) { resolve(); return; }
const interval = setInterval(() => {
if (daemonReady) {
clearInterval(interval);
clearTimeout(timer);
resolve();
}
}, 100);
const timer = setTimeout(() => {
clearInterval(interval);
reject(new Error('Daemon did not become ready within timeout'));
}, timeoutMs);
});
}
// ββ Tool Execution ββββββββββββββββββββββββββββββββββββββββββ
async function executeVncCommand(input) {
const { action, ...params } = input;
const response = await sendRequest(action, params);
// PC error response
if (response.error) {
return {
content: [{ type: 'text', text: `Error: ${response.error.message}` }],
isError: true,
};
}
const { detail, image, x, y, scaledWidth, scaledHeight, elements, timing } = response.result || {};
const content = [];
// Text detail
if (detail) {
content.push({ type: 'text', text: detail });
}
// Image
if (image) {
content.push({ type: 'image', data: image, mimeType: 'image/png' });
}
// OCR elements (detect_elements)
if (elements) {
content.push({ type: 'text', text: JSON.stringify(elements) });
}
// Timing map (get_timing, configure with reset)
if (timing) {
content.push({ type: 'text', text: JSON.stringify(timing) });
}
// Cursor position (nudge, cursor_crop)
if (x !== undefined && y !== undefined) {
content.push({ type: 'text', text: `cursor: (${x}, ${y})` });
}
// Display dimensions (health, detect_elements, get_timing β no image)
if (scaledWidth !== undefined && !image) {
content.push({ type: 'text', text: `display: ${scaledWidth}Γ${scaledHeight}` });
}
if (content.length === 0) {
content.push({ type: 'text', text: 'OK' });
}
return { content };
}
async function executeActionQueue(input) {
const results = [];
for (let i = 0; i < input.actions.length; i++) {
const { action, ...params } = input.actions[i];
const response = await sendRequest(action, params);
if (response.error) {
results.push(`[${i + 1}] ${action}: ERROR β ${response.error.message}`);
break;
}
const detail = response.result?.detail;
results.push(`[${i + 1}] ${action}: ${detail || 'OK'}`);
}
return { content: [{ type: 'text', text: results.join('\n') }] };
}
// ββ MCP Server ββββββββββββββββββββββββββββββββββββββββββββββ
async function main() {
log('Claude KVM v1.0.0 β Native VNC proxy');
spawnDaemon();
const mcpServer = new McpServer(
{ name: 'claude-kvm', version: '1.0.0' },
{ capabilities: { tools: {} } },
);
try {
await waitForReady(30000);
} catch (err) {
log(`Warning: ${err.message} β registering with default dimensions`);
}
// Register vnc_command tool
const vncTool = vncCommandTool(display.width, display.height);
mcpServer.tool(
vncTool.name,
vncTool.inputSchema,
async (input) => {
try {
return await executeVncCommand(input);
} catch (err) {
return { content: [{ type: 'text', text: `Error: ${err.message}` }], isError: true };
}
},
);
// Register action_queue tool
const queueTool = actionQueueTool(display.width, display.height);
mcpServer.tool(
queueTool.name,
queueTool.inputSchema,
async (input) => {
try {
return await executeActionQueue(input);
} catch (err) {
return { content: [{ type: 'text', text: `Error: ${err.message}` }], isError: true };
}
},
);
// Register control tools
for (const tool of controlTools()) {
mcpServer.tool(
tool.name,
tool.inputSchema,
async (input) => {
if (tool.name === 'task_complete') {
return { content: [{ type: 'text', text: input.summary }] };
}
if (tool.name === 'task_failed') {
return { content: [{ type: 'text', text: input.reason }], isError: true };
}
},
);
}
const transport = new StdioServerTransport();
await mcpServer.connect(transport);
log('MCP server connected on stdio');
process.on('SIGINT', () => {
log('Shutting down...');
if (daemon) {
daemon.stdin.write(JSON.stringify({ method: 'shutdown' }) + '\n');
setTimeout(() => { daemon?.kill(); process.exit(0); }, 500);
} else {
process.exit(0);
}
});
}
main().catch((err) => {
log(`Fatal: ${err.message}`);
process.exit(1);
});