-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathmcp-bridge.js
More file actions
487 lines (415 loc) · 13.1 KB
/
mcp-bridge.js
File metadata and controls
487 lines (415 loc) · 13.1 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/**
* mcp-bridge.js — Per-session WebSocket MCP server for Switchboard.
*
* Each Claude CLI PTY gets its own MCP server so the CLI can send
* openDiff / openFile / closeAllDiffTabs / getDiagnostics calls
* to Switchboard's file panel instead of a VS Code extension.
*/
const { WebSocketServer } = require('ws');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const os = require('os');
const net = require('net');
const IDE_DIR = path.join(os.homedir(), '.claude', 'ide');
// sessionId → ServerEntry
const servers = new Map();
// ── Helpers ──────────────────────────────────────────────────────────
function ensureIdeDir() {
fs.mkdirSync(IDE_DIR, { recursive: true });
}
/** Get a random free port from the OS. */
function findFreePort() {
return new Promise((resolve, reject) => {
const srv = net.createServer();
srv.listen(0, '127.0.0.1', () => {
const { port } = srv.address();
srv.close(() => resolve(port));
});
srv.on('error', reject);
});
}
/** Build the JSON-RPC 2.0 response envelope. */
function rpcResult(id, result) {
return JSON.stringify({ jsonrpc: '2.0', id, result });
}
function rpcError(id, code, message) {
return JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } });
}
// ── MCP Tool Schemas ─────────────────────────────────────────────────
const MCP_TOOLS = [
{
name: 'openDiff',
description: 'Open a diff view for a file edit',
inputSchema: {
type: 'object',
properties: {
old_file_path: { type: 'string' },
new_file_path: { type: 'string' },
new_file_contents: { type: 'string' },
tab_name: { type: 'string' },
},
required: ['old_file_path', 'new_file_path', 'new_file_contents', 'tab_name'],
},
},
{
name: 'openFile',
description: 'Open a file in the editor',
inputSchema: {
type: 'object',
properties: {
filePath: { type: 'string' },
preview: { type: 'boolean' },
startText: { type: 'string' },
endText: { type: 'string' },
selectToEndOfLine: { type: 'boolean' },
makeFrontmost: { type: 'boolean' },
},
required: ['filePath'],
},
},
{
name: 'close_tab',
description: 'Close a specific diff tab by name',
inputSchema: {
type: 'object',
properties: { tab_name: { type: 'string' } },
required: ['tab_name'],
},
},
{
name: 'closeAllDiffTabs',
description: 'Close all open diff tabs',
inputSchema: { type: 'object', properties: {} },
},
{
name: 'getDiagnostics',
description: 'Get diagnostics for a file',
inputSchema: {
type: 'object',
properties: { uri: { type: 'string' } },
},
},
];
// ── JSON-RPC Message Handler ─────────────────────────────────────────
function handleMessage(entry, raw, log) {
let msg;
try {
msg = JSON.parse(raw);
} catch {
log.warn('[mcp] Received invalid JSON');
return;
}
const { id, method, params } = msg;
// Notifications (no id) — fire-and-forget
if (id === undefined || id === null) {
if (method === 'notifications/initialized') {
log.info(`[mcp] session=${entry.sessionId} CLI initialized`);
}
return;
}
// Requests (have id) — must respond
switch (method) {
case 'initialize':
return sendResult(entry, id, {
protocolVersion: '2025-03-26',
capabilities: { tools: {} },
serverInfo: { name: 'Switchboard', version: '1.0.0' },
});
case 'tools/list':
return sendResult(entry, id, { tools: MCP_TOOLS });
case 'tools/call':
return handleToolCall(entry, id, params, log);
default:
log.debug(`[mcp] session=${entry.sessionId} unhandled method: ${method}`);
return sendError(entry, id, -32601, `Method not found: ${method}`);
}
}
function sendResult(entry, id, result) {
if (entry.ws && entry.ws.readyState === 1) {
entry.ws.send(rpcResult(id, result));
}
}
function sendError(entry, id, code, message) {
if (entry.ws && entry.ws.readyState === 1) {
entry.ws.send(rpcError(id, code, message));
}
}
// ── Tool Call Dispatch ───────────────────────────────────────────────
async function handleToolCall(entry, rpcId, params, log) {
const toolName = params?.name;
const args = params?.arguments || {};
switch (toolName) {
case 'openDiff':
return handleOpenDiff(entry, rpcId, args, log);
case 'openFile':
return handleOpenFile(entry, rpcId, args, log);
case 'close_tab':
return handleCloseTab(entry, rpcId, args, log);
case 'closeAllDiffTabs':
return handleCloseAllDiffTabs(entry, rpcId, log);
case 'getDiagnostics':
return handleGetDiagnostics(entry, rpcId);
default:
return sendError(entry, rpcId, -32602, `Unknown tool: ${toolName}`);
}
}
async function handleOpenDiff(entry, rpcId, args, log) {
const { old_file_path, new_file_contents, tab_name } = args;
// Read the current file from disk
let oldContent = '';
try {
oldContent = fs.readFileSync(old_file_path, 'utf8');
} catch {
log.debug(`[mcp] Could not read ${old_file_path} — treating as new file`);
}
const diffId = crypto.randomUUID();
// Create a promise that will be resolved when the user acts on the diff
const diffPromise = new Promise((resolve) => {
entry.pendingDiffs.set(diffId, { resolve, rpcId, tabName: tab_name });
});
// Send to renderer
if (entry.mainWindow && !entry.mainWindow.isDestroyed()) {
entry.mainWindow.webContents.send('mcp-open-diff', entry.sessionId, diffId, {
oldFilePath: old_file_path,
oldContent,
newContent: new_file_contents,
tabName: tab_name,
});
}
// Await user action
const result = await diffPromise;
// Send JSON-RPC response back to Claude CLI
if (result.action === 'accept-edited') {
// User accepted with edits — return FILE_SAVED + new content
sendResult(entry, rpcId, {
content: [
{ type: 'text', text: 'FILE_SAVED' },
{ type: 'text', text: result.content },
],
});
} else if (result.action === 'accept') {
// User closed tab (accept as-is)
sendResult(entry, rpcId, {
content: [{ type: 'text', text: 'TAB_CLOSED' }],
});
} else {
// User rejected
sendResult(entry, rpcId, {
content: [{ type: 'text', text: 'DIFF_REJECTED' }],
});
}
}
async function handleOpenFile(entry, rpcId, args, log) {
const { filePath, preview, startText, endText } = args;
let content = '';
try {
content = fs.readFileSync(filePath, 'utf8');
} catch (err) {
log.debug(`[mcp] Could not read ${filePath}: ${err.message}`);
}
if (entry.mainWindow && !entry.mainWindow.isDestroyed()) {
entry.mainWindow.webContents.send('mcp-open-file', entry.sessionId, {
filePath,
content,
preview: preview ?? false,
startText: startText || '',
endText: endText || '',
});
}
sendResult(entry, rpcId, {
content: [{ type: 'text', text: 'ok' }],
});
}
async function handleCloseTab(entry, rpcId, args, log) {
const { tab_name } = args;
log.debug(`[mcp] session=${entry.sessionId} close_tab: ${tab_name}`);
// Find the pending diff by tab_name
for (const [diffId, pending] of entry.pendingDiffs) {
if (pending.tabName === tab_name) {
entry.pendingDiffs.delete(diffId);
pending.resolve({ action: 'accept' });
// Notify renderer to close the tab
if (entry.mainWindow && !entry.mainWindow.isDestroyed()) {
entry.mainWindow.webContents.send('mcp-close-tab', entry.sessionId, diffId);
}
break;
}
}
sendResult(entry, rpcId, {
content: [{ type: 'text', text: 'ok' }],
});
}
async function handleCloseAllDiffTabs(entry, rpcId, log) {
log.debug(`[mcp] session=${entry.sessionId} closeAllDiffTabs`);
// Resolve all pending diffs as TAB_CLOSED
for (const [diffId, pending] of entry.pendingDiffs) {
pending.resolve({ action: 'accept' });
}
entry.pendingDiffs.clear();
if (entry.mainWindow && !entry.mainWindow.isDestroyed()) {
entry.mainWindow.webContents.send('mcp-close-all-diffs', entry.sessionId);
}
sendResult(entry, rpcId, {
content: [{ type: 'text', text: 'ok' }],
});
}
async function handleGetDiagnostics(entry, rpcId) {
sendResult(entry, rpcId, {
content: [{ type: 'text', text: '[]' }],
});
}
// ── Public API ───────────────────────────────────────────────────────
/**
* Start an MCP WebSocket server for a session.
* @returns {{ port: number, authToken: string }}
*/
async function startMcpServer(sessionId, workspaceFolders, mainWindow, log) {
ensureIdeDir();
const port = await findFreePort();
const authToken = crypto.randomUUID();
const wss = new WebSocketServer({
port,
host: '127.0.0.1',
handleProtocols: (protocols) => {
if (protocols.has('mcp')) return 'mcp';
return false;
},
});
const lockFilePath = path.join(IDE_DIR, `${port}.lock`);
const lockData = JSON.stringify({
pid: process.pid,
workspaceFolders,
ideName: 'Switchboard',
transport: 'ws',
runningInWindows: false,
authToken,
});
fs.writeFileSync(lockFilePath, lockData, 'utf8');
const entry = {
sessionId,
wss,
port,
authToken,
lockFilePath,
mainWindow,
ws: null,
pendingDiffs: new Map(),
};
wss.on('connection', (ws, req) => {
// Validate auth
const headerAuth = req.headers['x-claude-code-ide-authorization'];
if (headerAuth !== authToken) {
log.warn(`[mcp] session=${sessionId} rejected connection: bad auth`);
ws.close(4001, 'Unauthorized');
return;
}
log.info(`[mcp] session=${sessionId} CLI connected on port ${port}`);
// Close any previous connection
if (entry.ws) {
try { entry.ws.close(); } catch {}
}
entry.ws = ws;
ws.on('message', (data) => {
handleMessage(entry, data.toString(), log);
});
ws.on('close', () => {
if (entry.ws === ws) entry.ws = null;
log.debug(`[mcp] session=${sessionId} CLI disconnected`);
});
ws.on('error', (err) => {
log.debug(`[mcp] session=${sessionId} ws error: ${err.message}`);
});
});
wss.on('error', (err) => {
log.error(`[mcp] session=${sessionId} server error: ${err.message}`);
});
servers.set(sessionId, entry);
log.info(`[mcp] session=${sessionId} server started on port ${port}`);
return { port, authToken };
}
/**
* Shut down the MCP server for a session.
*/
function shutdownMcpServer(sessionId) {
const entry = servers.get(sessionId);
if (!entry) return;
// Resolve all pending diffs
for (const [, pending] of entry.pendingDiffs) {
pending.resolve({ action: 'accept' });
}
entry.pendingDiffs.clear();
// Close WebSocket
if (entry.ws) {
try { entry.ws.close(); } catch {}
}
// Close server
try { entry.wss.close(); } catch {}
// Delete lock file
try { fs.unlinkSync(entry.lockFilePath); } catch {}
servers.delete(sessionId);
}
/**
* Shut down all MCP servers (app quit).
*/
function shutdownAll() {
for (const sessionId of servers.keys()) {
shutdownMcpServer(sessionId);
}
}
/**
* Resolve a pending diff from the renderer.
* @param {string} action - 'accept' | 'accept-edited' | 'reject'
* @param {string|null} editedContent - modified content (for accept-edited)
*/
function resolvePendingDiff(sessionId, diffId, action, editedContent) {
const entry = servers.get(sessionId);
if (!entry) return;
const pending = entry.pendingDiffs.get(diffId);
if (!pending) return;
entry.pendingDiffs.delete(diffId);
pending.resolve({ action, content: editedContent });
}
/**
* Re-key a server entry when session ID changes (e.g. fork).
*/
function rekeyMcpServer(oldId, newId) {
const entry = servers.get(oldId);
if (!entry) return;
servers.delete(oldId);
entry.sessionId = newId;
servers.set(newId, entry);
}
/**
* Clean up stale lock files from previous Switchboard runs.
*/
function cleanStaleLockFiles(log) {
try {
ensureIdeDir();
const files = fs.readdirSync(IDE_DIR);
for (const file of files) {
if (!file.endsWith('.lock')) continue;
const lockPath = path.join(IDE_DIR, file);
try {
const data = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
if (data.ideName === 'Switchboard' && data.pid === process.pid) {
// Our PID but we didn't start it — stale from crash
fs.unlinkSync(lockPath);
if (log) log.info(`[mcp] Cleaned stale lock file: ${file}`);
}
} catch {
// Not our lock file or can't parse — skip
}
}
} catch {
// IDE dir may not exist yet
}
}
module.exports = {
startMcpServer,
shutdownMcpServer,
shutdownAll,
resolvePendingDiff,
rekeyMcpServer,
cleanStaleLockFiles,
};