Spaces:
Runtime error
Runtime error
File size: 1,804 Bytes
5b12974 | 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 | export async function proxyRequest(
request: Request,
targetUrl: string,
token: string,
): Promise<Response> {
try {
const targetURL = new URL(targetUrl);
const headers = new Headers();
// Copy relevant headers from the original request
const headersToProxy = [
"content-type",
"user-agent",
"accept",
"accept-language",
"accept-encoding",
"mcp-session-id",
"last-event-id",
];
headersToProxy.forEach((headerName) => {
const value = request.headers.get(headerName);
if (value) {
headers.set(headerName, value);
}
});
headers.set("Authorization", `Bearer ${token}`);
const body =
request.method !== "GET" && request.method !== "HEAD"
? await request.arrayBuffer()
: undefined;
const response = await fetch(targetURL.toString(), {
method: request.method,
headers,
body,
});
// Create response headers, excluding hop-by-hop headers
const responseHeaders = new Headers();
const headersToExclude = [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
];
response.headers.forEach((value, key) => {
if (!headersToExclude.includes(key.toLowerCase())) {
responseHeaders.set(key, value);
}
});
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: responseHeaders,
});
} catch (error) {
console.error("Proxy request failed:", error);
return new Response(JSON.stringify({ error: "Proxy request failed" }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}
|