-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathdaemon.ts
More file actions
428 lines (375 loc) · 10.2 KB
/
daemon.ts
File metadata and controls
428 lines (375 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* MCP-CLI Daemon - Background worker that maintains persistent MCP connections
*
* This is spawned as a detached process and manages a Unix socket for IPC.
* It maintains the MCP server connection and forwards requests from CLI invocations.
*/
import {
existsSync,
mkdirSync,
readFileSync,
unlinkSync,
writeFileSync,
} from 'node:fs';
import { dirname } from 'node:path';
import {
type ConnectedClient,
callTool,
connectToServer,
listTools,
} from './client.js';
import {
type ServerConfig,
debug,
getConfigHash,
getDaemonTimeoutMs,
getPidPath,
getSocketDir,
getSocketPath,
} from './config.js';
// ============================================================================
// Types
// ============================================================================
export interface DaemonRequest {
id: string;
type: 'listTools' | 'callTool' | 'ping' | 'close' | 'getInstructions';
toolName?: string;
args?: Record<string, unknown>;
}
export interface DaemonResponse {
id: string;
success: boolean;
data?: unknown;
error?: { code: string; message: string };
}
interface PidFileContent {
pid: number;
configHash: string;
startedAt: string;
}
// ============================================================================
// PID File Management
// ============================================================================
/**
* Write PID file with config hash for stale detection
*/
export function writePidFile(serverName: string, configHash: string): void {
const pidPath = getPidPath(serverName);
const dir = dirname(pidPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
const content: PidFileContent = {
pid: process.pid,
configHash,
startedAt: new Date().toISOString(),
};
writeFileSync(pidPath, JSON.stringify(content), { mode: 0o600 });
}
/**
* Read PID file content
*/
export function readPidFile(serverName: string): PidFileContent | null {
const pidPath = getPidPath(serverName);
if (!existsSync(pidPath)) {
return null;
}
try {
const content = readFileSync(pidPath, 'utf-8');
return JSON.parse(content);
} catch {
return null;
}
}
/**
* Remove PID file
*/
export function removePidFile(serverName: string): void {
const pidPath = getPidPath(serverName);
try {
if (existsSync(pidPath)) {
unlinkSync(pidPath);
}
} catch {
// Ignore errors during cleanup
}
}
/**
* Remove socket file
*/
export function removeSocketFile(serverName: string): void {
const socketPath = getSocketPath(serverName);
try {
if (existsSync(socketPath)) {
unlinkSync(socketPath);
}
} catch {
// Ignore errors during cleanup
}
}
/**
* Check if a process is running
*/
export function isProcessRunning(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
/**
* Kill a process by PID
*/
export function killProcess(pid: number): boolean {
try {
process.kill(pid, 'SIGTERM');
return true;
} catch {
return false;
}
}
// ============================================================================
// Daemon Worker
// ============================================================================
/**
* Main daemon entry point - run as detached background process
*/
export async function runDaemon(
serverName: string,
config: ServerConfig,
): Promise<void> {
const socketPath = getSocketPath(serverName);
const configHash = getConfigHash(config);
const timeoutMs = getDaemonTimeoutMs();
let idleTimer: ReturnType<typeof setTimeout> | null = null;
let mcpClient: ConnectedClient | null = null;
let server: ReturnType<typeof Bun.listen> | null = null;
const activeConnections = new Set<unknown>();
// Cleanup function
const cleanup = async () => {
debug(`[daemon:${serverName}] Shutting down...`);
if (idleTimer) {
clearTimeout(idleTimer);
idleTimer = null;
}
// Close all active socket connections
for (const conn of activeConnections) {
try {
(conn as { end: () => void }).end();
} catch {
// Ignore
}
}
activeConnections.clear();
// Close MCP connection
if (mcpClient) {
try {
await mcpClient.close();
} catch {
// Ignore
}
mcpClient = null;
}
// Close socket server
if (server) {
try {
server.stop();
} catch {
// Ignore
}
server = null;
}
// Clean up files
removeSocketFile(serverName);
removePidFile(serverName);
debug(`[daemon:${serverName}] Cleanup complete`);
};
// Reset idle timer
const resetIdleTimer = () => {
if (idleTimer) {
clearTimeout(idleTimer);
}
idleTimer = setTimeout(async () => {
debug(`[daemon:${serverName}] Idle timeout reached, shutting down`);
await cleanup();
process.exit(0);
}, timeoutMs);
};
// Handle signals
process.on('SIGTERM', async () => {
await cleanup();
process.exit(0);
});
process.on('SIGINT', async () => {
await cleanup();
process.exit(0);
});
// Ensure socket dir exists
const socketDir = getSocketDir();
if (!existsSync(socketDir)) {
mkdirSync(socketDir, { recursive: true, mode: 0o700 });
}
// Remove stale socket if exists
removeSocketFile(serverName);
// Write PID file
writePidFile(serverName, configHash);
// Connect to MCP server
try {
debug(`[daemon:${serverName}] Connecting to MCP server...`);
mcpClient = await connectToServer(serverName, config);
debug(`[daemon:${serverName}] Connected to MCP server`);
} catch (error) {
console.error(
`[daemon:${serverName}] Failed to connect:`,
(error as Error).message,
);
await cleanup();
process.exit(1);
}
// Handle incoming request
const handleRequest = async (data: Buffer): Promise<DaemonResponse> => {
resetIdleTimer();
let request: DaemonRequest;
try {
request = JSON.parse(data.toString());
} catch {
return {
id: 'unknown',
success: false,
error: { code: 'INVALID_REQUEST', message: 'Invalid JSON' },
};
}
debug(`[daemon:${serverName}] Request: ${request.type} (${request.id})`);
if (!mcpClient) {
return {
id: request.id,
success: false,
error: { code: 'NOT_CONNECTED', message: 'MCP client not connected' },
};
}
try {
switch (request.type) {
case 'ping':
return { id: request.id, success: true, data: 'pong' };
case 'listTools': {
const tools = await listTools(mcpClient.client);
return { id: request.id, success: true, data: tools };
}
case 'callTool': {
if (!request.toolName) {
return {
id: request.id,
success: false,
error: { code: 'MISSING_TOOL', message: 'toolName required' },
};
}
const result = await callTool(
mcpClient.client,
request.toolName,
request.args ?? {},
);
return { id: request.id, success: true, data: result };
}
case 'getInstructions': {
const instructions = mcpClient.client.getInstructions();
return { id: request.id, success: true, data: instructions };
}
case 'close':
// Graceful shutdown requested
setTimeout(async () => {
await cleanup();
process.exit(0);
}, 100);
return { id: request.id, success: true, data: 'closing' };
default:
return {
id: request.id,
success: false,
error: {
code: 'UNKNOWN_TYPE',
message: `Unknown request type: ${request.type}`,
},
};
}
} catch (error) {
const err = error as Error;
return {
id: request.id,
success: false,
error: { code: 'EXECUTION_ERROR', message: err.message },
};
}
};
// Start Unix socket server
try {
server = Bun.listen({
unix: socketPath,
socket: {
open(socket) {
activeConnections.add(socket);
debug(`[daemon:${serverName}] Client connected`);
},
async data(socket, data) {
const response = await handleRequest(data);
const payload = `${JSON.stringify(response)}\n`;
// Write in chunks to handle large payloads that exceed socket buffer
let offset = 0;
while (offset < payload.length) {
const written = socket.write(payload.slice(offset));
if (written === 0) {
await new Promise((r) => setTimeout(r, 1));
continue;
}
offset += written;
}
socket.flush();
socket.end();
},
close(socket) {
activeConnections.delete(socket);
debug(`[daemon:${serverName}] Client disconnected`);
},
error(socket, error) {
debug(`[daemon:${serverName}] Socket error: ${error.message}`);
activeConnections.delete(socket);
},
},
});
debug(`[daemon:${serverName}] Listening on ${socketPath}`);
// Start idle timer
resetIdleTimer();
// Signal readiness by writing to stdout (parent will read this)
console.log('DAEMON_READY');
} catch (error) {
console.error(
`[daemon:${serverName}] Failed to start socket server:`,
(error as Error).message,
);
await cleanup();
process.exit(1);
}
}
// ============================================================================
// Entry point when run directly
// ============================================================================
// Check if running as daemon process
if (process.argv[2] === '--daemon') {
const serverName = process.argv[3];
const configJson = process.argv[4];
if (!serverName || !configJson) {
console.error('Usage: daemon.ts --daemon <serverName> <configJson>');
process.exit(1);
}
let config: ServerConfig;
try {
config = JSON.parse(configJson);
} catch {
console.error('Invalid config JSON');
process.exit(1);
}
runDaemon(serverName, config).catch((error) => {
console.error('Daemon failed:', error);
process.exit(1);
});
}