@casys/mcp-server 0.20.0 → 0.21.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@casys/mcp-server",
3
- "version": "0.20.0",
3
+ "version": "0.21.1",
4
4
  "description": "Production-ready MCP server framework with concurrency control, auth, and observability",
5
5
  "type": "module",
6
6
  "main": "mod.ts",
@@ -12,6 +12,12 @@ import type { AuthInfo } from "./types.js";
12
12
  import type { Middleware } from "../middleware/types.js";
13
13
  import { isOtelEnabled, recordAuthEvent } from "../observability/otel.js";
14
14
 
15
+ const JSONRPC_FORBIDDEN = -32002;
16
+
17
+ function escapeAuthenticateParam(s: string): string {
18
+ return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
19
+ }
20
+
15
21
  /**
16
22
  * Authentication error with structured information
17
23
  * for generating proper HTTP error responses.
@@ -61,11 +67,14 @@ export function createUnauthorizedResponse(
61
67
  error?: string,
62
68
  errorDescription?: string,
63
69
  ): Response {
64
- const escape = (s: string) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
65
- const parts = [`Bearer resource_metadata="${escape(resourceMetadataUrl)}"`];
66
- if (error) parts.push(`error="${escape(error)}"`);
70
+ const parts = [
71
+ `Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
72
+ ];
73
+ if (error) parts.push(`error="${escapeAuthenticateParam(error)}"`);
67
74
  if (errorDescription) {
68
- parts.push(`error_description="${escape(errorDescription)}"`);
75
+ parts.push(
76
+ `error_description="${escapeAuthenticateParam(errorDescription)}"`,
77
+ );
69
78
  }
70
79
 
71
80
  return new Response(
@@ -88,20 +97,36 @@ export function createUnauthorizedResponse(
88
97
  * Create a 403 Forbidden response for insufficient scopes.
89
98
  *
90
99
  * @param requiredScopes - Scopes that were required but missing
100
+ * @param resourceMetadataUrl - URL to the Protected Resource Metadata endpoint
91
101
  */
