@casys/mcp-server 0.21.0 → 0.22.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.
package/mod.ts CHANGED
@@ -183,8 +183,16 @@ export {
183
183
  createAuthProviderFromConfig,
184
184
  loadAuthConfig,
185
185
  } from "./src/auth/mod.js";
186
+
186
187
  export type { AuthConfig, AuthProviderName } from "./src/auth/mod.js";
187
188
 
189
+ // Auth - Static Token Provider (opaque pre-shared bearer tokens)
190
+ export {
191
+ createStaticTokenAuthProvider,
192
+ StaticTokenAuthProvider,
193
+ } from "./src/auth/mod.js";
194
+ export type { StaticTokenAuthProviderOptions } from "./src/auth/mod.js";
195
+
188
196
  // Client Auth — OAuth client flow + CIMD
189
197
  export {
190
198
  buildClientIdMetadataDocument,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
5
5
  "type": "module",
6
6
  "main": "mod.ts",
package/src/auth/mod.ts CHANGED
@@ -80,3 +80,10 @@ export type {
80
80
  GoogleAuthConfig,
81
81
  OIDCAuthConfig,
82
82
  } from "./config.js";
83
+
84
+ // Static Token Provider (opaque pre-shared bearer tokens; no OIDC/JWT infra)
85
+ export {
86
+ createStaticTokenAuthProvider,
87
+ StaticTokenAuthProvider,
88
+ } from "./static-token-provider.js";
89
+ export type { StaticTokenAuthProviderOptions } from "./static-token-provider.js";
@@ -0,0 +1,197 @@
1
+ // deno-lint-ignore-file require-await
2
+ /**
3
+ * Static (opaque) bearer-token auth provider.
4
+ *
5
+ * Validates a fixed set of pre-shared bearer tokens with no OIDC/JWT
6
+ * infrastructure — no issuer, no JWKS endpoint, no key management. Suited to
7
+ * same-network deployments (Docker, VPN, LAN), server-to-server integrations,
8
+ * and CI pipelines where a full OAuth flow is disproportionate.
9
+ *
10
+ * All valid tokens map to the same {@link AuthInfo}: this is authentication
11
+ * ("is this an allowed caller?"), not per-user identity. For per-user identity,
12
+ * expiry, or scopes issued by an IdP, use {@link JwtAuthProvider} / the OIDC
13
+ * presets instead.
14
+ *
15
+ * Per RFC 9728 the emitted {@link ProtectedResourceMetadata} carries an empty
16
+ * `authorization_servers` array: there is no authorization server in a static
17
+ * token scheme — tokens are provisioned out of band — which is the correct
18
+ * signal for clients not to attempt AS discovery.
19
+ *
20
+ * @module lib/server/auth/static-token-provider
21
+ */
22
+
23
+ import { AuthProvider } from "./provider.js";
24
+ import {
25
+ type AuthInfo,
26
+ type HttpsUrl,
27
+ httpsUrl,
28
+ type ProtectedResourceMetadata,
29
+ } from "./types.js";
30
+
31
+ /**
32
+ * Options for {@link createStaticTokenAuthProvider} /
33
+ * {@link StaticTokenAuthProvider}.
34
+ */
35
+ export interface StaticTokenAuthProviderOptions {
36
+ /**
37
+ * RFC 9728 § 2 resource identifier — an absolute HTTP(S) URL identifying
38
+ * this server, validated via {@link httpsUrl} at construction. Required: the
39
+ * {@link AuthProvider} contract must emit Protected Resource Metadata, which
40
+ * needs a resource URL.
41
+ */
42
+ resource: string;
43
+ /**
44
+ * `subject` reported in {@link AuthInfo} for every valid token.
45
+ * Default `"static-token-user"`.
46
+ */
47
+ subject?: string;
48
+ /**
49
+ * `scopes` granted to every valid token. Default `[]` — a pure gate with no
50
+ * scopes, which is the common same-network case.
51
+ */
52
+ scopes?: string[];
53
+ /**
54
+ * `scopes_supported` advertised in the metadata document (what the resource
55
+ * accepts). Defaults to `scopes` when omitted.
56
+ */
57
+ scopesSupported?: string[];
58
+ /**
59
+ * Explicit Protected Resource Metadata URL. When omitted it is auto-derived
60
+ * from `resource` per RFC 9728 § 3.1, identically to {@link JwtAuthProvider}.
61
+ * Empty / whitespace-only values are treated as absent.
62
+ */
63
+ resourceMetadataUrl?: string;
64
+ }
65
+
66
+ /**
67
+ * {@link AuthProvider} that accepts a fixed set of opaque bearer tokens.
68
+ *
69
+ * Token lookup is O(1) via a pre-built `Set`; the shared {@link AuthInfo} (and
70
+ * its `scopes` array) is frozen at construction. Tokens are stored trimmed to
71
+ * match the bearer value the HTTP middleware extracts. Note that `Set.has()` is
72
+ * not constant-time — prefer long, high-entropy tokens (>= 32 random bytes) and
73
+ * rotate them regularly.
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * const provider = new StaticTokenAuthProvider(
78
+ * [Deno.env.get("MCP_AUTH_TOKEN")!],
79
+ * { resource: "https://my-mcp.example.com", scopes: ["tools:invoke"] },
80
+ * );
81
+ * ```
82
+ */
83
+ export class StaticTokenAuthProvider extends AuthProvider {
84
+ private readonly tokens: Set<string>;
85
+ private readonly authInfo: AuthInfo;
86
+ private readonly resource: string;
87
+ private readonly resourceMetadataUrl: HttpsUrl;
88
+ private readonly scopesSupported: string[] | undefined;
89
+
90
+ constructor(tokens: string[], options: StaticTokenAuthProviderOptions) {
91
+ super();
92
+
93
+ if (tokens.length === 0) {
94
+ throw new Error(
95
+ "[StaticTokenAuthProvider] `tokens` must contain at least one token",
96
+ );
97
+ }
98
+ if (tokens.some((t) => t.trim().length === 0)) {
99
+ throw new Error(
100
+ "[StaticTokenAuthProvider] `tokens` must not contain empty entries",
101
+ );
102
+ }
103
+ if (!options.resource?.trim()) {
104
+ throw new Error("[StaticTokenAuthProvider] `resource` is required");
105
+ }
106
+
107
+ // Validate `resource` as an absolute HTTP(S) URL unconditionally, so the
108
+ // documented guarantee holds even when `resourceMetadataUrl` is supplied.
109
+ const resourceUrl = httpsUrl(options.resource);
110
+
111
+ // Store tokens trimmed: the HTTP middleware trims the extracted bearer
112
+ // value (`extractBearerToken`), so a padded entry would otherwise be stored
113
+ // in a form that can never match an incoming request.
114
+ this.tokens = new Set(tokens.map((t) => t.trim()));
115
+
116
+ // Clone + freeze the scopes array: verifyToken returns this same AuthInfo
117
+ // reference for every valid token, so a shared mutable array would let one
118
+ // caller escalate scopes for all callers.
119
+ const scopes = Object.freeze([...(options.scopes ?? [])]) as string[];
120
+ this.authInfo = Object.freeze({
121
+ subject: options.subject ?? "static-token-user",
122
+ scopes,
123
+ }) as AuthInfo;
124
+
125
+ // Store the caller's raw resource string (RFC 9728 allows opaque URIs, and
126
+ // JwtAuthProvider does the same); `resourceUrl` above is used only for
127
+ // validation and metadata-URL derivation.
128
+ this.resource = options.resource;
129
+ this.scopesSupported = options.scopesSupported
130
+ ? (Object.freeze([...options.scopesSupported]) as string[])
131
+ : (scopes.length > 0 ? scopes : undefined);
132
+
133
+ // RFC 9728 § 3.1: when `resourceMetadataUrl` is omitted, insert the
134
+ // well-known suffix between the resource's origin and its path/query
135
+ // (identical derivation to JwtAuthProvider).
136
+ if (options.resourceMetadataUrl?.trim()) {
137
+ this.resourceMetadataUrl = httpsUrl(options.resourceMetadataUrl);
138
+ } else {
139
+ const parsed = new URL(resourceUrl);
140
+ const pathPart = parsed.pathname === "/" ? "" : parsed.pathname;
141
+ this.resourceMetadataUrl = httpsUrl(
142
+ `${parsed.origin}/.well-known/oauth-protected-resource${pathPart}${parsed.search}`,
143
+ );
144
+ }
145
+ }
146
+
147
+ async verifyToken(token: string): Promise<AuthInfo | null> {
148
+ // Trim to match how tokens are stored (and how the HTTP middleware extracts
149
+ // the bearer), so direct callers and the middleware path behave identically.
150
+ return this.tokens.has(token.trim()) ? this.authInfo : null;
151
+ }
152
+
153
+ getResourceMetadata(): ProtectedResourceMetadata {
154
+ // Fresh object per call (matching JwtAuthProvider) so a caller cannot
155
+ // mutate shared metadata — e.g. the `authorization_servers` array.
156
+ return {
157
+ resource: this.resource,
158
+ resource_metadata_url: this.resourceMetadataUrl,
159
+ // No authorization server: static tokens are provisioned out of band.
160
+ authorization_servers: [],
161
+ scopes_supported: this.scopesSupported,
162
+ bearer_methods_supported: ["header"],
163
+ };
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Create a static (opaque) bearer-token {@link AuthProvider}.
169
+ *
170
+ * @param tokens Non-empty list of valid bearer tokens (deduplicated, stored
171
+ * trimmed). Load them from env / a secrets manager — never hard-code tokens
172
+ * in source.
173
+ * @param options Provider configuration; `options.resource` is required.
174
+ *
175
+ * @example
176
+ * ```typescript
177
+ * import { createStaticTokenAuthProvider, McpApp } from "@casys/mcp-server";
178
+ *
179
+ * const app = new McpApp({
180
+ * name: "my-server",
181
+ * version: "1.0.0",
182
+ * auth: {
183
+ * provider: createStaticTokenAuthProvider(
184
+ * (Deno.env.get("MCP_AUTH_TOKENS") ?? "").split(",").filter(Boolean),
185
+ * { resource: "https://my-mcp.example.com" },
186
+ * ),
187
+ * },
188
+ * });
189
+ * await app.startHttp({ port: 7654, requireAuth: true });
190
+ * ```
191
+ */
192
+ export function createStaticTokenAuthProvider(
193
+ tokens: string[],
194
+ options: StaticTokenAuthProviderOptions,
195
+ ): StaticTokenAuthProvider {
196
+ return new StaticTokenAuthProvider(tokens, options);
197
+ }
@@ -4,6 +4,14 @@
4
4
  * Launches the official @modelcontextprotocol/inspector to debug
5
5
  * and test MCP servers interactively in a browser.
6
6
  *
7
+ * Runtime-agnostic: process spawning goes through `node:` builtins, which
8
+ * both Deno (via its Node compat layer) and Node.js support — one code path
9
+ * instead of a per-runtime adapter. The `node:` modules are imported
10
+ * dynamically inside the function bodies so nothing process-related enters
11
+ * the module graph at load time (mod.ts re-exports this module, and its
12
+ * import must stay side-effect free on constrained runtimes like
13
+ * Deno Deploy).
14
+ *
7
15
  * Usage from a server script:
8
16
  * ```typescript
9
17
  * import { launchInspector } from "@casys/mcp-server";
@@ -43,6 +51,9 @@ export async function launchInspector(
43
51
  serverArgs: string[],
44
52
  options?: InspectorOptions,
45
53
  ): Promise<void> {
54
+ const { spawn } = await import("node:child_process");
55
+ const { env, exit } = await import("node:process");
56
+
46
57
  const port = options?.port ?? 6274;
47
58
  const shouldOpen = options?.open ?? true;
48
59
 
@@ -62,23 +73,19 @@ export async function launchInspector(
62
73
  );
63
74
 
64
75
  // Use npx to run the inspector
65
- const command = new Deno.Command("npx", {
66
- args: [
76
+ const child = spawn(
77
+ "npx",
78
+ [
67
79
  "-y",
68
80
  "@modelcontextprotocol/inspector",
69
81
  serverCommand,
70
82
  ...filteredArgs,
71
83
  ],
72
- env: {
73
- ...Deno.env.toObject(),
74
- ...inspectorEnv,
84
+ {
85
+ env: { ...env, ...inspectorEnv },
86
+ stdio: "inherit",
75
87
  },
76
- stdin: "inherit",
77
- stdout: "inherit",
78
- stderr: "inherit",
79
- });
80
-
81
- const process = command.spawn();
88
+ );
82
89
 
83
90
  // Open browser after a short delay
84
91
  if (shouldOpen) {
@@ -90,10 +97,13 @@ export async function launchInspector(
90
97
  }
91
98
 
92
99
  // Wait for the inspector process to exit
93
- const status = await process.status;
94
- if (!status.success) {
95
- console.error(`[mcp-inspector] Inspector exited with code ${status.code}`);
96
- Deno.exit(status.code);
100
+ const code = await new Promise<number>((resolve, reject) => {
101
+ child.on("error", reject);
102
+ child.on("exit", (exitCode) => resolve(exitCode ?? 1));
103
+ });
104
+ if (code !== 0) {
105
+ console.error(`[mcp-inspector] Inspector exited with code ${code}`);
106
+ exit(code);
97
107
  }
98
108
  }
99
109
 
@@ -101,23 +111,21 @@ export async function launchInspector(
101
111
  * Open a URL in the default browser (cross-platform).
102
112
  */
103
113
  async function openBrowser(url: string): Promise<void> {
104
- const os = Deno.build.os;
105
- let cmd: string[];
114
+ const { spawn } = await import("node:child_process");
115
+ const { platform } = await import("node:process");
106
116
 
107
- if (os === "darwin") {
117
+ let cmd: string[];
118
+ if (platform === "darwin") {
108
119
  cmd = ["open", url];
109
- } else if (os === "windows") {
120
+ } else if (platform === "win32") {
110
121
  cmd = ["cmd", "/c", "start", url];
111
122
  } else {
112
123
  cmd = ["xdg-open", url];
113
124
  }
114
125
 
115
- const process = new Deno.Command(cmd[0], {
116
- args: cmd.slice(1),
117
- stdin: "null",
118
- stdout: "null",
119
- stderr: "null",
126
+ const child = spawn(cmd[0], cmd.slice(1), { stdio: "ignore" });
127
+ await new Promise<void>((resolve, reject) => {
128
+ child.on("error", reject);
129
+ child.on("exit", () => resolve());
120
130
  });
121
-
122
- await process.spawn().status;
123
131
  }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Runtime adapter — Deno implementation
3
+ *
4
+ * Implements the RuntimePort contract for Deno.
5
+ * Selected automatically by runtime.ts (the selector) when running under Deno.
6
+ *
7
+ * @see types.ts for the port contract
8
+ * @module lib/server/runtime.deno
9
+ */
10
+
11
+ import type {
12
+ FetchHandler,
13
+ RuntimePort,
14
+ ServeHandle,
15
+ ServeOptions,
16
+ } from "./types.js";
17
+
18
+ // Re-export types so consumers import from a single module
19
+ export type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
20
+
21
+ /**
22
+ * Get an environment variable.
23
+ */
24
+ export function env(key: string): string | undefined {
25
+ return Deno.env.get(key);
26
+ }
27
+
28
+ /**
29
+ * Read a UTF-8 text file.
30
+ * Returns null if the file does not exist.
31
+ */
32
+ export async function readTextFile(path: string): Promise<string | null> {
33
+ try {
34
+ return await Deno.readTextFile(path);
35
+ } catch (err) {
36
+ if (err instanceof Deno.errors.NotFound) {
37
+ return null;
38
+ }
39
+ throw err;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Write a UTF-8 text file.
45
+ */
46
+ export async function writeTextFile(
47
+ path: string,
48
+ content: string,
49
+ opts?: { mode?: number },
50
+ ): Promise<void> {
51
+ await Deno.writeTextFile(path, content, opts);
52
+ }
53
+
54
+ /**
55
+ * Create a directory.
56
+ */
57
+ export async function mkdir(
58
+ path: string,
59
+ opts?: { recursive?: boolean; mode?: number },
60
+ ): Promise<void> {
61
+ await Deno.mkdir(path, opts);
62
+ }
63
+
64
+ /**
65
+ * Remove a file or empty directory. No-op if absent.
66
+ */
67
+ export async function remove(path: string): Promise<void> {
68
+ try {
69
+ await Deno.remove(path);
70
+ } catch (err) {
71
+ if (err instanceof Deno.errors.NotFound) {
72
+ return;
73
+ }
74
+ throw err;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Read directory entry names. Returns [] if absent.
80
+ */
81
+ export async function readDir(path: string): Promise<string[]> {
82
+ try {
83
+ const names: string[] = [];
84
+ for await (const entry of Deno.readDir(path)) {
85
+ names.push(entry.name);
86
+ }
87
+ return names;
88
+ } catch (err) {
89
+ if (err instanceof Deno.errors.NotFound) {
90
+ return [];
91
+ }
92
+ throw err;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Start an HTTP server with a fetch-style handler.
98
+ */
99
+ export function serve(
100
+ options: ServeOptions,
101
+ handler: FetchHandler,
102
+ ): ServeHandle {
103
+ let server: Deno.HttpServer | null = null;
104
+ try {
105
+ server = Deno.serve(
106
+ {
107
+ port: options.port,
108
+ hostname: options.hostname,
109
+ onListen: options.onListen,
110
+ },
111
+ handler,
112
+ );
113
+ } catch (err) {
114
+ const error = toError(err);
115
+ if (options.onError) {
116
+ options.onError(error);
117
+ return {
118
+ shutdown: () => Promise.resolve(),
119
+ };
120
+ }
121
+ throw error;
122
+ }
123
+ return {
124
+ shutdown: () => server.shutdown(),
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Unref a timer so it doesn't block process exit.
130
+ */
131
+ export function unrefTimer(id: number): void {
132
+ Deno.unrefTimer(id);
133
+ }
134
+
135
+ /** Compile-time contract check — ensures this module satisfies RuntimePort */
136
+ void ({
137
+ env,
138
+ readTextFile,
139
+ writeTextFile,
140
+ mkdir,
141
+ remove,
142
+ readDir,
143
+ serve,
144
+ unrefTimer,
145
+ } satisfies RuntimePort);
146
+
147
+ function toError(err: unknown): Error {
148
+ return err instanceof Error ? err : new Error(String(err));
149
+ }
@@ -0,0 +1,324 @@
1
+ // deno-lint-ignore-file no-process-global
2
+ /**
3
+ * Runtime adapter — Node.js implementation
4
+ *
5
+ * Implements the RuntimePort contract for Node.js.
6
+ * Drop-in replacement for runtime.ts (Deno) — swapped by build script.
7
+ *
8
+ * @see runtime-types.ts for the port contract
9
+ * @module lib/server/runtime.node
10
+ */
11
+
12
+ import { Buffer } from "node:buffer";
13
+ import {
14
+ mkdir as nodeMkdir,
15
+ readdir,
16
+ readFile,
17
+ rm,
18
+ writeFile,
19
+ } from "node:fs/promises";
20
+ import { createServer } from "node:http";
21
+ import type {
22
+ FetchHandler,
23
+ RuntimePort,
24
+ ServeHandle,
25
+ ServeOptions,
26
+ } from "./types.js";
27
+
28
+ // Re-export types so consumers import from a single module
29
+ export type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
30
+
31
+ class PayloadTooLargeError extends Error {
32
+ constructor(maxBytes: number) {
33
+ super(`Payload too large. Max ${maxBytes} bytes.`);
34
+ this.name = "PayloadTooLargeError";
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Get an environment variable.
40
+ */
41
+ export function env(key: string): string | undefined {
42
+ return process.env[key];
43
+ }
44
+
45
+ /**
46
+ * Read a UTF-8 text file.
47
+ * Returns null if the file does not exist.
48
+ */
49
+ export async function readTextFile(path: string): Promise<string | null> {
50
+ try {
51
+ return await readFile(path, "utf-8");
52
+ } catch (err: unknown) {
53
+ if (
54
+ err && typeof err === "object" && "code" in err && err.code === "ENOENT"
55
+ ) {
56
+ return null;
57
+ }
58
+ throw err;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Write a UTF-8 text file.
64
+ */
65
+ export async function writeTextFile(
66
+ path: string,
67
+ content: string,
68
+ opts?: { mode?: number },
69
+ ): Promise<void> {
70
+ await writeFile(path, content, { mode: opts?.mode });
71
+ }
72
+
73
+ /**
74
+ * Create a directory.
75
+ */
76
+ export async function mkdir(
77
+ path: string,
78
+ opts?: { recursive?: boolean; mode?: number },
79
+ ): Promise<void> {
80
+ await nodeMkdir(path, { recursive: opts?.recursive, mode: opts?.mode });
81
+ }
82
+
83
+ /**
84
+ * Remove a file or empty directory. No-op if absent.
85
+ */
86
+ export async function remove(path: string): Promise<void> {
87
+ try {
88
+ await rm(path);
89
+ } catch (err: unknown) {
90
+ if (isNodeNotFound(err)) {
91
+ return;
92
+ }
93
+ throw err;
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Read directory entry names. Returns [] if absent.
99
+ */
100
+ export async function readDir(path: string): Promise<string[]> {
101
+ try {
102
+ return await readdir(path);
103
+ } catch (err: unknown) {
104
+ if (isNodeNotFound(err)) {
105
+ return [];
106
+ }
107
+ throw err;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Start an HTTP server with a fetch-style handler.
113
+ * Uses node:http with a Request/Response adapter (compatible with Hono).
114
+ */
115
+ export function serve(
116
+ options: ServeOptions,
117
+ handler: FetchHandler,
118
+ ): ServeHandle {
119
+ const hostname = options.hostname ?? "0.0.0.0";
120
+ const maxBodyBytes = options.maxBodyBytes ?? null;
121
+
122
+ const server = createServer(async (nodeReq, nodeRes) => {
123
+ try {
124
+ const contentLength = nodeReq.headers["content-length"];
125
+ if (maxBodyBytes !== null && contentLength) {
126
+ const length = Array.isArray(contentLength)
127
+ ? Number(contentLength[0])
128
+ : Number(contentLength);
129
+ if (!Number.isNaN(length) && length > maxBodyBytes) {
130
+ nodeRes.writeHead(413);
131
+ nodeRes.end(`Payload too large. Max ${maxBodyBytes} bytes.`);
132
+ return;
133
+ }
134
+ }
135
+
136
+ // Convert Node.js IncomingMessage → Web Request
137
+ // Prefer Host header (correct behind reverse proxy) over bound hostname
138
+ const host = nodeReq.headers.host ?? `${hostname}:${options.port}`;
139
+ const url = `http://${host}${nodeReq.url ?? "/"}`;
140
+ const headers = new Headers();
141
+ for (const [key, value] of Object.entries(nodeReq.headers)) {
142
+ if (value) {
143
+ if (Array.isArray(value)) {
144
+ for (const v of value) headers.append(key, v);
145
+ } else {
146
+ headers.set(key, value);
147
+ }
148
+ }
149
+ }
150
+
151
+ const body = nodeReq.method !== "GET" && nodeReq.method !== "HEAD"
152
+ ? await collectBody(nodeReq, maxBodyBytes)
153
+ : undefined;
154
+
155
+ const request = new Request(url, {
156
+ method: nodeReq.method ?? "GET",
157
+ headers,
158
+ body,
159
+ // @ts-ignore: duplex needed for streaming requests in Node 20+
160
+ duplex: body ? "half" : undefined,
161
+ });
162
+
163
+ // Call the fetch handler (Hono, etc.)
164
+ const response = await handler(request);
165
+
166
+ // Convert Web Response → Node.js ServerResponse
167
+ // Use raw header entries to preserve duplicate Set-Cookie headers
168
+ const resHeaders: Record<string, string | string[]> = {};
169
+ response.headers.forEach((value, key) => {
170
+ const existing = resHeaders[key];
171
+ if (existing !== undefined) {
172
+ resHeaders[key] = Array.isArray(existing)
173
+ ? [...existing, value]
174
+ : [existing, value];
175
+ } else {
176
+ resHeaders[key] = value;
177
+ }
178
+ });
179
+ nodeRes.writeHead(response.status, resHeaders);
180
+
181
+ if (response.body) {
182
+ const reader = response.body.getReader();
183
+ while (true) {
184
+ const { done, value } = await reader.read();
185
+ if (done) break;
186
+ nodeRes.write(value);
187
+ }
188
+ nodeRes.end();
189
+ } else {
190
+ nodeRes.end();
191
+ }
192
+ } catch (err) {
193
+ if (err instanceof PayloadTooLargeError) {
194
+ if (!nodeRes.headersSent) {
195
+ nodeRes.writeHead(413);
196
+ nodeRes.end(err.message);
197
+ }
198
+ return;
199
+ }
200
+ console.error("[runtime.node] Request handler error:", err);
201
+ if (!nodeRes.headersSent) {
202
+ nodeRes.writeHead(500);
203
+ nodeRes.end("Internal Server Error");
204
+ }
205
+ }
206
+ });
207
+
208
+ server.on("error", (err) => {
209
+ if (options.onError) {
210
+ options.onError(err);
211
+ return;
212
+ }
213
+ setTimeout(() => {
214
+ throw err;
215
+ }, 0);
216
+ });
217
+
218
+ server.listen(options.port, hostname, () => {
219
+ if (options.onListen) {
220
+ const address = server.address();
221
+ const port = typeof address === "object" && address !== null
222
+ ? address.port
223
+ : options.port;
224
+ options.onListen({ hostname, port });
225
+ }
226
+ });
227
+
228
+ return {
229
+ shutdown: () =>
230
+ new Promise<void>((resolve, reject) => {
231
+ server.close((err) => {
232
+ if (err && !isNodeServerNotRunning(err)) {
233
+ reject(err);
234
+ return;
235
+ }
236
+ resolve();
237
+ });
238
+ }),
239
+ };
240
+ }
241
+
242
+ /**
243
+ * Unref a timer so it doesn't block process exit.
244
+ */
245
+ export function unrefTimer(id: number): void {
246
+ // In Node.js, setTimeout returns a Timeout object (not a numeric ID).
247
+ // The caller passes it as `number` for Deno compat — we cast back.
248
+ try {
249
+ const timer = id as unknown as { unref?: () => void };
250
+ if (
251
+ typeof timer === "object" && timer && typeof timer.unref === "function"
252
+ ) {
253
+ timer.unref();
254
+ }
255
+ } catch (err) {
256
+ console.warn("[runtime.node] Failed to unref timer:", err);
257
+ }
258
+ }
259
+
260
+ /** Compile-time contract check — ensures this module satisfies RuntimePort */
261
+ void ({
262
+ env,
263
+ readTextFile,
264
+ writeTextFile,
265
+ mkdir,
266
+ remove,
267
+ readDir,
268
+ serve,
269
+ unrefTimer,
270
+ } satisfies RuntimePort);
271
+
272
+ // ─── Internal helpers ────────────────────────────────────
273
+
274
+ /** Collect request body from Node.js IncomingMessage */
275
+ function collectBody(
276
+ req: import("node:http").IncomingMessage,
277
+ maxBytes: number | null,
278
+ ): Promise<ArrayBuffer> {
279
+ return new Promise((resolve, reject) => {
280
+ const chunks: Buffer[] = [];
281
+ let total = 0;
282
+ let rejected = false;
283
+ req.on("data", (chunk: Buffer) => {
284
+ if (rejected) return;
285
+ total += chunk.length;
286
+ if (maxBytes !== null && total > maxBytes) {
287
+ rejected = true;
288
+ req.destroy();
289
+ reject(new PayloadTooLargeError(maxBytes));
290
+ return;
291
+ }
292
+ chunks.push(chunk);
293
+ });
294
+ req.on("end", () => {
295
+ if (!rejected) {
296
+ const body = Buffer.concat(chunks);
297
+ resolve(
298
+ body.buffer.slice(
299
+ body.byteOffset,
300
+ body.byteOffset + body.byteLength,
301
+ ),
302
+ );
303
+ }
304
+ });
305
+ req.on("error", (err) => {
306
+ if (!rejected) {
307
+ reject(err);
308
+ }
309
+ });
310
+ });
311
+ }
312
+
313
+ function isNodeNotFound(err: unknown): boolean {
314
+ return Boolean(
315
+ err && typeof err === "object" && "code" in err && err.code === "ENOENT",
316
+ );
317
+ }
318
+
319
+ function isNodeServerNotRunning(err: unknown): boolean {
320
+ return Boolean(
321
+ err && typeof err === "object" && "code" in err &&
322
+ err.code === "ERR_SERVER_NOT_RUNNING",
323
+ );
324
+ }
@@ -1,324 +1,50 @@
1
- // deno-lint-ignore-file no-process-global
2
1
  /**
3
- * Runtime adapter — Node.js implementation
2
+ * Runtime adapter — selector
4
3
  *
5
- * Implements the RuntimePort contract for Node.js.
6
- * Drop-in replacement for runtime.ts (Deno) — swapped by build script.
4
+ * Auto-detects the host runtime and forwards to the Deno or Node adapter.
5
+ * This is the module every consumer imports. It replaces the previous
6
+ * build-time file swap (runtime.ts <- runtime.node.ts), which only ever
7
+ * applied to mcp-server's own npm build and never to JSR consumers that
8
+ * bundle the Deno source for Node (e.g. @casys/mcp-erpnext via esbuild),
9
+ * whose bundle therefore embedded `Deno.*` calls and crashed under Node
10
+ * with "ReferenceError: Deno is not defined".
7
11
  *
8
- * @see runtime-types.ts for the port contract
9
- * @module lib/server/runtime.node
12
+ * A *dynamic* import is used on purpose so the inactive adapter is never
13
+ * evaluated: under Deno, runtime.node.ts — and its top-level `node:http` /
14
+ * `node:fs/promises` / `node:buffer` imports — never executes, which keeps
15
+ * capability-restricted targets like Deno Deploy (the canonical cloud
16
+ * target, where node:http's raw-TCP `createServer` is unsupported) safe at
17
+ * load time. Platforms and bundlers that statically analyze
18
+ * constant-specifier dynamic imports may still fetch or include the
19
+ * inactive module, but they never run it. Under Node, the Deno adapter is
20
+ * likewise never evaluated.
21
+ *
22
+ * @see types.ts for the RuntimePort contract
23
+ * @see runtime.deno.ts / runtime.node.ts for the implementations
24
+ * @module lib/server/runtime
10
25
  */
