-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnode.js
More file actions
79 lines (68 loc) · 1.92 KB
/
node.js
File metadata and controls
79 lines (68 loc) · 1.92 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
import http from 'http';
import { createMCPHandler } from './core.js';
import { MCP_VERSION } from './mcp-version.js';
const PORT = process.env.PORT || process.argv[2] || 3000;
const MCP_PATH = '/';
const handler = createMCPHandler({
fetchFn: (url) =>
fetch(url).then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}),
cache: new Map(),
logger: console.log,
});
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, MCP-Protocol-Version',
};
const server = http.createServer(async (req, res) => {
if (req.method === 'OPTIONS') {
res.writeHead(204, corsHeaders);
res.end();
return;
}
if (req.url === '/health') {
res.writeHead(200, {
'Content-Type': 'application/json',
...corsHeaders,
});
res.end(JSON.stringify({ status: 'healthy', version: MCP_VERSION }));
return;
}
if (req.method !== 'POST' || req.url !== MCP_PATH) {
res.writeHead(404, corsHeaders);
res.end('Not Found');
return;
}
let body = '';
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const message = JSON.parse(body);
const response = await handler(message);
res.writeHead(200, {
'Content-Type': 'application/json',
'MCP-Protocol-Version': MCP_VERSION,
...corsHeaders,
});
res.end(JSON.stringify(response));
} catch (e) {
res.writeHead(400, {
'Content-Type': 'application/json',
...corsHeaders,
});
res.end(JSON.stringify({ error: 'Invalid request', detail: e.message }));
}
});
req.on('error', (err) => {
res.writeHead(500, corsHeaders);
res.end('Server error');
});
});
server.listen(PORT, () => {
console.log(`MCP Server listening on http://localhost:${PORT}${MCP_PATH}`);
});