92
- export function createForbiddenResponse(requiredScopes: string[]): Response {
102
+ export function createForbiddenResponse(
103
+ requiredScopes: string[],
104
+ resourceMetadataUrl: string,
105
+ ): Response {
106
+ const requiredScopesDescription = requiredScopes.join(", ");
107
+ const parts = [
108
+ `Bearer resource_metadata="${escapeAuthenticateParam(resourceMetadataUrl)}"`,
109
+ `error="insufficient_scope"`,
110
+ `error_description="${
111
+ escapeAuthenticateParam(requiredScopesDescription)
112
+ }"`,
113
+ ];
114
+
93
115
  return new Response(
94
116
  JSON.stringify({
95
117
  jsonrpc: "2.0",
96
118
  id: null,
97
119
  error: {
98
- code: -32001,
120
+ code: JSONRPC_FORBIDDEN,
99
121
  message: `Forbidden: requires scopes ${requiredScopes.join(", ")}`,
100
122
  },
101
123
  }),
102
124
  {
103
125
  status: 403,
104
- headers: { "Content-Type": "application/json" },
126
+ headers: {
127
+ "Content-Type": "application/json",
128
+ "WWW-Authenticate": parts.join(", "),
129
+ },
105
130
  },
106
131
  );
107
132
  }
@@ -150,18 +175,19 @@ export function createAuthMiddleware(provider: AuthProvider): Middleware {
150
175
  return next();
151
176
  }
152
177
 
178
+ // 0.15.0+: provider's getResourceMetadata() always returns a valid
179
+ // absolute URL in resource_metadata_url (type system guarantees it).
180
+ // No derivation needed at the middleware level anymore.
181
+ const metadataUrl = provider.getResourceMetadata().resource_metadata_url;
182
+
153
183
  // Already authenticated by the HTTP-level gate (verifyHttpAuth).
154
184
  // Skip the redundant verifyToken call to avoid JWKS race conditions
155
185
  // when concurrent requests arrive on a cold cache.
156
186
  if (ctx.authInfo) {
187
+ ctx.resourceMetadataUrl = metadataUrl;
157
188
  return next();
158
189
  }
159
190
 
160
- // 0.15.0+: provider's getResourceMetadata() always returns a valid
161
- // absolute URL in resource_metadata_url (type system guarantees it).
162
- // No derivation needed at the middleware level anymore.
163
- const metadataUrl = provider.getResourceMetadata().resource_metadata_url;
164
-
165
191
  const token = extractBearerToken(ctx.request);
166
192
  if (!token) {
167
193
  if (isOtelEnabled()) {
@@ -48,8 +48,8 @@ export function createScopeMiddleware(
48
48
  const missingScopes = requiredScopes.filter((s) =>
49
49
  !authInfo.scopes.includes(s)
50
50
  );
51
- // resourceMetadataUrl is not critical for 403 responses (only used in 401),
52
- // but we populate it from context if available for consistency
51
+ // Used by 403 responses to advertise protected resource metadata in
52
+ // WWW-Authenticate; auth middleware populates it for HTTP requests.
53
53
  const metadataUrl = (ctx.resourceMetadataUrl as string | undefined) ?? "";
54
54
  throw new AuthError("insufficient_scope", metadataUrl, missingScopes);
55
55
  }
@@ -29,7 +29,7 @@ export interface ClientIdMetadataDocument {
29
29
  client_id: string;
30
30
  client_name: string;
31
31
  redirect_uris: string[];
32
- grant_types: ["authorization_code"];
32
+ grant_types: ["authorization_code", "refresh_token"];
33
33
  response_types: ["code"];
34
34
  token_endpoint_auth_method: "none";
35
35
  /** RFC 7591 application type. Always "native" for loopback CLI/desktop clients. */
@@ -120,7 +120,7 @@ export function buildClientIdMetadataDocument(
120
120
  client_id: clientRegistration.clientIdMetadataUrl,
121
121
  client_name: config.clientName!,
122
122
  redirect_uris: [clientRegistration.redirectUri],
123
- grant_types: ["authorization_code"],
123
+ grant_types: ["authorization_code", "refresh_token"],
124
124
  response_types: ["code"],
125
125
  token_endpoint_auth_method: "none",
126
126
  application_type: "native",
@@ -68,7 +68,7 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
68
68
  return {
69
69
  client_name: this.config.clientName ?? "PML Client",
70
70
  redirect_uris: [String(this.redirectUrl)],
71
- grant_types: ["authorization_code"],
71
+ grant_types: ["authorization_code", "refresh_token"],
72
72
  response_types: ["code"],
73
73
  token_endpoint_auth_method: "none", // public client, PKCE only
74
74
  application_type: "native", // loopback CLI/desktop — prevents AS rejection of http://127.0.0.1 redirects
@@ -101,9 +101,18 @@ export class OAuthClientProviderImpl implements OAuthClientProvider {
101
101
  }
102
102
 
103
103
  async saveTokens(tokens: OAuthTokens): Promise<void> {
104
+ // Sequential guard only: keep an existing refresh_token when a later save omits it.
105
+ // This get/set is not atomic; concurrent saves for one serverUrl are unsupported
106
+ // because refresh is serialized by the caller.
107
+ const stored = await this.config.tokenStore.get(this.serverUrl);
108
+ const tokensToStore = tokens.refresh_token === undefined &&
109
+ stored?.tokens.refresh_token !== undefined
110
+ ? { ...tokens, refresh_token: stored.tokens.refresh_token }
111
+ : tokens;
112
+
104
113
  await this.config.tokenStore.set(this.serverUrl, {
105
114
  serverUrl: this.serverUrl,
106
- tokens,
115
+ tokens: tokensToStore,
107
116
  obtainedAt: Date.now(),
108
117
  });
109
118
  }
@@ -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
  }
package/src/mcp-app.ts CHANGED
@@ -15,6 +15,9 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
15
15
  import {
16
16
  type CallToolRequest,
17
17
  CallToolRequestSchema,
18
+ type ClientCapabilities,
19
+ ErrorCode,
20
+ type Implementation,
18
21
  ListResourcesRequestSchema,
19
22
  ListToolsRequestSchema,
20
23
  type ReadResourceRequest,
@@ -171,6 +174,13 @@ async function readBodyWithLimit(
171
174
  /** Namespaced protocolVersion key in params._meta (spec 2026-07-28) */
172
175
  const STATELESS_PROTO_KEY = "io.modelcontextprotocol/protocolVersion";
173
176
 
177
+ /** Namespaced clientInfo key in params._meta (SEP-2575 stateless transport) */
178
+ const STATELESS_CLIENT_INFO_KEY = "io.modelcontextprotocol/clientInfo";
179
+
180
+ /** Namespaced clientCapabilities key in params._meta (SEP-2575 stateless transport) */
181
+ const STATELESS_CLIENT_CAPABILITIES_KEY =
182
+ "io.modelcontextprotocol/clientCapabilities";
183
+
174
184
  /** Protocol versions accepted by this server in stateless mode */
175
185
  const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
176
186
  "2026-07-28",
@@ -181,6 +191,14 @@ const STATELESS_SUPPORTED_VERSIONS: readonly string[] = [
181
191
  /** Version echoed in MCP-Protocol-Version header on error responses (server's stable baseline) */
182
192
  const STATELESS_FALLBACK_VERSION = "2025-06-18";
183
193
 
194
+ const JSONRPC_INVALID_PARAMS = ErrorCode.InvalidParams;
195
+ const MCP_UNSUPPORTED_PROTOCOL_VERSION = -32004;
196
+
197
+ interface StatelessClientMeta {
198
+ readonly clientInfo?: Implementation;
199
+ readonly clientCapabilities?: ClientCapabilities;
200
+ }
201
+
184
202
  /**
185
203
  * Narrow type-guard: returns true iff `v` is a plain object (not array, not null).
186
204
  * Used to safely extract fields from JSON-RPC `params` without unsafe casts.
@@ -636,6 +654,10 @@ export class McpApp {
636
654
  ? { sessionId: ctx.sessionId }
637
655
  : {}),
638
656
  ...(ctx.authInfo ? { authInfo: ctx.authInfo as AuthInfo } : {}),
657
+ ...(ctx.clientInfo !== undefined ? { clientInfo: ctx.clientInfo } : {}),
658
+ ...(ctx.clientCapabilities !== undefined
659
+ ? { clientCapabilities: ctx.clientCapabilities }
660
+ : {}),
639
661
  }));
640
662
  });
641
663
  }
@@ -656,6 +678,7 @@ export class McpApp {
656
678
  request?: Request,
657
679
  sessionId?: string,
658
680
  preVerifiedAuthInfo?: AuthInfo,
681
+ clientMeta?: StatelessClientMeta,
659
682
  ): Promise<MiddlewareResult> {
660
683
  if (!this.middlewareRunner) {
661
684
  throw new Error(
@@ -672,6 +695,12 @@ export class McpApp {
672
695
  // middleware skips the redundant verifyToken call (avoids JWKS
673
696
  // race conditions on concurrent cold-cache requests).
674
697
  authInfo: preVerifiedAuthInfo,
698
+ ...(clientMeta?.clientInfo !== undefined
699
+ ? { clientInfo: clientMeta.clientInfo }
700
+ : {}),
701
+ ...(clientMeta?.clientCapabilities !== undefined
702
+ ? { clientCapabilities: clientMeta.clientCapabilities }
703
+ : {}),
675
704
  };
676
705
 
677
706
  // OTel span + metrics
@@ -1527,9 +1556,9 @@ export class McpApp {
1527
1556
  // Must run BEFORE any method dispatch so every call (not just initialize)
1528
1557
  // is validated. Sets MCP-Protocol-Version header on all subsequent responses
1529
1558
  // via Hono's c.header() accumulation.
1530
- // Key location: params._meta[STATELESS_PROTO_KEY] (spec 2026-07-28, confirmed).
1531
- // TODO(spec-2026-07-28, valider en interop MCP Inspector): MCP-Protocol-Version
1532
- // request header comparison to body version not enforced until spec text is final.
1559
+ // Key location: params._meta[STATELESS_PROTO_KEY] (SEP-2575 Final).
1560
+ // Tolerant mode: MCP-Protocol-Version may be absent for backward compatibility;
1561
+ // when present it must match the _meta version.
1533
1562
  let statelessVersion: string | undefined;
1534
1563
  if (this.options.transport === "stateless") {
1535
1564
  const clientVersion = isRecord(params) && isRecord(params["_meta"])
@@ -1543,7 +1572,7 @@ export class McpApp {
1543
1572
  jsonrpc: "2.0",
1544
1573
  id,
1545
1574
  error: {
1546
- code: -32020,
1575
+ code: JSONRPC_INVALID_PARAMS,
1547
1576
  message: `Missing required field '${STATELESS_PROTO_KEY}'`,
1548
1577
  },
1549
1578
  },
@@ -1559,7 +1588,7 @@ export class McpApp {
1559
1588
  jsonrpc: "2.0",
1560
1589
  id,
1561
1590
  error: {
1562
- code: -32022,
1591
+ code: MCP_UNSUPPORTED_PROTOCOL_VERSION,
1563
1592
  message: `Unsupported protocolVersion: "${clientVersion}"`,
1564
1593
  data: {
1565
1594
  supported: [...STATELESS_SUPPORTED_VERSIONS],
@@ -1572,12 +1601,56 @@ export class McpApp {
1572
1601
  );
1573
1602
  }
1574
1603
 
1604
+ const headerVersion = c.req.header("MCP-Protocol-Version");
1605
+ if (
1606
+ headerVersion !== undefined &&
1607
+ headerVersion !== clientVersion
1608
+ ) {
1609
+ return jsonRpcResponse(
1610
+ {
1611
+ jsonrpc: "2.0",
1612
+ id,
1613
+ error: {
1614
+ code: JSONRPC_INVALID_PARAMS,
1615
+ message:
1616
+ `MCP-Protocol-Version header "${headerVersion}" does not match _meta protocolVersion "${clientVersion}"`,
1617
+ },
1618
+ },
1619
+ 400,
1620
+ { "MCP-Protocol-Version": STATELESS_FALLBACK_VERSION },
1621
+ );
1622
+ }
1623
+
1575
1624
  statelessVersion = clientVersion;
1576
1625
  // Spec 2026-07-28: echo negotiated version in every response header.
1577
1626
  // c.header() accumulates headers — all subsequent c.json() calls inherit it.
1578
1627
  c.header("MCP-Protocol-Version", statelessVersion);
1579
1628
  }
1580
1629
 
1630
+ if (
1631
+ method === "server/discover" &&
1632
+ this.options.transport === "stateless"
1633
+ ) {
1634
+ return c.json({
1635
+ jsonrpc: "2.0",
1636
+ id,
1637
+ result: {
1638
+ supportedVersions: [...STATELESS_SUPPORTED_VERSIONS],
1639
+ capabilities: {
1640
+ tools: {},
1641
+ resources: this.resources.size > 0 ? {} : undefined,
1642
+ },
1643
+ serverInfo: {
1644
+ name: this.options.name,
1645
+ version: this.options.version,
1646
+ },
1647
+ ...(this.options.instructions
1648
+ ? { instructions: this.options.instructions }
1649
+ : {}),
1650
+ },
1651
+ });
1652
+ }
1653
+
1581
1654
  // Initialize - create session and return session ID (now auth-verified)
1582
1655
  if (method === "initialize") {
1583
1656
  // Track A: stateless V2 — respond without creating a session or emitting Mcp-Session-Id.
@@ -1683,6 +1756,20 @@ export class McpApp {
1683
1756
  if (method === "tools/call" && params?.name) {
1684
1757
  const toolName = params.name as string;
1685
1758
  const args = (params.arguments as Record<string, unknown>) || {};
1759
+ const statelessClientMeta:
1760
+ | StatelessClientMeta
1761
+ | undefined = this.options.transport === "stateless" &&
1762
+ isRecord(params) &&
1763
+ isRecord(params["_meta"])
1764
+ ? {
1765
+ clientInfo: params["_meta"][STATELESS_CLIENT_INFO_KEY] as
1766
+ | Implementation
1767
+ | undefined,
1768
+ clientCapabilities: params["_meta"][
1769
+ STATELESS_CLIENT_CAPABILITIES_KEY
1770
+ ] as ClientCapabilities | undefined,
1771
+ }
1772
+ : undefined;
1686
1773
 
1687
1774
  try {
1688
1775
  const result = await this.executeToolCall(
@@ -1691,6 +1778,7 @@ export class McpApp {
1691
1778
  c.req.raw,
1692
1779
  reqSessionId,
1693
1780
  httpAuthInfo,
1781
+ statelessClientMeta,
1694
1782
  );
1695
1783
  return c.json({
1696
1784
  jsonrpc: "2.0",
@@ -1710,7 +1798,10 @@ export class McpApp {
1710
1798
  );
1711
1799
  }
1712
1800
  if (error.code === "insufficient_scope") {
1713
- return createForbiddenResponse(error.requiredScopes ?? []);
1801
+ return createForbiddenResponse(
1802
+ error.requiredScopes ?? [],
1803
+ error.resourceMetadataUrl,
1804
+ );
1714
1805
  }
1715
1806
  }
1716
1807
 
@@ -1818,6 +1909,10 @@ export class McpApp {
1818
1909
  }
1819
1910
 
1820
1911
  // MCP protocol methods we don't implement — return empty results
1912
+ // ping: SEP-2575 removes ping in stateless mode, but we deliberately keep
1913
+ // answering it for backward compatibility. A SEP-conformant client won't send
1914
+ // it, and a stale client using ping for liveness keeps working. (Decision:
1915
+ // tolerant over strict, consistent with the rest of the stateless conformance work.)
1821
1916
  if (method === "ping") {
1822
1917
  return c.json({ jsonrpc: "2.0", id, result: {} });
1823
1918
  }
@@ -7,6 +7,11 @@
7
7
  * @module lib/server/middleware/types
8
8
  */
9
9
 
10
+ import type {
11
+ ClientCapabilities,
12
+ Implementation,
13
+ } from "@modelcontextprotocol/sdk/types.js";
14
+
10
15
  /**
11
16
  * Context passed through the middleware pipeline.
12
17
  * Each middleware can read and enrich the context.
@@ -24,6 +29,12 @@ export interface MiddlewareContext {
24
29
  /** Session ID (only present for HTTP transport) */
25
30
  sessionId?: string;
26
31
 
32
+ /** Client implementation metadata (stateless HTTP transport, when provided) */
33
+ clientInfo?: Implementation;
34
+
35
+ /** Client capabilities metadata (stateless HTTP transport, when provided) */
36
+ clientCapabilities?: ClientCapabilities;
37
+
27
38
  /** Extensible by middlewares (e.g., authInfo added by auth middleware) */
28
39
  [key: string]: unknown;
29
40
  }
@@ -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;
package/src/types.ts CHANGED
@@ -8,6 +8,10 @@
8
8
  */
9
9
 
10
10
  import type { McpUiToolMeta as McpUiToolMetaBase } from "@modelcontextprotocol/ext-apps";
11
+ import type {
12
+ ClientCapabilities,
13
+ Implementation,
14
+ } from "@modelcontextprotocol/sdk/types.js";
11
15
 
12
16
  /**
13
17
  * Rate limit configuration
@@ -467,6 +471,8 @@ export interface ToolHandlerContext {
467
471
  readonly request?: Request;
468
472
  readonly sessionId?: string;
469
473
  readonly authInfo?: import("./auth/types.js").AuthInfo;
474
+ readonly clientInfo?: Implementation;
475
+ readonly clientCapabilities?: ClientCapabilities;
470
476
  }
471
477
 
472
478
  export type ToolHandler = (