11
26
 
12
- import { Buffer } from "node:buffer";
13
- import {
14
- mkdir as nodeMkdir,
15
- readdir,
16
- readFile,
17
- rm,
18
- writeFile,
19
- } from "node:fs/promises";
20
- import { createServer } from "node:http";
21
- import type {
22
- FetchHandler,
23
- RuntimePort,
24
- ServeHandle,
25
- ServeOptions,
26
- } from "./types.js";
27
+ import type { RuntimePort } from "./types.js";
27
28
 
28
29
  // Re-export types so consumers import from a single module
29
30
  export type { FetchHandler, ServeHandle, ServeOptions } from "./types.js";
30
31
 
31
- class PayloadTooLargeError extends Error {
32
- constructor(maxBytes: number) {
33
- super(`Payload too large. Max ${maxBytes} bytes.`);
34
- this.name = "PayloadTooLargeError";
35
- }
36
- }
37
-
38
- /**
39
- * Get an environment variable.
40
- */
41
- export function env(key: string): string | undefined {
42
- return process.env[key];
43
- }
44
-
45
- /**
46
- * Read a UTF-8 text file.
47
- * Returns null if the file does not exist.
48
- */
49
- export async function readTextFile(path: string): Promise<string | null> {
50
- try {
51
- return await readFile(path, "utf-8");
52
- } catch (err: unknown) {
53
- if (
54
- err && typeof err === "object" && "code" in err && err.code === "ENOENT"
55
- ) {
56
- return null;
57
- }
58
- throw err;
59
- }
60
- }
61
-
62
- /**
63
- * Write a UTF-8 text file.
64
- */
65
- export async function writeTextFile(
66
- path: string,
67
- content: string,
68
- opts?: { mode?: number },
69
- ): Promise<void> {
70
- await writeFile(path, content, { mode: opts?.mode });
71
- }
72
-
73
- /**
74
- * Create a directory.
75
- */
76
- export async function mkdir(
77
- path: string,
78
- opts?: { recursive?: boolean; mode?: number },
79
- ): Promise<void> {
80
- await nodeMkdir(path, { recursive: opts?.recursive, mode: opts?.mode });
81
- }
82
-
83
- /**
84
- * Remove a file or empty directory. No-op if absent.
85
- */
86
- export async function remove(path: string): Promise<void> {
87
- try {
88
- await rm(path);
89
- } catch (err: unknown) {
90
- if (isNodeNotFound(err)) {
91
- return;
92
- }
93
- throw err;
94
- }
95
- }
96
-
97
- /**
98
- * Read directory entry names. Returns [] if absent.
99
- */
100
- export async function readDir(path: string): Promise<string[]> {
101
- try {
102
- return await readdir(path);
103
- } catch (err: unknown) {
104
- if (isNodeNotFound(err)) {
105
- return [];
106
- }
107
- throw err;
108
- }
109
- }
110
-
111
- /**
112
- * Start an HTTP server with a fetch-style handler.
113
- * Uses node:http with a Request/Response adapter (compatible with Hono).
114
- */
115
- export function serve(
116
- options: ServeOptions,
117
- handler: FetchHandler,
118
- ): ServeHandle {
119
- const hostname = options.hostname ?? "0.0.0.0";
120
- const maxBodyBytes = options.maxBodyBytes ?? null;
121
-
122
- const server = createServer(async (nodeReq, nodeRes) => {
123
- try {
124
- const contentLength = nodeReq.headers["content-length"];
125
- if (maxBodyBytes !== null && contentLength) {
126
- const length = Array.isArray(contentLength)
127
- ? Number(contentLength[0])
128
- : Number(contentLength);
129
- if (!Number.isNaN(length) && length > maxBodyBytes) {
130
- nodeRes.writeHead(413);
131
- nodeRes.end(`Payload too large. Max ${maxBodyBytes} bytes.`);
132
- return;
133
- }
134
- }
135
-
136
- // Convert Node.js IncomingMessage → Web Request
137
- // Prefer Host header (correct behind reverse proxy) over bound hostname
138
- const host = nodeReq.headers.host ?? `${hostname}:${options.port}`;
139
- const url = `http://${host}${nodeReq.url ?? "/"}`;
140
- const headers = new Headers();
141
- for (const [key, value] of Object.entries(nodeReq.headers)) {
142
- if (value) {
143
- if (Array.isArray(value)) {
144
- for (const v of value) headers.append(key, v);
145
- } else {
146
- headers.set(key, value);
147
- }
148
- }
149
- }
150
-
151
- const body = nodeReq.method !== "GET" && nodeReq.method !== "HEAD"
152
- ? await collectBody(nodeReq, maxBodyBytes)
153
- : undefined;
154
-
155
- const request = new Request(url, {
156
- method: nodeReq.method ?? "GET",
157
- headers,
158
- body,
159
- // @ts-ignore: duplex needed for streaming requests in Node 20+
160
- duplex: body ? "half" : undefined,
161
- });
162
-
163
- // Call the fetch handler (Hono, etc.)
164
- const response = await handler(request);
165
-
166
- // Convert Web Response → Node.js ServerResponse
167
- // Use raw header entries to preserve duplicate Set-Cookie headers
168
- const resHeaders: Record<string, string | string[]> = {};
169
- response.headers.forEach((value, key) => {
170
- const existing = resHeaders[key];
171
- if (existing !== undefined) {
172
- resHeaders[key] = Array.isArray(existing)
173
- ? [...existing, value]
174
- : [existing, value];
175
- } else {
176
- resHeaders[key] = value;
177
- }
178
- });
179
- nodeRes.writeHead(response.status, resHeaders);
180
-
181
- if (response.body) {
182
- const reader = response.body.getReader();
183
- while (true) {
184
- const { done, value } = await reader.read();
185
- if (done) break;
186
- nodeRes.write(value);
187
- }
188
- nodeRes.end();
189
- } else {
190
- nodeRes.end();
191
- }
192
- } catch (err) {
193
- if (err instanceof PayloadTooLargeError) {
194
- if (!nodeRes.headersSent) {
195
- nodeRes.writeHead(413);
196
- nodeRes.end(err.message);
197
- }
198
- return;
199
- }
200
- console.error("[runtime.node] Request handler error:", err);
201
- if (!nodeRes.headersSent) {
202
- nodeRes.writeHead(500);
203
- nodeRes.end("Internal Server Error");
204
- }
205
- }
206
- });
207
-
208
- server.on("error", (err) => {
209
- if (options.onError) {
210
- options.onError(err);
211
- return;
212
- }
213
- setTimeout(() => {
214
- throw err;
215
- }, 0);
216
- });
217
-
218
- server.listen(options.port, hostname, () => {
219
- if (options.onListen) {
220
- const address = server.address();
221
- const port = typeof address === "object" && address !== null
222
- ? address.port
223
- : options.port;
224
- options.onListen({ hostname, port });
225
- }
226
- });
227
-
228
- return {
229
- shutdown: () =>
230
- new Promise<void>((resolve, reject) => {
231
- server.close((err) => {
232
- if (err && !isNodeServerNotRunning(err)) {
233
- reject(err);
234
- return;
235
- }
236
- resolve();
237
- });
238
- }),
239
- };
240
- }
241
-
242
- /**
243
- * Unref a timer so it doesn't block process exit.
244
- */
245
- export function unrefTimer(id: number): void {
246
- // In Node.js, setTimeout returns a Timeout object (not a numeric ID).
247
- // The caller passes it as `number` for Deno compat — we cast back.
248
- try {
249
- const timer = id as unknown as { unref?: () => void };
250
- if (
251
- typeof timer === "object" && timer && typeof timer.unref === "function"
252
- ) {
253
- timer.unref();
254
- }
255
- } catch (err) {
256
- console.warn("[runtime.node] Failed to unref timer:", err);
257
- }
258
- }
259
-
260
- /** Compile-time contract check — ensures this module satisfies RuntimePort */
261
- void ({
262
- env,
263
- readTextFile,
264
- writeTextFile,
265
- mkdir,
266
- remove,
267
- readDir,
268
- serve,
269
- unrefTimer,
270
- } satisfies RuntimePort);
271
-
272
- // ─── Internal helpers ────────────────────────────────────
273
-
274
- /** Collect request body from Node.js IncomingMessage */
275
- function collectBody(
276
- req: import("node:http").IncomingMessage,
277
- maxBytes: number | null,
278
- ): Promise<ArrayBuffer> {
279
- return new Promise((resolve, reject) => {
280
- const chunks: Buffer[] = [];
281
- let total = 0;
282
- let rejected = false;
283
- req.on("data", (chunk: Buffer) => {
284
- if (rejected) return;
285
- total += chunk.length;
286
- if (maxBytes !== null && total > maxBytes) {
287
- rejected = true;
288
- req.destroy();
289
- reject(new PayloadTooLargeError(maxBytes));
290
- return;
291
- }
292
- chunks.push(chunk);
293
- });
294
- req.on("end", () => {
295
- if (!rejected) {
296
- const body = Buffer.concat(chunks);
297
- resolve(
298
- body.buffer.slice(
299
- body.byteOffset,
300
- body.byteOffset + body.byteLength,
301
- ),
302
- );
303
- }
304
- });
305
- req.on("error", (err) => {
306
- if (!rejected) {
307
- reject(err);
308
- }
309
- });
310
- });
311
- }
312
-
313
- function isNodeNotFound(err: unknown): boolean {
314
- return Boolean(
315
- err && typeof err === "object" && "code" in err && err.code === "ENOENT",
316
- );
317
- }
318
-
319
- function isNodeServerNotRunning(err: unknown): boolean {
320
- return Boolean(
321
- err && typeof err === "object" && "code" in err &&
322
- err.code === "ERR_SERVER_NOT_RUNNING",
323
- );
324
- }
32
+ // Structural detection: a bare `globalThis.Deno = {}` shim (seen in some Node
33
+ // test setups and bundlers) must NOT be mistaken for a real Deno runtime, so
34
+ // probe a concrete field (`Deno.version.deno`) rather than mere existence.
35
+ const isDeno = typeof (globalThis as {
36
+ Deno?: { version?: { deno?: string } };
37
+ }).Deno?.version?.deno === "string";
38
+
39
+ const impl: RuntimePort = isDeno
40
+ ? await import("./runtime.deno.js")
41
+ : await import("./runtime.node.js");
42
+
43
+ export const env = impl.env;
44
+ export const readTextFile = impl.readTextFile;
45
+ export const writeTextFile = impl.writeTextFile;
46
+ export const mkdir = impl.mkdir;
47
+ export const remove = impl.remove;
48
+ export const readDir = impl.readDir;
49
+ export const serve = impl.serve;
50
+ export const unrefTimer = impl.unrefTimer;