Repository navigation
Expand file tree
/
Copy pathnode.js
More file actions
126 lines (109 loc) · 3.87 KB
/
Copy pathnode.js
File metadata and controls
126 lines (109 loc) · 3.87 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
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 HOST = process.env.HOST || '127.0.0.1';
const MCP_PATH = '/';
const allowedOrigins = new Set((process.env.MCP_ALLOWED_ORIGINS || '').split(',').map((origin) => origin.trim()).filter(Boolean));
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-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, MCP-Protocol-Version, Mcp-Method, Mcp-Name',
};
function originHeaders(origin) {
return origin && allowedOrigins.has(origin) ? { ...corsHeaders, 'Access-Control-Allow-Origin': origin, Vary: 'Origin' } : corsHeaders;
}
function headerError(id, message) {
return { jsonrpc: '2.0', id: id ?? null, error: { code: -32020, message } };
}
function validateHeaders(req, message) {
const version = req.headers['mcp-protocol-version'];
const method = req.headers['mcp-method'];
const name = req.headers['mcp-name'];
const bodyVersion = message.params?._meta?.['io.modelcontextprotocol/protocolVersion'] ?? message.params?.protocolVersion;
if (version && bodyVersion && version !== bodyVersion) {
return 'MCP request headers do not match the request body';
}
if (method && method !== message.method) {
return 'MCP request headers do not match the request body';
}
if (message.method === 'tools/call' && name && name !== message.params?.name) {
return 'MCP request headers do not match the request body';
}
return null;
}
function responseStatus(response) {
if (response?.error?.code === -32601) return 404;
if (response?.error?.code === -32602 || response?.error?.code === -32020 || response?.error?.code === -32021 || response?.error?.code === -32022) return 400;
return 200;
}
const server = http.createServer(async (req, res) => {
const origin = req.headers.origin;
if (origin && !allowedOrigins.has(origin)) {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(headerError(null, 'Origin is not allowed')));
return;
}
const headers = originHeaders(origin);
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
return;
}
if (req.url === '/health') {
res.writeHead(200, {
'Content-Type': 'application/json',
...headers,
});
res.end(JSON.stringify({ status: 'healthy', version: MCP_VERSION }));
return;
}
if (req.url !== MCP_PATH || req.method !== 'POST') {
res.writeHead(405, { 'Allow': 'POST, OPTIONS', ...headers });
res.end('Method Not Allowed');
return;
}
let body = '';
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', async () => {
try {
const message = JSON.parse(body);
const mismatch = validateHeaders(req, message);
if (mismatch) {
res.writeHead(400, { 'Content-Type': 'application/json', ...headers });
res.end(JSON.stringify(headerError(message.id, mismatch)));
return;
}
const response = await handler(message);
res.writeHead(responseStatus(response), {
'Content-Type': 'application/json',
'MCP-Protocol-Version': MCP_VERSION,
...headers,
});
res.end(JSON.stringify(response));
} catch (e) {
res.writeHead(400, {
'Content-Type': 'application/json',
...headers,
});
res.end(JSON.stringify({ error: 'Invalid request', detail: e.message }));
}
});
req.on('error', (err) => {
res.writeHead(500, headers);
res.end('Server error');
});
});
server.listen(PORT, HOST, () => {
console.log(`MCP Server listening on http://${HOST}:${PORT}${MCP_PATH}`);
});