-
Notifications
You must be signed in to change notification settings - Fork 881
Expand file tree
/
Copy pathindex.ts
More file actions
70 lines (64 loc) · 2.12 KB
/
Copy pathindex.ts
File metadata and controls
70 lines (64 loc) · 2.12 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
import { createMcpHandler } from "agents/mcp";
import { parseConfig, createClient, type Env } from "./config.js";
import { createServer } from "./server.js";
const CORS_ORIGIN = "*";
const CORS_METHODS = "GET, POST, DELETE, OPTIONS";
const CORS_ALLOWED_HEADERS =
"Content-Type, Authorization, X-Honcho-User-Name, X-Honcho-Workspace-ID, X-Honcho-Assistant-Name";
const CORS_HEADERS = {
"Access-Control-Allow-Origin": CORS_ORIGIN,
"Access-Control-Allow-Methods": CORS_METHODS,
"Access-Control-Allow-Headers": CORS_ALLOWED_HEADERS,
};
function stripOAuthChallenge(response: Response): Response {
if (!response.headers.has("WWW-Authenticate")) return response;
const headers = new Headers(response.headers);
headers.delete("WWW-Authenticate");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
export default {
async fetch(
request: Request,
env: Env,
executionCtx: ExecutionContext,
): Promise<Response> {
if (request.method === "OPTIONS") {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
let config;
try {
config = parseConfig(request, env);
} catch (e) {
const message =
e instanceof Error ? e.message : "Invalid request";
return new Response(JSON.stringify({ error: message }), {
status: 401,
headers: { "Content-Type": "application/json", ...CORS_HEADERS },
});
}
try {
const honcho = createClient(config);
const server = createServer({ honcho, config });
const handler = createMcpHandler(server, {
route: "/",
corsOptions: {
origin: CORS_ORIGIN,
methods: CORS_METHODS,
headers: CORS_ALLOWED_HEADERS,
},
});
return stripOAuthChallenge(await handler(request, env, executionCtx));
} catch (e) {
const message =
e instanceof Error ? e.message : "Internal server error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: { "Content-Type": "application/json", ...CORS_HEADERS },
});
}
},
};