-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathserver.ts
More file actions
93 lines (82 loc) · 2.45 KB
/
Copy pathserver.ts
File metadata and controls
93 lines (82 loc) · 2.45 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
import { documentRegistry, getPrimaryWorkspaceFolder } from '#core';
import {
buildPortFilePath,
DOCUMENT_ROUTE,
encodePortFile,
LOOPBACK_HOST,
TOKEN_HEADER,
} from '@lemoncode/quickmock-registry-protocol';
import { randomBytes } from 'node:crypto';
import { unlinkSync, writeFileSync } from 'node:fs';
import {
createServer,
type IncomingMessage,
type ServerResponse,
} from 'node:http';
import * as vscode from 'vscode';
import { PORT_FILE_MODE, TOKEN_BYTE_LENGTH } from './constants';
/**
* Starts the MCP document bridge server, which serves the content of documents open in the editor to the MCP server.
* @param context The VS Code extension context.
* @returns A promise that resolves when the server has started.
*/
export const startDocumentBridge = async (
context: vscode.ExtensionContext
): Promise<void> => {
const workspaceRoot = getPrimaryWorkspaceFolder()?.uri.fsPath;
if (!workspaceRoot) return;
const portFile = buildPortFilePath(workspaceRoot);
const token = randomBytes(TOKEN_BYTE_LENGTH).toString('hex');
const handleRequest = (req: IncomingMessage, res: ServerResponse): void => {
if (req.headers[TOKEN_HEADER] !== token) {
res.writeHead(401);
res.end();
return;
}
const url = new URL(req.url ?? '/', 'http://localhost');
if (url.pathname !== DOCUMENT_ROUTE) {
res.writeHead(404);
res.end();
return;
}
const path = url.searchParams.get('path');
if (!path) {
res.writeHead(400);
res.end('Missing path parameter');
return;
}
const content = documentRegistry.get(path);
if (content === undefined) {
res.writeHead(404);
res.end('Document not open in editor');
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(content);
};
const server = createServer(handleRequest);
await new Promise<void>((resolve, reject) => {
server.on('error', reject);
// Get the assigned port and write it to the port file
server.listen(0, LOOPBACK_HOST, () => {
const { port } = server.address() as { port: number };
try {
writeFileSync(portFile, encodePortFile(port, token), {
mode: PORT_FILE_MODE,
});
} catch (err) {
reject(err);
return;
}
resolve();
});
});
context.subscriptions.push({
dispose: () => {
server.close();
try {
unlinkSync(portFile);
} catch {}
},
});
};