Skip to content

Commit cf3be2d

Browse files
authored
Fix/cors (#71)
* fix: cors headers * fix: CORS
1 parent d8880ea commit cf3be2d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/index.ts

+34
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,35 @@ const requestHandler = createRequestHandler(
2020
import.meta.env.MODE,
2121
);
2222

23+
// Helper function to add CORS headers to a response
24+
const addCorsHeaders = (response: Response): Response => {
25+
const headers = new Headers(response.headers);
26+
headers.set("Access-Control-Allow-Origin", "http://localhost:5173");
27+
headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
28+
headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization");
29+
headers.set("Access-Control-Allow-Credentials", "true");
30+
31+
return new Response(response.body, {
32+
status: response.status,
33+
statusText: response.statusText,
34+
headers,
35+
});
36+
};
37+
38+
// Create CORS preflight response
39+
const handleCorsPreflightRequest = (): Response => {
40+
return new Response(null, {
41+
status: 204, // No content
42+
headers: {
43+
"Access-Control-Allow-Origin": "*",
44+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
45+
"Access-Control-Allow-Headers": "Content-Type",
46+
"Access-Control-Allow-Credentials": "true",
47+
"Access-Control-Max-Age": "86400", // 24 hours
48+
},
49+
});
50+
};
51+
2352
export class MyMCP extends McpAgent {
2453
server = new McpServer({
2554
name: "GitMCP",
@@ -67,6 +96,11 @@ const mcpHandler = MyMCP.mount("/*");
6796
// Export a request handler that checks the transport header
6897
export default {
6998
async fetch(request: Request, env: any, ctx: any) {
99+
// Handle CORS preflight requests
100+
if (request.method === "OPTIONS") {
101+
return handleCorsPreflightRequest();
102+
}
103+
70104
const url = new URL(request.url);
71105
const isSse =
72106
request.headers.get("accept")?.includes("text/event-stream") &&

0 commit comments

Comments
 (0)