@modelcontextprotocol/inspector 1.0.1 → 2.0.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +199 -361
- package/clients/cli/build/index.js +13218 -0
- package/clients/launcher/build/index.js +90 -0
- package/clients/launcher/build/parse-launcher-argv.js +29 -0
- package/clients/tui/build/chunk-MCKGQKYU.js +15 -0
- package/clients/tui/build/index.js +14573 -0
- package/clients/tui/build/undici-HXPKCIY3.js +25789 -0
- package/clients/web/build/chunk-MCKGQKYU.js +15 -0
- package/clients/web/build/index.js +4322 -0
- package/clients/web/build/undici-HXPKCIY3.js +25789 -0
- package/clients/web/dist/assets/css-DfBGKsUM.js +1 -0
- package/clients/web/dist/assets/index-Cbtmmw0V.js +300 -0
- package/clients/web/dist/assets/index-CiUpWldH.css +1 -0
- package/clients/web/dist/assets/json-rfaH9Mx5.js +1 -0
- package/clients/web/dist/assets/markdown-PVXc4EJ0.js +1 -0
- package/clients/web/dist/assets/markup-Bk4keGDK.js +1 -0
- package/clients/web/dist/assets/markup-DPsXihXF.js +1 -0
- package/clients/web/dist/assets/prism-light-B8tIwqDr.js +6 -0
- package/clients/web/dist/assets/tomorrow-COrD2Qnh.js +1 -0
- package/clients/web/dist/assets/yaml-B78V9E0m.js +1 -0
- package/clients/web/dist/icons.svg +24 -0
- package/clients/web/dist/index.html +17 -0
- package/package.json +96 -80
- package/scripts/install-clients.mjs +65 -0
- package/LICENSE +0 -216
- package/cli/build/cli.js +0 -290
- package/cli/build/client/connection.js +0 -38
- package/cli/build/client/index.js +0 -6
- package/cli/build/client/prompts.js +0 -43
- package/cli/build/client/resources.js +0 -36
- package/cli/build/client/tools.js +0 -87
- package/cli/build/client/types.js +0 -1
- package/cli/build/error-handler.js +0 -18
- package/cli/build/index.js +0 -257
- package/cli/build/transport.js +0 -65
- package/cli/build/utils/awaitable-log.js +0 -7
- package/client/bin/client.js +0 -62
- package/client/bin/start.js +0 -355
- package/client/dist/assets/OAuthCallback-DKaW5Tk8.js +0 -55
- package/client/dist/assets/OAuthDebugCallback-Bx3X7Zkh.js +0 -64
- package/client/dist/assets/index-CH-qD91V.js +0 -67487
- package/client/dist/assets/index-DXy0twoH.css +0 -2786
- package/client/dist/index.html +0 -14
- package/server/build/index.js +0 -889
- package/server/build/mcpProxy.js +0 -121
- package/server/build/static/sandbox_proxy.html +0 -197
- package/server/static/sandbox_proxy.html +0 -197
- /package/{client/dist/mcp.svg → clients/web/dist/assets/MCP-CWGQJYyH.svg} +0 -0
package/server/build/index.js
DELETED
|
@@ -1,889 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import cors from "cors";
|
|
3
|
-
import { parseArgs } from "node:util";
|
|
4
|
-
import { parse as shellParseArgs } from "shell-quote";
|
|
5
|
-
import nodeFetch, { Headers as NodeHeaders } from "node-fetch";
|
|
6
|
-
// Type-compatible wrappers for node-fetch to work with browser-style types
|
|
7
|
-
const fetch = nodeFetch;
|
|
8
|
-
const Headers = NodeHeaders;
|
|
9
|
-
import { SSEClientTransport, SseError, } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
10
|
-
import { StdioClientTransport, getDefaultEnvironment, } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
11
|
-
import { StreamableHTTPClientTransport, StreamableHTTPError, } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
12
|
-
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
13
|
-
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
14
|
-
import express from "express";
|
|
15
|
-
import rateLimit from "express-rate-limit";
|
|
16
|
-
import { findActualExecutable } from "spawn-rx";
|
|
17
|
-
import mcpProxy from "./mcpProxy.js";
|
|
18
|
-
import { randomUUID, randomBytes, timingSafeEqual } from "node:crypto";
|
|
19
|
-
import { lookup as dnsLookup } from "node:dns/promises";
|
|
20
|
-
import { isIP } from "node:net";
|
|
21
|
-
import { fileURLToPath } from "url";
|
|
22
|
-
import { dirname, join } from "path";
|
|
23
|
-
import { readFileSync } from "fs";
|
|
24
|
-
const DEFAULT_MCP_PROXY_LISTEN_PORT = "6277";
|
|
25
|
-
const sandboxRateLimiter = rateLimit({
|
|
26
|
-
windowMs: 15 * 60 * 1000, // 15 minutes
|
|
27
|
-
max: 100, // limit each IP to 100 /sandbox requests per windowMs
|
|
28
|
-
});
|
|
29
|
-
const defaultEnvironment = {
|
|
30
|
-
...getDefaultEnvironment(),
|
|
31
|
-
...(process.env.MCP_ENV_VARS ? JSON.parse(process.env.MCP_ENV_VARS) : {}),
|
|
32
|
-
};
|
|
33
|
-
const { values } = parseArgs({
|
|
34
|
-
args: process.argv.slice(2),
|
|
35
|
-
options: {
|
|
36
|
-
env: { type: "string", default: "" },
|
|
37
|
-
args: { type: "string", default: "" },
|
|
38
|
-
command: { type: "string", default: "" },
|
|
39
|
-
transport: { type: "string", default: "" },
|
|
40
|
-
"server-url": { type: "string", default: "" },
|
|
41
|
-
},
|
|
42
|
-
});
|
|
43
|
-
/**
|
|
44
|
-
* Helper function to detect 401 Unauthorized errors from various transport types.
|
|
45
|
-
* StreamableHTTPClientTransport throws a generic Error with "HTTP 401" in the message
|
|
46
|
-
* when there's no authProvider configured, while SSEClientTransport throws SseError.
|
|
47
|
-
*/
|
|
48
|
-
const is401Error = (error) => {
|
|
49
|
-
if (error instanceof SseError && error.code === 401)
|
|
50
|
-
return true;
|
|
51
|
-
if (error instanceof StreamableHTTPError && error.code === 401)
|
|
52
|
-
return true;
|
|
53
|
-
if (error instanceof Error &&
|
|
54
|
-
(error.message.includes("HTTP 401") || error.message.includes("(401)")))
|
|
55
|
-
return true;
|
|
56
|
-
return false;
|
|
57
|
-
};
|
|
58
|
-
/**
|
|
59
|
-
* Sends a sanitized JSON error response to the client without exposing
|
|
60
|
-
* stack traces or internal error details. The full error is expected to
|
|
61
|
-
* have already been logged server-side via console.error.
|
|
62
|
-
*/
|
|
63
|
-
const sendErrorResponse = (res, status, message) => {
|
|
64
|
-
res.status(status).json({ error: message });
|
|
65
|
-
};
|
|
66
|
-
/**
|
|
67
|
-
* Prefer forwarding the upstream MCP 401 (WWW-Authenticate + body) so the browser
|
|
68
|
-
* matches direct-mode OAuth behavior. Falls back to a generic 401 JSON response
|
|
69
|
-
* when no upstream details were captured, to avoid leaking stack traces.
|
|
70
|
-
*/
|
|
71
|
-
const sendProxiedUnauthorized = (res, headerHolder) => {
|
|
72
|
-
const captured = headerHolder?.lastUpstream401;
|
|
73
|
-
if (captured && headerHolder) {
|
|
74
|
-
if (captured.wwwAuthenticate) {
|
|
75
|
-
res.setHeader("WWW-Authenticate", captured.wwwAuthenticate);
|
|
76
|
-
}
|
|
77
|
-
res.status(401);
|
|
78
|
-
res.setHeader("Content-Type", captured.contentType);
|
|
79
|
-
res.send(captured.body);
|
|
80
|
-
delete headerHolder.lastUpstream401;
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
sendErrorResponse(res, 401, "Unauthorized");
|
|
84
|
-
};
|
|
85
|
-
// Function to get HTTP headers.
|
|
86
|
-
const getHttpHeaders = (req) => {
|
|
87
|
-
const headers = {};
|
|
88
|
-
// Iterate over all headers in the request
|
|
89
|
-
for (const key in req.headers) {
|
|
90
|
-
const lowerKey = key.toLowerCase();
|
|
91
|
-
// Check if the header is one we want to forward
|
|
92
|
-
if (lowerKey.startsWith("mcp-") ||
|
|
93
|
-
lowerKey === "authorization" ||
|
|
94
|
-
lowerKey === "last-event-id") {
|
|
95
|
-
// Exclude the proxy's own authentication header and the Client <-> Proxy session ID header
|
|
96
|
-
if (lowerKey !== "x-mcp-proxy-auth" && lowerKey !== "mcp-session-id") {
|
|
97
|
-
const value = req.headers[key];
|
|
98
|
-
if (typeof value === "string") {
|
|
99
|
-
// If the value is a string, use it directly
|
|
100
|
-
headers[key] = value;
|
|
101
|
-
}
|
|
102
|
-
else if (Array.isArray(value)) {
|
|
103
|
-
// If the value is an array, use the last element
|
|
104
|
-
const lastValue = value.at(-1);
|
|
105
|
-
if (lastValue !== undefined) {
|
|
106
|
-
headers[key] = lastValue;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
// If value is undefined, it's skipped, which is correct.
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
// Handle the custom auth header separately. We expect `x-custom-auth-header`
|
|
114
|
-
// to be a string containing the name of the actual authentication header.
|
|
115
|
-
const customAuthHeaderName = req.headers["x-custom-auth-header"];
|
|
116
|
-
if (typeof customAuthHeaderName === "string") {
|
|
117
|
-
const lowerCaseHeaderName = customAuthHeaderName.toLowerCase();
|
|
118
|
-
const value = req.headers[lowerCaseHeaderName];
|
|
119
|
-
if (typeof value === "string") {
|
|
120
|
-
headers[customAuthHeaderName] = value;
|
|
121
|
-
}
|
|
122
|
-
else if (Array.isArray(value)) {
|
|
123
|
-
// If the actual auth header was sent multiple times, use the last value.
|
|
124
|
-
const lastValue = value.at(-1);
|
|
125
|
-
if (lastValue !== undefined) {
|
|
126
|
-
headers[customAuthHeaderName] = lastValue;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
// Handle multiple custom headers (new approach)
|
|
131
|
-
if (req.headers["x-custom-auth-headers"] !== undefined) {
|
|
132
|
-
try {
|
|
133
|
-
const customHeaderNames = JSON.parse(req.headers["x-custom-auth-headers"]);
|
|
134
|
-
if (Array.isArray(customHeaderNames)) {
|
|
135
|
-
customHeaderNames.forEach((headerName) => {
|
|
136
|
-
const lowerCaseHeaderName = headerName.toLowerCase();
|
|
137
|
-
if (req.headers[lowerCaseHeaderName] !== undefined) {
|
|
138
|
-
const value = req.headers[lowerCaseHeaderName];
|
|
139
|
-
headers[headerName] = Array.isArray(value)
|
|
140
|
-
? value[value.length - 1]
|
|
141
|
-
: value;
|
|
142
|
-
}
|
|
143
|
-
});
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
catch (error) {
|
|
147
|
-
console.warn("Failed to parse x-custom-auth-headers:", error);
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
return headers;
|
|
151
|
-
};
|
|
152
|
-
/**
|
|
153
|
-
* Updates a headers object in-place, preserving the original Accept header.
|
|
154
|
-
* This is necessary to ensure that transports holding a reference to the headers
|
|
155
|
-
* object see the updates.
|
|
156
|
-
* @param currentHeaders The headers object to update.
|
|
157
|
-
* @param newHeaders The new headers to apply.
|
|
158
|
-
*/
|
|
159
|
-
const updateHeadersInPlace = (currentHeaders, newHeaders) => {
|
|
160
|
-
// Preserve the Accept header, which is set at transport creation and
|
|
161
|
-
// is not present in subsequent client requests.
|
|
162
|
-
const accept = currentHeaders["Accept"];
|
|
163
|
-
// Clear the old headers and apply the new ones.
|
|
164
|
-
Object.keys(currentHeaders).forEach((key) => delete currentHeaders[key]);
|
|
165
|
-
Object.assign(currentHeaders, newHeaders);
|
|
166
|
-
// Restore the Accept header.
|
|
167
|
-
if (accept) {
|
|
168
|
-
currentHeaders["Accept"] = accept;
|
|
169
|
-
}
|
|
170
|
-
};
|
|
171
|
-
const app = express();
|
|
172
|
-
app.use(cors());
|
|
173
|
-
app.use((req, res, next) => {
|
|
174
|
-
res.header("Access-Control-Expose-Headers", "mcp-session-id, WWW-Authenticate");
|
|
175
|
-
next();
|
|
176
|
-
});
|
|
177
|
-
const webAppTransports = new Map(); // Web app transports by web app sessionId
|
|
178
|
-
const serverTransports = new Map(); // Server Transports by web app sessionId
|
|
179
|
-
const sessionHeaderHolders = new Map(); // For dynamic header updates
|
|
180
|
-
// Use provided token from environment or generate a new one
|
|
181
|
-
const sessionToken = process.env.MCP_PROXY_AUTH_TOKEN || randomBytes(32).toString("hex");
|
|
182
|
-
const authDisabled = !!process.env.DANGEROUSLY_OMIT_AUTH;
|
|
183
|
-
// Origin validation middleware to prevent DNS rebinding attacks
|
|
184
|
-
const originValidationMiddleware = (req, res, next) => {
|
|
185
|
-
const origin = req.headers.origin;
|
|
186
|
-
// Default origins based on CLIENT_PORT or use environment variable
|
|
187
|
-
const clientPort = process.env.CLIENT_PORT || "6274";
|
|
188
|
-
const defaultOrigin = `http://localhost:${clientPort}`;
|
|
189
|
-
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",") || [
|
|
190
|
-
defaultOrigin,
|
|
191
|
-
];
|
|
192
|
-
if (origin && !allowedOrigins.includes(origin)) {
|
|
193
|
-
console.error(`Invalid origin: ${origin}`);
|
|
194
|
-
res.status(403).json({
|
|
195
|
-
error: "Forbidden - invalid origin",
|
|
196
|
-
message: "Request blocked to prevent DNS rebinding attacks. Configure allowed origins via environment variable.",
|
|
197
|
-
});
|
|
198
|
-
return;
|
|
199
|
-
}
|
|
200
|
-
next();
|
|
201
|
-
};
|
|
202
|
-
const authMiddleware = (req, res, next) => {
|
|
203
|
-
if (authDisabled) {
|
|
204
|
-
return next();
|
|
205
|
-
}
|
|
206
|
-
const sendUnauthorized = () => {
|
|
207
|
-
res.status(401).json({
|
|
208
|
-
error: "Unauthorized",
|
|
209
|
-
message: "Authentication required. Use the session token shown in the console when starting the server.",
|
|
210
|
-
});
|
|
211
|
-
};
|
|
212
|
-
const authHeader = req.headers["x-mcp-proxy-auth"];
|
|
213
|
-
const authHeaderValue = Array.isArray(authHeader)
|
|
214
|
-
? authHeader[0]
|
|
215
|
-
: authHeader;
|
|
216
|
-
if (!authHeaderValue || !authHeaderValue.startsWith("Bearer ")) {
|
|
217
|
-
sendUnauthorized();
|
|
218
|
-
return;
|
|
219
|
-
}
|
|
220
|
-
const providedToken = authHeaderValue.substring(7); // Remove 'Bearer ' prefix
|
|
221
|
-
const expectedToken = sessionToken;
|
|
222
|
-
// Convert to buffers for timing-safe comparison
|
|
223
|
-
const providedBuffer = Buffer.from(providedToken);
|
|
224
|
-
const expectedBuffer = Buffer.from(expectedToken);
|
|
225
|
-
// Check length first to prevent timing attacks
|
|
226
|
-
if (providedBuffer.length !== expectedBuffer.length) {
|
|
227
|
-
sendUnauthorized();
|
|
228
|
-
return;
|
|
229
|
-
}
|
|
230
|
-
// Perform timing-safe comparison
|
|
231
|
-
if (!timingSafeEqual(providedBuffer, expectedBuffer)) {
|
|
232
|
-
sendUnauthorized();
|
|
233
|
-
return;
|
|
234
|
-
}
|
|
235
|
-
next();
|
|
236
|
-
};
|
|
237
|
-
/**
|
|
238
|
-
* Converts a Node.js ReadableStream to a web-compatible ReadableStream
|
|
239
|
-
* This is necessary for the EventSource polyfill which expects web streams
|
|
240
|
-
*/
|
|
241
|
-
const createWebReadableStream = (nodeStream) => {
|
|
242
|
-
let closed = false;
|
|
243
|
-
return new ReadableStream({
|
|
244
|
-
start(controller) {
|
|
245
|
-
nodeStream.on("data", (chunk) => {
|
|
246
|
-
if (!closed) {
|
|
247
|
-
controller.enqueue(chunk);
|
|
248
|
-
}
|
|
249
|
-
});
|
|
250
|
-
nodeStream.on("end", () => {
|
|
251
|
-
if (!closed) {
|
|
252
|
-
closed = true;
|
|
253
|
-
controller.close();
|
|
254
|
-
}
|
|
255
|
-
});
|
|
256
|
-
nodeStream.on("error", (err) => {
|
|
257
|
-
if (!closed) {
|
|
258
|
-
closed = true;
|
|
259
|
-
controller.error(err);
|
|
260
|
-
}
|
|
261
|
-
});
|
|
262
|
-
},
|
|
263
|
-
cancel() {
|
|
264
|
-
closed = true;
|
|
265
|
-
nodeStream.destroy();
|
|
266
|
-
},
|
|
267
|
-
});
|
|
268
|
-
};
|
|
269
|
-
/**
|
|
270
|
-
* Creates a `fetch` function that merges dynamic session headers with the
|
|
271
|
-
* headers from the actual request, ensuring that request-specific headers like
|
|
272
|
-
* `Content-Type` are preserved. For SSE requests, it also converts Node.js
|
|
273
|
-
* streams to web-compatible streams.
|
|
274
|
-
*/
|
|
275
|
-
const createCustomFetch = (headerHolder) => {
|
|
276
|
-
return async (input, init) => {
|
|
277
|
-
// Determine the headers from the original request/init.
|
|
278
|
-
// The SDK may pass a Request object or a URL and an init object.
|
|
279
|
-
const originalHeaders = input instanceof Request ? input.headers : init?.headers;
|
|
280
|
-
// Start with our dynamic session headers.
|
|
281
|
-
const finalHeaders = new Headers(headerHolder.headers);
|
|
282
|
-
// Merge the SDK's request-specific headers, letting them overwrite.
|
|
283
|
-
// This is crucial for preserving Content-Type on POST requests.
|
|
284
|
-
new Headers(originalHeaders).forEach((value, key) => {
|
|
285
|
-
finalHeaders.set(key, value);
|
|
286
|
-
});
|
|
287
|
-
// Convert Headers to a plain object for node-fetch compatibility
|
|
288
|
-
const headersObject = {};
|
|
289
|
-
finalHeaders.forEach((value, key) => {
|
|
290
|
-
headersObject[key] = value;
|
|
291
|
-
});
|
|
292
|
-
// Get the response from node-fetch (cast input and init to handle type differences)
|
|
293
|
-
const response = await fetch(input, { ...init, headers: headersObject });
|
|
294
|
-
if (response.status === 401) {
|
|
295
|
-
const wwwAuthenticate = response.headers.get("www-authenticate") ?? undefined;
|
|
296
|
-
const contentType = response.headers.get("content-type") ?? "application/json";
|
|
297
|
-
const body = await response.text();
|
|
298
|
-
headerHolder.lastUpstream401 = {
|
|
299
|
-
wwwAuthenticate,
|
|
300
|
-
body,
|
|
301
|
-
contentType,
|
|
302
|
-
};
|
|
303
|
-
const responseHeaders = {};
|
|
304
|
-
response.headers.forEach((value, key) => {
|
|
305
|
-
responseHeaders[key] = value;
|
|
306
|
-
});
|
|
307
|
-
return new Response(body, {
|
|
308
|
-
status: 401,
|
|
309
|
-
statusText: response.statusText,
|
|
310
|
-
headers: responseHeaders,
|
|
311
|
-
});
|
|
312
|
-
}
|
|
313
|
-
// Check if this is an SSE request by looking at the Accept header
|
|
314
|
-
const acceptHeader = finalHeaders.get("Accept");
|
|
315
|
-
const isSSE = acceptHeader?.includes("text/event-stream");
|
|
316
|
-
if (isSSE && response.body) {
|
|
317
|
-
// For SSE requests, we need to convert the Node.js stream to a web ReadableStream
|
|
318
|
-
// because the EventSource polyfill expects web-compatible streams
|
|
319
|
-
const webStream = createWebReadableStream(response.body);
|
|
320
|
-
// Create a new response with the web-compatible stream
|
|
321
|
-
// Convert node-fetch headers to plain object for web Response compatibility
|
|
322
|
-
const responseHeaders = {};
|
|
323
|
-
response.headers.forEach((value, key) => {
|
|
324
|
-
responseHeaders[key] = value;
|
|
325
|
-
});
|
|
326
|
-
return new Response(webStream, {
|
|
327
|
-
status: response.status,
|
|
328
|
-
statusText: response.statusText,
|
|
329
|
-
headers: responseHeaders,
|
|
330
|
-
});
|
|
331
|
-
}
|
|
332
|
-
// For non-SSE requests, return the response as-is (cast to handle type differences)
|
|
333
|
-
return response;
|
|
334
|
-
};
|
|
335
|
-
};
|
|
336
|
-
const createTransport = async (req) => {
|
|
337
|
-
const query = req.query;
|
|
338
|
-
console.log("Query parameters:", JSON.stringify(query));
|
|
339
|
-
const transportType = query.transportType;
|
|
340
|
-
if (transportType === "stdio") {
|
|
341
|
-
const command = query.command.trim();
|
|
342
|
-
const origArgs = shellParseArgs(query.args);
|
|
343
|
-
const queryEnv = query.env ? JSON.parse(query.env) : {};
|
|
344
|
-
const env = { ...defaultEnvironment, ...process.env, ...queryEnv };
|
|
345
|
-
const { cmd, args } = findActualExecutable(command, origArgs);
|
|
346
|
-
console.log(`STDIO transport: command=${cmd}, args=${args}`);
|
|
347
|
-
const transport = new StdioClientTransport({
|
|
348
|
-
command: cmd,
|
|
349
|
-
args,
|
|
350
|
-
env,
|
|
351
|
-
stderr: "pipe",
|
|
352
|
-
});
|
|
353
|
-
await transport.start();
|
|
354
|
-
return { transport };
|
|
355
|
-
}
|
|
356
|
-
else if (transportType === "sse") {
|
|
357
|
-
const url = query.url;
|
|
358
|
-
const headers = getHttpHeaders(req);
|
|
359
|
-
headers["Accept"] = "text/event-stream";
|
|
360
|
-
const headerHolder = { headers };
|
|
361
|
-
console.log(`SSE transport: url=${url}, headers=${JSON.stringify(headers)}`);
|
|
362
|
-
const transport = new SSEClientTransport(new URL(url), {
|
|
363
|
-
eventSourceInit: {
|
|
364
|
-
fetch: createCustomFetch(headerHolder),
|
|
365
|
-
},
|
|
366
|
-
requestInit: {
|
|
367
|
-
headers: headerHolder.headers,
|
|
368
|
-
},
|
|
369
|
-
});
|
|
370
|
-
await transport.start();
|
|
371
|
-
return { transport, headerHolder };
|
|
372
|
-
}
|
|
373
|
-
else if (transportType === "streamable-http") {
|
|
374
|
-
const headers = getHttpHeaders(req);
|
|
375
|
-
headers["Accept"] = "text/event-stream, application/json";
|
|
376
|
-
const headerHolder = { headers };
|
|
377
|
-
const transport = new StreamableHTTPClientTransport(new URL(query.url), {
|
|
378
|
-
// Pass a custom fetch to inject the latest headers on each request
|
|
379
|
-
fetch: createCustomFetch(headerHolder),
|
|
380
|
-
});
|
|
381
|
-
await transport.start();
|
|
382
|
-
return { transport, headerHolder };
|
|
383
|
-
}
|
|
384
|
-
else {
|
|
385
|
-
console.error(`Invalid transport type: ${transportType}`);
|
|
386
|
-
throw new Error("Invalid transport type specified");
|
|
387
|
-
}
|
|
388
|
-
};
|
|
389
|
-
app.get("/mcp", originValidationMiddleware, authMiddleware, async (req, res) => {
|
|
390
|
-
const sessionId = req.headers["mcp-session-id"];
|
|
391
|
-
console.log(`Received GET message for sessionId ${sessionId}`);
|
|
392
|
-
const headerHolder = sessionHeaderHolders.get(sessionId);
|
|
393
|
-
if (headerHolder) {
|
|
394
|
-
updateHeadersInPlace(headerHolder.headers, getHttpHeaders(req));
|
|
395
|
-
}
|
|
396
|
-
try {
|
|
397
|
-
const transport = webAppTransports.get(sessionId);
|
|
398
|
-
if (!transport) {
|
|
399
|
-
res.status(404).end("Session not found");
|
|
400
|
-
return;
|
|
401
|
-
}
|
|
402
|
-
else {
|
|
403
|
-
await transport.handleRequest(req, res);
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
catch (error) {
|
|
407
|
-
console.error("Error in /mcp route:", error);
|
|
408
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
409
|
-
}
|
|
410
|
-
});
|
|
411
|
-
app.post("/mcp", originValidationMiddleware, authMiddleware, async (req, res) => {
|
|
412
|
-
const sessionId = req.headers["mcp-session-id"];
|
|
413
|
-
if (sessionId) {
|
|
414
|
-
console.log(`Received POST message for sessionId ${sessionId}`);
|
|
415
|
-
const headerHolder = sessionHeaderHolders.get(sessionId);
|
|
416
|
-
if (headerHolder) {
|
|
417
|
-
updateHeadersInPlace(headerHolder.headers, getHttpHeaders(req));
|
|
418
|
-
}
|
|
419
|
-
try {
|
|
420
|
-
const transport = webAppTransports.get(sessionId);
|
|
421
|
-
if (!transport) {
|
|
422
|
-
res.status(404).end("Transport not found for sessionId " + sessionId);
|
|
423
|
-
}
|
|
424
|
-
else {
|
|
425
|
-
await transport.handleRequest(req, res);
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
catch (error) {
|
|
429
|
-
console.error("Error in /mcp route:", error);
|
|
430
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
else {
|
|
434
|
-
console.log("New StreamableHttp connection request");
|
|
435
|
-
let streamableHeaderHolder;
|
|
436
|
-
try {
|
|
437
|
-
const { transport: serverTransport, headerHolder } = await createTransport(req);
|
|
438
|
-
streamableHeaderHolder = headerHolder;
|
|
439
|
-
const webAppTransport = new StreamableHTTPServerTransport({
|
|
440
|
-
sessionIdGenerator: randomUUID,
|
|
441
|
-
onsessioninitialized: (sessionId) => {
|
|
442
|
-
webAppTransports.set(sessionId, webAppTransport);
|
|
443
|
-
serverTransports.set(sessionId, serverTransport); // eslint-disable-line @typescript-eslint/no-non-null-assertion
|
|
444
|
-
if (headerHolder) {
|
|
445
|
-
sessionHeaderHolders.set(sessionId, headerHolder);
|
|
446
|
-
}
|
|
447
|
-
console.log("Client <-> Proxy sessionId: " + sessionId);
|
|
448
|
-
},
|
|
449
|
-
onsessionclosed: (sessionId) => {
|
|
450
|
-
webAppTransports.delete(sessionId);
|
|
451
|
-
serverTransports.delete(sessionId);
|
|
452
|
-
sessionHeaderHolders.delete(sessionId);
|
|
453
|
-
},
|
|
454
|
-
});
|
|
455
|
-
console.log("Created StreamableHttp client transport");
|
|
456
|
-
await webAppTransport.start();
|
|
457
|
-
mcpProxy({
|
|
458
|
-
transportToClient: webAppTransport,
|
|
459
|
-
transportToServer: serverTransport,
|
|
460
|
-
headerHolder,
|
|
461
|
-
});
|
|
462
|
-
await webAppTransport.handleRequest(req, res, req.body);
|
|
463
|
-
}
|
|
464
|
-
catch (error) {
|
|
465
|
-
if (is401Error(error)) {
|
|
466
|
-
console.error("Received 401 Unauthorized from MCP server:", error instanceof Error ? error.message : error);
|
|
467
|
-
sendProxiedUnauthorized(res, streamableHeaderHolder);
|
|
468
|
-
return;
|
|
469
|
-
}
|
|
470
|
-
console.error("Error in /mcp POST route:", error);
|
|
471
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
});
|
|
475
|
-
app.delete("/mcp", originValidationMiddleware, authMiddleware, async (req, res) => {
|
|
476
|
-
const sessionId = req.headers["mcp-session-id"];
|
|
477
|
-
console.log(`Received DELETE message for sessionId ${sessionId}`);
|
|
478
|
-
if (sessionId) {
|
|
479
|
-
try {
|
|
480
|
-
const serverTransport = serverTransports.get(sessionId);
|
|
481
|
-
if (!serverTransport) {
|
|
482
|
-
res.status(404).end("Transport not found for sessionId " + sessionId);
|
|
483
|
-
}
|
|
484
|
-
else {
|
|
485
|
-
await serverTransport.terminateSession();
|
|
486
|
-
await serverTransport.close();
|
|
487
|
-
webAppTransports.delete(sessionId);
|
|
488
|
-
serverTransports.delete(sessionId);
|
|
489
|
-
sessionHeaderHolders.delete(sessionId);
|
|
490
|
-
console.log(`Transports removed for sessionId ${sessionId}`);
|
|
491
|
-
}
|
|
492
|
-
res.status(200).end();
|
|
493
|
-
}
|
|
494
|
-
catch (error) {
|
|
495
|
-
console.error("Error in /mcp route:", error);
|
|
496
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
});
|
|
500
|
-
app.get("/stdio", originValidationMiddleware, authMiddleware, async (req, res) => {
|
|
501
|
-
try {
|
|
502
|
-
console.log("New STDIO connection request");
|
|
503
|
-
const { transport: serverTransport } = await createTransport(req);
|
|
504
|
-
const proxyFullAddress = req.query.proxyFullAddress || "";
|
|
505
|
-
const prefix = proxyFullAddress || "";
|
|
506
|
-
const endpoint = `${prefix}/message`;
|
|
507
|
-
const webAppTransport = new SSEServerTransport(endpoint, res);
|
|
508
|
-
webAppTransports.set(webAppTransport.sessionId, webAppTransport);
|
|
509
|
-
console.log("Created client transport");
|
|
510
|
-
serverTransports.set(webAppTransport.sessionId, serverTransport);
|
|
511
|
-
console.log("Created server transport");
|
|
512
|
-
await webAppTransport.start();
|
|
513
|
-
serverTransport.stderr.on("data", (chunk) => {
|
|
514
|
-
if (chunk.toString().includes("MODULE_NOT_FOUND")) {
|
|
515
|
-
// Server command not found, remove transports
|
|
516
|
-
const message = "Command not found, transports removed";
|
|
517
|
-
webAppTransport.send({
|
|
518
|
-
jsonrpc: "2.0",
|
|
519
|
-
method: "notifications/message",
|
|
520
|
-
params: {
|
|
521
|
-
level: "emergency",
|
|
522
|
-
logger: "proxy",
|
|
523
|
-
data: {
|
|
524
|
-
message,
|
|
525
|
-
},
|
|
526
|
-
},
|
|
527
|
-
});
|
|
528
|
-
webAppTransport.close();
|
|
529
|
-
serverTransport.close();
|
|
530
|
-
webAppTransports.delete(webAppTransport.sessionId);
|
|
531
|
-
serverTransports.delete(webAppTransport.sessionId);
|
|
532
|
-
sessionHeaderHolders.delete(webAppTransport.sessionId);
|
|
533
|
-
console.error(message);
|
|
534
|
-
}
|
|
535
|
-
else {
|
|
536
|
-
// Inspect message and attempt to assign a RFC 5424 Syslog Protocol level
|
|
537
|
-
let level;
|
|
538
|
-
let message = chunk.toString().trim();
|
|
539
|
-
let ucMsg = chunk.toString().toUpperCase();
|
|
540
|
-
if (ucMsg.includes("DEBUG")) {
|
|
541
|
-
level = "debug";
|
|
542
|
-
}
|
|
543
|
-
else if (ucMsg.includes("INFO")) {
|
|
544
|
-
level = "info";
|
|
545
|
-
}
|
|
546
|
-
else if (ucMsg.includes("NOTICE")) {
|
|
547
|
-
level = "notice";
|
|
548
|
-
}
|
|
549
|
-
else if (ucMsg.includes("WARN")) {
|
|
550
|
-
level = "warning";
|
|
551
|
-
}
|
|
552
|
-
else if (ucMsg.includes("ERROR")) {
|
|
553
|
-
level = "error";
|
|
554
|
-
}
|
|
555
|
-
else if (ucMsg.includes("CRITICAL")) {
|
|
556
|
-
level = "critical";
|
|
557
|
-
}
|
|
558
|
-
else if (ucMsg.includes("ALERT")) {
|
|
559
|
-
level = "alert";
|
|
560
|
-
}
|
|
561
|
-
else if (ucMsg.includes("EMERGENCY")) {
|
|
562
|
-
level = "emergency";
|
|
563
|
-
}
|
|
564
|
-
else if (ucMsg.includes("SIGINT")) {
|
|
565
|
-
message = "SIGINT received. Server shutdown.";
|
|
566
|
-
level = "emergency";
|
|
567
|
-
}
|
|
568
|
-
else if (ucMsg.includes("SIGHUP")) {
|
|
569
|
-
message = "SIGHUP received. Server shutdown.";
|
|
570
|
-
level = "emergency";
|
|
571
|
-
}
|
|
572
|
-
else if (ucMsg.includes("SIGTERM")) {
|
|
573
|
-
message = "SIGTERM received. Server shutdown.";
|
|
574
|
-
level = "emergency";
|
|
575
|
-
}
|
|
576
|
-
else {
|
|
577
|
-
level = "info";
|
|
578
|
-
}
|
|
579
|
-
webAppTransport.send({
|
|
580
|
-
jsonrpc: "2.0",
|
|
581
|
-
method: "notifications/message",
|
|
582
|
-
params: {
|
|
583
|
-
level,
|
|
584
|
-
logger: "stdio",
|
|
585
|
-
data: {
|
|
586
|
-
message,
|
|
587
|
-
},
|
|
588
|
-
},
|
|
589
|
-
});
|
|
590
|
-
}
|
|
591
|
-
});
|
|
592
|
-
mcpProxy({
|
|
593
|
-
transportToClient: webAppTransport,
|
|
594
|
-
transportToServer: serverTransport,
|
|
595
|
-
});
|
|
596
|
-
}
|
|
597
|
-
catch (error) {
|
|
598
|
-
if (is401Error(error)) {
|
|
599
|
-
console.error("Received 401 Unauthorized from MCP server. Authentication failure.");
|
|
600
|
-
sendProxiedUnauthorized(res, undefined);
|
|
601
|
-
return;
|
|
602
|
-
}
|
|
603
|
-
console.error("Error in /stdio route:", error);
|
|
604
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
605
|
-
}
|
|
606
|
-
});
|
|
607
|
-
app.get("/sse", originValidationMiddleware, authMiddleware, async (req, res) => {
|
|
608
|
-
let sseHeaderHolder;
|
|
609
|
-
try {
|
|
610
|
-
console.log("New SSE connection request. NOTE: The SSE transport is deprecated and has been replaced by StreamableHttp");
|
|
611
|
-
const { transport: serverTransport, headerHolder } = await createTransport(req);
|
|
612
|
-
sseHeaderHolder = headerHolder;
|
|
613
|
-
const proxyFullAddress = req.query.proxyFullAddress || "";
|
|
614
|
-
const prefix = proxyFullAddress || "";
|
|
615
|
-
const endpoint = `${prefix}/message`;
|
|
616
|
-
const webAppTransport = new SSEServerTransport(endpoint, res);
|
|
617
|
-
webAppTransports.set(webAppTransport.sessionId, webAppTransport);
|
|
618
|
-
console.log("Created client transport");
|
|
619
|
-
serverTransports.set(webAppTransport.sessionId, serverTransport); // eslint-disable-line @typescript-eslint/no-non-null-assertion
|
|
620
|
-
if (headerHolder) {
|
|
621
|
-
sessionHeaderHolders.set(webAppTransport.sessionId, headerHolder);
|
|
622
|
-
}
|
|
623
|
-
console.log("Created server transport");
|
|
624
|
-
await webAppTransport.start();
|
|
625
|
-
mcpProxy({
|
|
626
|
-
transportToClient: webAppTransport,
|
|
627
|
-
transportToServer: serverTransport,
|
|
628
|
-
headerHolder,
|
|
629
|
-
});
|
|
630
|
-
}
|
|
631
|
-
catch (error) {
|
|
632
|
-
if (is401Error(error)) {
|
|
633
|
-
console.error("Received 401 Unauthorized from MCP server. Authentication failure.");
|
|
634
|
-
sendProxiedUnauthorized(res, sseHeaderHolder);
|
|
635
|
-
return;
|
|
636
|
-
}
|
|
637
|
-
else if (error instanceof SseError && error.code === 404) {
|
|
638
|
-
console.error("Received 404 not found from MCP server. Does the MCP server support SSE?");
|
|
639
|
-
sendErrorResponse(res, 404, "MCP server returned 404. Does it support SSE?");
|
|
640
|
-
return;
|
|
641
|
-
}
|
|
642
|
-
else if (error instanceof Error &&
|
|
643
|
-
(error.message.includes("ECONNREFUSED") ||
|
|
644
|
-
(error.cause && String(error.cause).includes("ECONNREFUSED")))) {
|
|
645
|
-
console.error("Connection refused. Is the MCP server running?");
|
|
646
|
-
sendErrorResponse(res, 500, "Connection refused. Is the MCP server running?");
|
|
647
|
-
return;
|
|
648
|
-
}
|
|
649
|
-
console.error("Error in /sse route:", error);
|
|
650
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
651
|
-
}
|
|
652
|
-
});
|
|
653
|
-
app.post("/message", originValidationMiddleware, authMiddleware, async (req, res) => {
|
|
654
|
-
try {
|
|
655
|
-
const sessionId = req.query.sessionId;
|
|
656
|
-
console.log(`Received POST message for sessionId ${sessionId}`);
|
|
657
|
-
const headerHolder = sessionHeaderHolders.get(sessionId);
|
|
658
|
-
if (headerHolder) {
|
|
659
|
-
updateHeadersInPlace(headerHolder.headers, getHttpHeaders(req));
|
|
660
|
-
}
|
|
661
|
-
const transport = webAppTransports.get(sessionId);
|
|
662
|
-
if (!transport) {
|
|
663
|
-
res.status(404).end("Session not found");
|
|
664
|
-
return;
|
|
665
|
-
}
|
|
666
|
-
await transport.handlePostMessage(req, res);
|
|
667
|
-
}
|
|
668
|
-
catch (error) {
|
|
669
|
-
console.error("Error in /message route:", error);
|
|
670
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
671
|
-
}
|
|
672
|
-
});
|
|
673
|
-
app.get("/health", (req, res) => {
|
|
674
|
-
res.json({
|
|
675
|
-
status: "ok",
|
|
676
|
-
});
|
|
677
|
-
});
|
|
678
|
-
// Raised when the /fetch proxy is asked to reach a disallowed target, so the
|
|
679
|
-
// route can distinguish an SSRF rejection (403) from an upstream failure (500).
|
|
680
|
-
class ProxyTargetError extends Error {
|
|
681
|
-
}
|
|
682
|
-
const MAX_PROXY_REDIRECTS = 5;
|
|
683
|
-
// The /fetch proxy is used by the client to reach OAuth discovery/token
|
|
684
|
-
// endpoints on the connected MCP server (bypassing browser CORS). Connecting
|
|
685
|
-
// to loopback and RFC1918/private LAN hosts is a core use case (testing local
|
|
686
|
-
// or self-hosted MCP servers), so those stay reachable. We only block
|
|
687
|
-
// link-local addresses — 169.254.0.0/16 (the AWS/GCP/Azure/etc. cloud metadata
|
|
688
|
-
// endpoint 169.254.169.254 lives here) and IPv6 link-local / the AWS IPv6 IMDS
|
|
689
|
-
// address — which are never legitimate proxy targets and are the real SSRF
|
|
690
|
-
// exfiltration vector.
|
|
691
|
-
function isBlockedProxyAddress(ip) {
|
|
692
|
-
const kind = isIP(ip);
|
|
693
|
-
if (kind === 4) {
|
|
694
|
-
const parts = ip.split(".").map(Number);
|
|
695
|
-
// 169.254.0.0/16 — IPv4 link-local (incl. cloud metadata 169.254.169.254)
|
|
696
|
-
return parts[0] === 169 && parts[1] === 254;
|
|
697
|
-
}
|
|
698
|
-
if (kind === 6) {
|
|
699
|
-
const addr = ip.toLowerCase();
|
|
700
|
-
// IPv4-mapped IPv6 (::ffff:x). The WHATWG URL parser serializes the embedded
|
|
701
|
-
// IPv4 in hex (::ffff:a9fe:a9fe for 169.254.169.254), while DNS and other
|
|
702
|
-
// sources may use the dotted form (::ffff:169.254.169.254) — handle both by
|
|
703
|
-
// extracting the IPv4 and re-checking it.
|
|
704
|
-
const mapped = addr.match(/^::ffff:(.+)$/);
|
|
705
|
-
if (mapped) {
|
|
706
|
-
const tail = mapped[1];
|
|
707
|
-
if (isIP(tail) === 4) {
|
|
708
|
-
return isBlockedProxyAddress(tail);
|
|
709
|
-
}
|
|
710
|
-
const hex = tail.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
|
711
|
-
if (hex) {
|
|
712
|
-
const high = parseInt(hex[1], 16);
|
|
713
|
-
const low = parseInt(hex[2], 16);
|
|
714
|
-
return isBlockedProxyAddress(`${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`);
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
// fe80::/10 — IPv6 link-local
|
|
718
|
-
if (/^fe[89ab]/.test(addr)) {
|
|
719
|
-
return true;
|
|
720
|
-
}
|
|
721
|
-
// fd00:ec2::254 — AWS IPv6 instance metadata endpoint
|
|
722
|
-
return addr === "fd00:ec2::254";
|
|
723
|
-
}
|
|
724
|
-
return false;
|
|
725
|
-
}
|
|
726
|
-
// Resolves the target host and rejects it if any resolved address is a blocked
|
|
727
|
-
// (link-local/metadata) address, mitigating SSRF including the DNS case where a
|
|
728
|
-
// hostname resolves to the cloud metadata IP.
|
|
729
|
-
async function assertSafeProxyTarget(parsedUrl) {
|
|
730
|
-
const host = parsedUrl.hostname.replace(/^\[|\]$/g, ""); // strip IPv6 brackets
|
|
731
|
-
let addresses;
|
|
732
|
-
if (isIP(host)) {
|
|
733
|
-
addresses = [host];
|
|
734
|
-
}
|
|
735
|
-
else {
|
|
736
|
-
try {
|
|
737
|
-
addresses = (await dnsLookup(host, { all: true })).map((r) => r.address);
|
|
738
|
-
}
|
|
739
|
-
catch {
|
|
740
|
-
throw new ProxyTargetError(`Could not resolve host: ${host}`);
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
if (addresses.length === 0) {
|
|
744
|
-
throw new ProxyTargetError(`Could not resolve host: ${host}`);
|
|
745
|
-
}
|
|
746
|
-
for (const address of addresses) {
|
|
747
|
-
if (isBlockedProxyAddress(address)) {
|
|
748
|
-
throw new ProxyTargetError(`Refusing to proxy request to blocked address (${address})`);
|
|
749
|
-
}
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
// Fetch that follows redirects manually so every hop's target is re-validated
|
|
753
|
-
// against assertSafeProxyTarget — otherwise an allowed host could redirect the
|
|
754
|
-
// proxy into a blocked internal/metadata address.
|
|
755
|
-
async function safeProxyFetch(initialUrl, init) {
|
|
756
|
-
let currentUrl = new URL(initialUrl);
|
|
757
|
-
let method = init?.method ?? "GET";
|
|
758
|
-
let body = init?.body;
|
|
759
|
-
const headers = init?.headers ?? {};
|
|
760
|
-
for (let hop = 0; hop <= MAX_PROXY_REDIRECTS; hop++) {
|
|
761
|
-
if (!["http:", "https:"].includes(currentUrl.protocol)) {
|
|
762
|
-
throw new ProxyTargetError("Only http/https URLs are allowed");
|
|
763
|
-
}
|
|
764
|
-
await assertSafeProxyTarget(currentUrl);
|
|
765
|
-
const response = await fetch(currentUrl.toString(), {
|
|
766
|
-
method,
|
|
767
|
-
headers,
|
|
768
|
-
body,
|
|
769
|
-
redirect: "manual",
|
|
770
|
-
});
|
|
771
|
-
if (response.status >= 300 && response.status < 400) {
|
|
772
|
-
const location = response.headers.get("location");
|
|
773
|
-
if (!location) {
|
|
774
|
-
return response;
|
|
775
|
-
}
|
|
776
|
-
currentUrl = new URL(location, currentUrl);
|
|
777
|
-
// Mirror browser/fetch semantics: 301/302/303 downgrade to a bodyless GET.
|
|
778
|
-
if ([301, 302, 303].includes(response.status)) {
|
|
779
|
-
method = "GET";
|
|
780
|
-
body = undefined;
|
|
781
|
-
}
|
|
782
|
-
continue;
|
|
783
|
-
}
|
|
784
|
-
return response;
|
|
785
|
-
}
|
|
786
|
-
throw new ProxyTargetError("Too many redirects");
|
|
787
|
-
}
|
|
788
|
-
app.post("/fetch", express.json(), originValidationMiddleware, authMiddleware, async (req, res) => {
|
|
789
|
-
try {
|
|
790
|
-
const { url, init } = req.body;
|
|
791
|
-
if (typeof url !== "string" || url.length === 0) {
|
|
792
|
-
res.status(400).json({ error: "Missing or invalid url" });
|
|
793
|
-
return;
|
|
794
|
-
}
|
|
795
|
-
let parsedUrl;
|
|
796
|
-
try {
|
|
797
|
-
parsedUrl = new URL(url);
|
|
798
|
-
}
|
|
799
|
-
catch {
|
|
800
|
-
res.status(400).json({ error: "Invalid URL" });
|
|
801
|
-
return;
|
|
802
|
-
}
|
|
803
|
-
if (!["http:", "https:"].includes(parsedUrl.protocol)) {
|
|
804
|
-
res.status(400).json({ error: "Only http/https URLs are allowed" });
|
|
805
|
-
return;
|
|
806
|
-
}
|
|
807
|
-
let response;
|
|
808
|
-
try {
|
|
809
|
-
response = await safeProxyFetch(url, init);
|
|
810
|
-
}
|
|
811
|
-
catch (error) {
|
|
812
|
-
if (error instanceof ProxyTargetError) {
|
|
813
|
-
res.status(403).json({ error: error.message });
|
|
814
|
-
return;
|
|
815
|
-
}
|
|
816
|
-
throw error;
|
|
817
|
-
}
|
|
818
|
-
const responseBody = await response.text();
|
|
819
|
-
const headers = {};
|
|
820
|
-
response.headers.forEach((value, key) => {
|
|
821
|
-
headers[key] = value;
|
|
822
|
-
});
|
|
823
|
-
res.status(response.status).json({
|
|
824
|
-
ok: response.ok,
|
|
825
|
-
status: response.status,
|
|
826
|
-
statusText: response.statusText,
|
|
827
|
-
headers,
|
|
828
|
-
body: responseBody,
|
|
829
|
-
});
|
|
830
|
-
}
|
|
831
|
-
catch (error) {
|
|
832
|
-
console.error("Error in /fetch route:", error);
|
|
833
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
834
|
-
}
|
|
835
|
-
});
|
|
836
|
-
app.get("/config", originValidationMiddleware, authMiddleware, (req, res) => {
|
|
837
|
-
try {
|
|
838
|
-
res.json({
|
|
839
|
-
defaultEnvironment,
|
|
840
|
-
defaultCommand: values.command,
|
|
841
|
-
defaultArgs: values.args,
|
|
842
|
-
defaultTransport: values.transport,
|
|
843
|
-
defaultServerUrl: values["server-url"],
|
|
844
|
-
});
|
|
845
|
-
}
|
|
846
|
-
catch (error) {
|
|
847
|
-
console.error("Error in /config route:", error);
|
|
848
|
-
sendErrorResponse(res, 500, "Internal server error");
|
|
849
|
-
}
|
|
850
|
-
});
|
|
851
|
-
app.get("/sandbox", sandboxRateLimiter, (req, res) => {
|
|
852
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
853
|
-
const __dirname = dirname(__filename);
|
|
854
|
-
const filePath = join(__dirname, "..", "static", "sandbox_proxy.html");
|
|
855
|
-
let sandboxHtml;
|
|
856
|
-
try {
|
|
857
|
-
sandboxHtml = readFileSync(filePath, "utf-8");
|
|
858
|
-
}
|
|
859
|
-
catch (e) {
|
|
860
|
-
sandboxHtml = "MCP Apps sandbox not loaded: " + e;
|
|
861
|
-
}
|
|
862
|
-
res.set("Cache-Control", "no-cache, no-store, max-age=0");
|
|
863
|
-
res.send(sandboxHtml);
|
|
864
|
-
});
|
|
865
|
-
const PORT = parseInt(process.env.SERVER_PORT || DEFAULT_MCP_PROXY_LISTEN_PORT, 10);
|
|
866
|
-
const HOST = process.env.HOST || "localhost";
|
|
867
|
-
const server = app.listen(PORT, HOST);
|
|
868
|
-
server.on("listening", () => {
|
|
869
|
-
console.log(`\n⚠️ @modelcontextprotocol/inspector v1 is deprecated.\n` +
|
|
870
|
-
` Upgrade: npx @modelcontextprotocol/inspector@latest\n` +
|
|
871
|
-
` v1 receives security fixes only.\n`);
|
|
872
|
-
console.log(`⚙️ Proxy server listening on ${HOST}:${PORT}`);
|
|
873
|
-
if (!authDisabled) {
|
|
874
|
-
console.log(`🔑 Session token: ${sessionToken}\n ` +
|
|
875
|
-
`Use this token to authenticate requests or set DANGEROUSLY_OMIT_AUTH=true to disable auth`);
|
|
876
|
-
}
|
|
877
|
-
else {
|
|
878
|
-
console.log(`⚠️ WARNING: Authentication is disabled. This is not recommended.`);
|
|
879
|
-
}
|
|
880
|
-
});
|
|
881
|
-
server.on("error", (err) => {
|
|
882
|
-
if (err.message.includes(`EADDRINUSE`)) {
|
|
883
|
-
console.error(`❌ Proxy Server PORT IS IN USE at port ${PORT} ❌ `);
|
|
884
|
-
}
|
|
885
|
-
else {
|
|
886
|
-
console.error(err.message);
|
|
887
|
-
}
|
|
888
|
-
process.exit(1);
|
|
889
|
-
});
|