Repository navigation
Expand file tree
/
Copy pathmcp-proxy.js
More file actions
375 lines (345 loc) · 13.8 KB
/
Copy pathmcp-proxy.js
File metadata and controls
375 lines (345 loc) · 13.8 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
import { getCorsHeaders, isDisallowedOrigin } from './_cors.js';
import { jsonResponse } from './_json-response.js';
export const config = { runtime: 'edge' };
const TIMEOUT_MS = 15_000;
const SSE_CONNECT_TIMEOUT_MS = 10_000;
const SSE_RPC_TIMEOUT_MS = 12_000;
const MCP_PROTOCOL_VERSION = '2025-03-26';
const BLOCKED_HOST_PATTERNS = [
/^localhost$/i,
/^127\./,
/^10\./,
/^172\.(1[6-9]|2\d|3[01])\./,
/^192\.168\./,
/^169\.254\./, // link-local + cloud metadata (AWS/GCP/Azure)
/^::1$/,
/^fd[0-9a-f]{2}:/i,
/^fe80:/i,
];
function buildInitPayload() {
return {
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'worldmonitor', version: '1.0' },
},
};
}
function validateServerUrl(raw) {
let url;
try { url = new URL(raw); } catch { return null; }
if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;
const host = url.hostname;
if (BLOCKED_HOST_PATTERNS.some(p => p.test(host))) return null;
return url;
}
function buildHeaders(customHeaders) {
const h = {
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
'User-Agent': 'WorldMonitor-MCP-Proxy/1.0',
};
if (customHeaders && typeof customHeaders === 'object') {
for (const [k, v] of Object.entries(customHeaders)) {
if (typeof k === 'string' && typeof v === 'string') {
// Strip CRLF to prevent header injection
const safeKey = k.replace(/[\r\n]/g, '');
const safeVal = v.replace(/[\r\n]/g, '');
if (safeKey) h[safeKey] = safeVal;
}
}
}
return h;
}
// --- Streamable HTTP transport (MCP 2025-03-26) ---
async function postJson(url, body, headers, sessionId) {
const h = { ...headers };
if (sessionId) h['Mcp-Session-Id'] = sessionId;
const resp = await fetch(url.toString(), {
method: 'POST',
headers: h,
body: JSON.stringify(body),
signal: AbortSignal.timeout(TIMEOUT_MS),
});
return resp;
}
async function parseJsonRpcResponse(resp) {
const ct = resp.headers.get('content-type') || '';
if (ct.includes('text/event-stream')) {
const text = await resp.text();
const lines = text.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const parsed = JSON.parse(line.slice(6));
if (parsed.result !== undefined || parsed.error !== undefined) return parsed;
} catch { /* skip */ }
}
}
throw new Error('No result found in SSE response');
}
return resp.json();
}
async function sendInitialized(serverUrl, headers, sessionId) {
try {
await postJson(serverUrl, {
jsonrpc: '2.0',
method: 'notifications/initialized',
params: {},
}, headers, sessionId);
} catch { /* non-fatal */ }
}
async function mcpListTools(serverUrl, customHeaders) {
const headers = buildHeaders(customHeaders);
const initResp = await postJson(serverUrl, buildInitPayload(), headers, null);
if (!initResp.ok) throw new Error(`Initialize failed: HTTP ${initResp.status}`);
const sessionId = initResp.headers.get('Mcp-Session-Id') || initResp.headers.get('mcp-session-id');
const initData = await parseJsonRpcResponse(initResp);
if (initData.error) throw new Error(`Initialize error: ${initData.error.message}`);
await sendInitialized(serverUrl, headers, sessionId);
const listResp = await postJson(serverUrl, {
jsonrpc: '2.0', id: 2, method: 'tools/list', params: {},
}, headers, sessionId);
if (!listResp.ok) throw new Error(`tools/list failed: HTTP ${listResp.status}`);
const listData = await parseJsonRpcResponse(listResp);
if (listData.error) throw new Error(`tools/list error: ${listData.error.message}`);
return listData.result?.tools || [];
}
async function mcpCallTool(serverUrl, toolName, toolArgs, customHeaders) {
const headers = buildHeaders(customHeaders);
const initResp = await postJson(serverUrl, buildInitPayload(), headers, null);
if (!initResp.ok) throw new Error(`Initialize failed: HTTP ${initResp.status}`);
const sessionId = initResp.headers.get('Mcp-Session-Id') || initResp.headers.get('mcp-session-id');
const initData = await parseJsonRpcResponse(initResp);
if (initData.error) throw new Error(`Initialize error: ${initData.error.message}`);
await sendInitialized(serverUrl, headers, sessionId);
const callResp = await postJson(serverUrl, {
jsonrpc: '2.0', id: 3, method: 'tools/call',
params: { name: toolName, arguments: toolArgs || {} },
}, headers, sessionId);
if (!callResp.ok) throw new Error(`tools/call failed: HTTP ${callResp.status}`);
const callData = await parseJsonRpcResponse(callResp);
if (callData.error) throw new Error(`tools/call error: ${callData.error.message}`);
return callData.result;
}
// --- SSE transport (HTTP+SSE, older MCP spec) ---
// Servers whose URL path ends with /sse use this protocol:
// 1. Client GETs the SSE URL — server opens a stream and emits an `endpoint` event
// containing the URL where the client should POST JSON-RPC messages.
// 2. Client POSTs JSON-RPC to that endpoint URL.
// 3. Server sends responses on the same SSE stream as `data:` lines.
function isSseTransport(url) {
const p = url.pathname;
return p === '/sse' || p.endsWith('/sse');
}
function makeDeferred() {
let resolve, reject;
const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
class SseSession {
constructor(sseUrl, headers) {
this._sseUrl = sseUrl;
this._headers = headers;
this._endpointUrl = null;
this._endpointDeferred = makeDeferred();
this._pending = new Map(); // rpc id -> deferred
this._reader = null;
}
async connect() {
const resp = await fetch(this._sseUrl, {
headers: { ...this._headers, Accept: 'text/event-stream', 'Cache-Control': 'no-cache' },
signal: AbortSignal.timeout(SSE_CONNECT_TIMEOUT_MS),
});
if (!resp.ok) throw new Error(`SSE connect HTTP ${resp.status}`);
this._reader = resp.body.getReader();
this._startReadLoop();
await this._endpointDeferred.promise;
}
_startReadLoop() {
const dec = new TextDecoder();
let buf = '';
let eventType = '';
const reader = this._reader;
const self = this;
(async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
// Stream closed — if endpoint never arrived, reject so connect() throws
if (!self._endpointUrl) {
self._endpointDeferred.reject(new Error('SSE stream closed before endpoint event'));
}
for (const [, d] of self._pending) d.reject(new Error('SSE stream closed'));
break;
}
buf += dec.decode(value, { stream: true });
const lines = buf.split('\n');
buf = lines.pop() ?? '';
for (const line of lines) {
if (line.startsWith('event: ')) {
eventType = line.slice(7).trim();
} else if (line.startsWith('data: ')) {
const data = line.slice(6).trim();
if (eventType === 'endpoint') {
// Resolve endpoint URL (relative path or absolute) then re-validate
// to prevent SSRF: a malicious server could emit an RFC1918 address.
let resolved;
try {
resolved = new URL(data.startsWith('http') ? data : data, self._sseUrl);
} catch {
self._endpointDeferred.reject(new Error('SSE endpoint event contains invalid URL'));
return;
}
if (resolved.protocol !== 'https:' && resolved.protocol !== 'http:') {
self._endpointDeferred.reject(new Error('SSE endpoint protocol not allowed'));
return;
}
if (BLOCKED_HOST_PATTERNS.some(p => p.test(resolved.hostname))) {
self._endpointDeferred.reject(new Error('SSE endpoint host is blocked'));
return;
}
self._endpointUrl = resolved.toString();
self._endpointDeferred.resolve();
} else {
try {
const msg = JSON.parse(data);
if (msg.id !== undefined) {
const d = self._pending.get(msg.id);
if (d) { self._pending.delete(msg.id); d.resolve(msg); }
}
} catch { /* skip non-JSON data lines */ }
}
eventType = '';
}
}
}
} catch (err) {
self._endpointDeferred.reject(err);
for (const [, d] of self._pending) d.reject(new Error('SSE stream closed'));
}
})();
}
async send(id, method, params) {
const deferred = makeDeferred();
this._pending.set(id, deferred);
const timer = setTimeout(() => {
if (this._pending.has(id)) {
this._pending.delete(id);
deferred.reject(new Error(`RPC ${method} timed out`));
}
}, SSE_RPC_TIMEOUT_MS);
try {
const postResp = await fetch(this._endpointUrl, {
method: 'POST',
headers: { ...this._headers, 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id, method, params }),
signal: AbortSignal.timeout(SSE_RPC_TIMEOUT_MS),
});
if (!postResp.ok) {
this._pending.delete(id);
throw new Error(`${method} POST HTTP ${postResp.status}`);
}
return await deferred.promise;
} finally {
clearTimeout(timer);
}
}
async notify(method, params) {
await fetch(this._endpointUrl, {
method: 'POST',
headers: { ...this._headers, 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', method, params }),
signal: AbortSignal.timeout(5_000),
}).catch(() => {});
}
close() {
try { this._reader?.cancel(); } catch { /* ignore */ }
}
}
async function mcpListToolsSse(serverUrl, customHeaders) {
const headers = buildHeaders(customHeaders);
const session = new SseSession(serverUrl.toString(), headers);
try {
await session.connect();
const initResp = await session.send(1, 'initialize', {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'worldmonitor', version: '1.0' },
});
if (initResp.error) throw new Error(`Initialize error: ${initResp.error.message}`);
await session.notify('notifications/initialized', {});
const listResp = await session.send(2, 'tools/list', {});
if (listResp.error) throw new Error(`tools/list error: ${listResp.error.message}`);
return listResp.result?.tools || [];
} finally {
session.close();
}
}
async function mcpCallToolSse(serverUrl, toolName, toolArgs, customHeaders) {
const headers = buildHeaders(customHeaders);
const session = new SseSession(serverUrl.toString(), headers);
try {
await session.connect();
const initResp = await session.send(1, 'initialize', {
protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'worldmonitor', version: '1.0' },
});
if (initResp.error) throw new Error(`Initialize error: ${initResp.error.message}`);
await session.notify('notifications/initialized', {});
const callResp = await session.send(2, 'tools/call', { name: toolName, arguments: toolArgs || {} });
if (callResp.error) throw new Error(`tools/call error: ${callResp.error.message}`);
return callResp.result;
} finally {
session.close();
}
}
// --- Request handler ---
export default async function handler(req) {
if (isDisallowedOrigin(req))
return new Response('Forbidden', { status: 403 });
const cors = getCorsHeaders(req, 'GET, POST, OPTIONS');
if (req.method === 'OPTIONS')
return new Response(null, { status: 204, headers: cors });
try {
if (req.method === 'GET') {
const url = new URL(req.url);
const rawServer = url.searchParams.get('serverUrl');
const rawHeaders = url.searchParams.get('headers');
if (!rawServer) return jsonResponse({ error: 'Missing serverUrl' }, 400, cors);
const serverUrl = validateServerUrl(rawServer);
if (!serverUrl) return jsonResponse({ error: 'Invalid serverUrl' }, 400, cors);
let customHeaders = {};
if (rawHeaders) {
try { customHeaders = JSON.parse(rawHeaders); } catch { /* ignore */ }
}
const tools = isSseTransport(serverUrl)
? await mcpListToolsSse(serverUrl, customHeaders)
: await mcpListTools(serverUrl, customHeaders);
return jsonResponse({ tools }, 200, cors);
}
if (req.method === 'POST') {
const body = await req.json();
const { serverUrl: rawServer, toolName, toolArgs, customHeaders } = body;
if (!rawServer) return jsonResponse({ error: 'Missing serverUrl' }, 400, cors);
if (!toolName) return jsonResponse({ error: 'Missing toolName' }, 400, cors);
const serverUrl = validateServerUrl(rawServer);
if (!serverUrl) return jsonResponse({ error: 'Invalid serverUrl' }, 400, cors);
const result = isSseTransport(serverUrl)
? await mcpCallToolSse(serverUrl, toolName, toolArgs || {}, customHeaders || {})
: await mcpCallTool(serverUrl, toolName, toolArgs || {}, customHeaders || {});
return jsonResponse({ result }, 200, { ...cors, 'Cache-Control': 'no-store' });
}
return jsonResponse({ error: 'Method not allowed' }, 405, cors);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
const isTimeout = msg.includes('TimeoutError') || msg.includes('timed out');
// Return 422 (not 502) so Cloudflare proxy does not replace our JSON body with its own HTML error page
return jsonResponse({ error: isTimeout ? 'MCP server timed out' : msg }, isTimeout ? 504 : 422, cors);
}
}