@constructorfleet/sketchforge3d 1.31.0 → 1.32.0

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.
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Serves MCP Streamable HTTP statelessly: one JSON body per POST, no SSE, no session.
3
+ * Authorize requests before calling the handler.
4
+ */
5
+
6
+ import { SUPPORTED_PROTOCOL_VERSIONS, rpcError } from "./protocol.mjs";
7
+
8
+ export const DEFAULT_MAX_BODY_BYTES = 16 * 1024 * 1024;
9
+
10
+ const NO_STORE = { "Cache-Control": "no-store" };
11
+
12
+ function json(body, status = 200) {
13
+ return new Response(JSON.stringify(body), { status, headers: { ...NO_STORE, "Content-Type": "application/json" } });
14
+ }
15
+
16
+ function refusal(status, code, message) {
17
+ return json(rpcError(null, code, message), status);
18
+ }
19
+
20
+ /** Detects cross-site browser requests by comparing Origin with Host. */
21
+ function foreignOrigin(request) {
22
+ const origin = request.headers.get("origin");
23
+ if (!origin) return false;
24
+ const hosts = [request.headers.get("x-forwarded-host"), request.headers.get("host")]
25
+ .flatMap((value) => (value ? value.split(",") : []))
26
+ .map((value) => value.trim().toLowerCase())
27
+ .filter(Boolean);
28
+ // Runtimes that drop Host leave only the URL to compare.
29
+ if (!hosts.length) hosts.push(new URL(request.url).host.toLowerCase());
30
+ try {
31
+ return !hosts.includes(new URL(origin).host.toLowerCase());
32
+ } catch {
33
+ return true;
34
+ }
35
+ }
36
+
37
+ function accepts(request, mediaType) {
38
+ const accept = request.headers.get("accept");
39
+ if (!accept) return true;
40
+ const [type] = mediaType.split("/");
41
+ return accept.split(",").some((entry) => {
42
+ const offered = entry.split(";")[0].trim().toLowerCase();
43
+ return offered === mediaType || offered === "*/*" || offered === `${type}/*`;
44
+ });
45
+ }
46
+
47
+ /** Reads at most `maxBytes`, or resolves null once the body exceeds it. */
48
+ async function boundedBody(request, maxBytes) {
49
+ if (Number(request.headers.get("content-length")) > maxBytes) return null;
50
+ if (!request.body) return new Uint8Array();
51
+ const reader = request.body.getReader();
52
+ const chunks = [];
53
+ let total = 0;
54
+ for (;;) {
55
+ const { done, value } = await reader.read();
56
+ if (done) break;
57
+ total += value.byteLength;
58
+ if (total > maxBytes) {
59
+ await reader.cancel().catch(() => undefined);
60
+ return null;
61
+ }
62
+ chunks.push(value);
63
+ }
64
+ const bytes = new Uint8Array(total);
65
+ let offset = 0;
66
+ for (const chunk of chunks) {
67
+ bytes.set(chunk, offset);
68
+ offset += chunk.byteLength;
69
+ }
70
+ return bytes;
71
+ }
72
+
73
+ function isMessage(value) {
74
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.jsonrpc !== "2.0") return false;
75
+ return typeof value.method === "string" || "result" in value || "error" in value;
76
+ }
77
+
78
+ /** Builds a `(Request) => Promise<Response>` handler for POSTed JSON-RPC messages. */
79
+ export function createStreamableHttpHandler({ dispatch, maxBodyBytes = DEFAULT_MAX_BODY_BYTES }) {
80
+ return async function handle(request) {
81
+ if (request.method !== "POST") {
82
+ return new Response(null, { status: 405, headers: { ...NO_STORE, Allow: "POST" } });
83
+ }
84
+ if (foreignOrigin(request)) return refusal(403, -32600, "Origin is not this server.");
85
+ const version = request.headers.get("mcp-protocol-version");
86
+ if (version && !SUPPORTED_PROTOCOL_VERSIONS.includes(version)) {
87
+ return refusal(400, -32600, `Unsupported MCP-Protocol-Version: ${version}. Supported: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")}.`);
88
+ }
89
+ if (!/^application\/json\b/i.test(request.headers.get("content-type") ?? "")) {
90
+ return refusal(415, -32600, "Content-Type must be application/json.");
91
+ }
92
+ if (!accepts(request, "application/json")) return refusal(406, -32600, "Accept must include application/json.");
93
+
94
+ const bytes = await boundedBody(request, maxBodyBytes);
95
+ if (!bytes) return refusal(413, -32600, `Request body exceeds ${maxBodyBytes} bytes.`);
96
+ let payload;
97
+ try {
98
+ payload = JSON.parse(new TextDecoder().decode(bytes));
99
+ } catch {
100
+ return refusal(400, -32700, "Parse error");
101
+ }
102
+
103
+ const batch = Array.isArray(payload);
104
+ const messages = batch ? payload : [payload];
105
+ if (!messages.length || !messages.every(isMessage)) return refusal(400, -32600, "Invalid Request");
106
+
107
+ // In order: batched writes to one project would contend for its lock.
108
+ const responses = [];
109
+ for (const message of messages) {
110
+ const response = typeof message.method === "string" ? await dispatch(message) : undefined;
111
+ if (response) responses.push(response);
112
+ }
113
+ if (!responses.length) return new Response(null, { status: 202, headers: NO_STORE });
114
+ return json(batch ? responses : responses[0]);
115
+ };
116
+ }