@smartbear/mcp 0.40.0 → 0.41.3

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/README.md CHANGED
@@ -315,6 +315,13 @@ Add the following configuration to your `claude_desktop_config.json` to launch t
315
315
  }
316
316
  ```
317
317
 
318
+ ## Server Configuration (HTTP mode)
319
+
320
+ | Variable | Default | Purpose |
321
+ |---|---|---|
322
+ | `BASE_URL` | *(derived from request)* | The server's own public URL, e.g. `https://mcp.example.com`. Set this on any deployment behind a proxy or load balancer — otherwise the address advertised for OAuth discovery is derived from the client-supplied `Host` header. |
323
+ | `TRUST_PROXY` | `false` | Set to `true` only when a proxy in front of the server sets `X-Forwarded-Host` and strips any client-supplied value. |
324
+
318
325
  ## Documentation
319
326
 
320
327
  For detailed introduction, examples, and advanced configuration visit our 📖 [Full Documentation](https://developer.smartbear.com/smartbear-mcp)
@@ -1,10 +1,18 @@
1
1
  import NodeCache from "node-cache";
2
+ const DEFAULT_CACHE_TTL_SECONDS = 86400;
3
+ function getConfiguredCacheTtlSeconds() {
4
+ const parsed = process.env.CACHE_TTL ? Number.parseInt(process.env.CACHE_TTL, 10) : DEFAULT_CACHE_TTL_SECONDS;
5
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_CACHE_TTL_SECONDS;
6
+ }
7
+ function isCachingEnabled() {
8
+ return process.env.CACHE_ENABLED !== "false";
9
+ }
2
10
  class CacheService {
3
11
  cache;
4
12
  enabled;
5
13
  constructor() {
6
- this.enabled = process.env.CACHE_ENABLED !== "false";
7
- const ttl = process.env.CACHE_TTL ? Number.parseInt(process.env.CACHE_TTL, 10) : 86400;
14
+ this.enabled = isCachingEnabled();
15
+ const ttl = getConfiguredCacheTtlSeconds();
8
16
  this.cache = this.enabled ? new NodeCache({
9
17
  stdTTL: ttl
10
18
  }) : null;
@@ -53,5 +61,7 @@ class CacheService {
53
61
  }
54
62
  }
55
63
  export {
56
- CacheService
64
+ CacheService,
65
+ getConfiguredCacheTtlSeconds,
66
+ isCachingEnabled
57
67
  };
@@ -1,8 +1,28 @@
1
+ import { PROTOCOL_VERSION_META_KEY, CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY } from "@modelcontextprotocol/server";
1
2
  import { toClientIdentity, setProcessClientIdentity } from "./client-identity.js";
3
+ function extractModernClientMeta(message) {
4
+ if (typeof message !== "object" || message === null) {
5
+ return void 0;
6
+ }
7
+ const params = message.params;
8
+ const meta = params?._meta;
9
+ const protocolVersion = meta?.[PROTOCOL_VERSION_META_KEY];
10
+ if (typeof protocolVersion !== "string") {
11
+ return void 0;
12
+ }
13
+ return {
14
+ protocolVersion,
15
+ clientInfo: meta?.[CLIENT_INFO_META_KEY],
16
+ clientCapabilities: meta?.[CLIENT_CAPABILITIES_META_KEY]
17
+ };
18
+ }
2
19
  function handleInitializeMessage(server, message) {
3
20
  if (typeof message !== "object" || message === null || !("method" in message) || message.method !== "initialize") {
4
21
  return;
5
22
  }
23
+ if (extractModernClientMeta(message)) {
24
+ return;
25
+ }
6
26
  const params = message.params;
7
27
  const identity = toClientIdentity(
8
28
  params?.clientInfo,
@@ -22,5 +42,6 @@ function handleInitializeMessage(server, message) {
22
42
  }
23
43
  }
24
44
  export {
45
+ extractModernClientMeta,
25
46
  handleInitializeMessage
26
47
  };
@@ -1,4 +1,71 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { CLIENT_CAPABILITIES_META_KEY, inputResponse, inputRequired } from "@modelcontextprotocol/server";
3
+ class InputRequiredSignal extends Error {
4
+ constructor(result) {
5
+ super("Tool requires client input to continue (multi-round-trip)");
6
+ this.result = result;
7
+ this.name = "InputRequiredSignal";
8
+ Object.setPrototypeOf(this, InputRequiredSignal.prototype);
9
+ }
10
+ }
11
+ const elicitationScopeStorage = new AsyncLocalStorage();
12
+ function runWithElicitationScope(ctx, fn) {
13
+ const mcpReq = ctx?.mcpReq;
14
+ const envelope = mcpReq?.envelope;
15
+ const capabilities = envelope?.[CLIENT_CAPABILITIES_META_KEY];
16
+ const scope = {
17
+ modern: !!envelope,
18
+ elicitationDeclared: typeof capabilities === "object" && capabilities !== null && Object.hasOwn(capabilities, "elicitation"),
19
+ responses: {
20
+ ...decodeElicitationState(mcpReq?.requestState?.()),
21
+ ...mcpReq?.inputResponses
22
+ },
23
+ issued: 0
24
+ };
25
+ return elicitationScopeStorage.run(scope, fn);
26
+ }
27
+ const ELICITATION_STATE_VERSION = 1;
28
+ function encodeElicitationState(responses) {
29
+ return JSON.stringify({ v: ELICITATION_STATE_VERSION, responses });
30
+ }
31
+ const MAX_ELICITATION_STATE_LENGTH = 32768;
32
+ function decodeElicitationState(raw) {
33
+ if (typeof raw !== "string" || raw === "" || raw.length > MAX_ELICITATION_STATE_LENGTH) {
34
+ return {};
35
+ }
36
+ try {
37
+ const parsed = JSON.parse(raw);
38
+ if (typeof parsed === "object" && parsed !== null && parsed.v === ELICITATION_STATE_VERSION && typeof parsed.responses === "object" && parsed.responses !== null && !Array.isArray(parsed.responses)) {
39
+ return parsed.responses;
40
+ }
41
+ } catch {
42
+ }
43
+ return {};
44
+ }
1
45
  async function executeElicitationOrPolyfill(server, params, options) {
46
+ const scope = elicitationScopeStorage.getStore();
47
+ if (scope?.modern) {
48
+ if (!scope.elicitationDeclared) {
49
+ return createElicitationPolyfillResult(params);
50
+ }
51
+ scope.issued += 1;
52
+ const key = `input_${scope.issued}`;
53
+ const view = inputResponse(scope.responses, key);
54
+ if (view.kind === "elicit") {
55
+ return view.content !== void 0 ? {
56
+ action: view.action,
57
+ content: view.content
58
+ } : { action: view.action };
59
+ }
60
+ throw new InputRequiredSignal(
61
+ inputRequired({
62
+ inputRequests: {
63
+ [key]: inputRequired.elicit(params)
64
+ },
65
+ ...Object.keys(scope.responses).length > 0 ? { requestState: encodeElicitationState(scope.responses) } : {}
66
+ })
67
+ );
68
+ }
2
69
  if (!server.isElicitationSupported()) {
3
70
  return createElicitationPolyfillResult(params);
4
71
  }
@@ -20,6 +87,8 @@ function isElicitationPolyfillResult(value) {
20
87
  return typeof value === "object" && value !== null && "requiresInputCollection" in value && value.requiresInputCollection === true;
21
88
  }
22
89
  export {
90
+ InputRequiredSignal,
23
91
  executeElicitationOrPolyfill,
24
- isElicitationPolyfillResult
92
+ isElicitationPolyfillResult,
93
+ runWithElicitationScope
25
94
  };
@@ -1,7 +1,10 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  const requestContextStorage = new AsyncLocalStorage();
3
3
  function withRequestContext(req, fn) {
4
- return requestContextStorage.run({ headers: req.headers }, fn);
4
+ return withRequestHeaders(req.headers, fn);
5
+ }
6
+ function withRequestHeaders(headers, fn) {
7
+ return requestContextStorage.run({ headers }, fn);
5
8
  }
6
9
  function getRequestContext() {
7
10
  return requestContextStorage.getStore();
@@ -12,6 +15,25 @@ function setRequestMcpClient(identity) {
12
15
  context.mcpClient = identity;
13
16
  }
14
17
  }
18
+ function setModernRequestClient(meta) {
19
+ const context = getRequestContext();
20
+ if (!context) {
21
+ return;
22
+ }
23
+ context.era = "modern";
24
+ context.clientMeta = meta;
25
+ context.mcpClient = {
26
+ name: meta.clientInfo?.name,
27
+ version: meta.clientInfo?.version,
28
+ protocolVersion: meta.protocolVersion
29
+ };
30
+ }
31
+ function getRequestEra() {
32
+ return getRequestContext()?.era ?? "legacy";
33
+ }
34
+ function getRequestClientMeta() {
35
+ return getRequestContext()?.clientMeta;
36
+ }
15
37
  function getRequestHeader(name) {
16
38
  const context = getRequestContext();
17
39
  if (!context?.headers) return void 0;
@@ -19,9 +41,13 @@ function getRequestHeader(name) {
19
41
  return headerValue;
20
42
  }
21
43
  export {
44
+ getRequestClientMeta,
22
45
  getRequestContext,
46
+ getRequestEra,
23
47
  getRequestHeader,
24
48
  requestContextStorage,
49
+ setModernRequestClient,
25
50
  setRequestMcpClient,
26
- withRequestContext
51
+ withRequestContext,
52
+ withRequestHeaders
27
53
  };
@@ -1,12 +1,26 @@
1
1
  import { McpServer, ResourceTemplate } from "@modelcontextprotocol/server";
2
2
  import { z, ZodObject } from "zod";
3
3
  import Bugsnag from "./bugsnag.js";
4
- import { CacheService } from "./cache.js";
5
- import { toClientIdentity } from "./client-identity.js";
4
+ import { isCachingEnabled, CacheService, getConfiguredCacheTtlSeconds } from "./cache.js";
5
+ import { toClientIdentity, getCurrentClientIdentity } from "./client-identity.js";
6
6
  import { MCP_SERVER_VERSION, MCP_SERVER_NAME } from "./info.js";
7
- import { executeElicitationOrPolyfill, isElicitationPolyfillResult } from "./pollyfills.js";
7
+ import { runWithElicitationScope, InputRequiredSignal, executeElicitationOrPolyfill, isElicitationPolyfillResult } from "./pollyfills.js";
8
+ import { getRequestEra, getRequestClientMeta } from "./request-context.js";
8
9
  import { ToolError } from "./tools.js";
9
10
  import { getTypeDescription, getDefaultValue, getReadableTypeName, isOptionalType } from "./zod-utils.js";
11
+ function buildCacheHints() {
12
+ const hint = {
13
+ ttlMs: getConfiguredCacheTtlSeconds() * 1e3,
14
+ cacheScope: "private"
15
+ };
16
+ return {
17
+ "tools/list": hint,
18
+ "prompts/list": hint,
19
+ "resources/list": hint,
20
+ "resources/templates/list": hint,
21
+ "resources/read": hint
22
+ };
23
+ }
10
24
  class SmartBearMcpServer extends McpServer {
11
25
  cache;
12
26
  elicitationSupported = false;
@@ -14,20 +28,39 @@ class SmartBearMcpServer extends McpServer {
14
28
  clients = [];
15
29
  enabledToolsets;
16
30
  mcpClientIdentity;
17
- constructor(enabledToolsets) {
31
+ constructor(enabledToolsets, era = "legacy") {
18
32
  super(
19
33
  {
20
34
  name: MCP_SERVER_NAME,
21
35
  version: MCP_SERVER_VERSION
22
36
  },
23
37
  {
24
- capabilities: {
25
- // resources and prompts are supported by some but not all clients
38
+ capabilities: era === "modern" ? {
39
+ // resources and prompts are supported by some but not all clients.
40
+ // No `logging`: deprecated by SEP-2577 as of 2026-07-28 (our
41
+ // diagnostics already go to stderr). `listChanged` stays
42
+ // advertised: on the modern era it tells clients which
43
+ // notification types a `subscriptions/listen` filter may
44
+ // request, and the SDK's serving entries implement
45
+ // `subscriptions/listen` themselves — no server-side work.
46
+ tools: { listChanged: true }
47
+ } : {
48
+ // Legacy (2025-era) capabilities, unchanged for the
49
+ // deprecation window.
26
50
  tools: { listChanged: true },
27
51
  // Server supports dynamic tool lists
28
52
  logging: {}
29
53
  // Server supports logging messages
30
- }
54
+ },
55
+ // Cache hints stamped onto the cacheable modern-era (2026-07-28)
56
+ // results (tools/list, prompts/list, resources/list,
57
+ // resources/templates/list, resources/read). Lifetime follows the
58
+ // operator's CACHE_TTL; scope is `private` because every result is
59
+ // derived from the caller's own configuration (auth headers,
60
+ // toolsets) and must not be served to other principals from a shared
61
+ // cache. Legacy responses are never affected, and with caching
62
+ // disabled the SDK default (`ttlMs: 0`) stands.
63
+ ...isCachingEnabled() ? { cacheHints: buildCacheHints() } : {}
31
64
  }
32
65
  );
33
66
  this.cache = new CacheService();
@@ -41,14 +74,33 @@ class SmartBearMcpServer extends McpServer {
41
74
  setElicitationSupported(supported) {
42
75
  this.elicitationSupported = supported;
43
76
  }
77
+ /**
78
+ * Whether the current caller supports server-initiated elicitation.
79
+ *
80
+ * Modern era: read from the capabilities this request declared in `_meta`.
81
+ * Only consulted on the legacy code path — modern requests that declare
82
+ * `elicitation` are served via the multi round-trip pattern (MRTR,
83
+ * SEP-2322) in `executeElicitationOrPolyfill` before this is reached, and
84
+ * modern requests that do not declare it fall back to the polyfill.
85
+ * Legacy era: the per-connection flag captured at `initialize`.
86
+ */
44
87
  isElicitationSupported() {
88
+ if (getRequestEra() === "modern") {
89
+ const capabilities = getRequestClientMeta()?.clientCapabilities;
90
+ return !!capabilities && Object.hasOwn(capabilities, "elicitation");
91
+ }
45
92
  return this.elicitationSupported;
46
93
  }
47
94
  setClientInfo(info) {
48
95
  this.clientInfo = info;
49
96
  }
97
+ /**
98
+ * Client info for the current caller: from this request's `_meta` envelope in
99
+ * the modern era, falling back to the value captured at `initialize` for
100
+ * legacy connections.
101
+ */
50
102
  getClientInfo() {
51
- return this.clientInfo;
103
+ return getRequestClientMeta()?.clientInfo ?? this.clientInfo;
52
104
  }
53
105
  getClients() {
54
106
  return this.clients;
@@ -61,12 +113,24 @@ class SmartBearMcpServer extends McpServer {
61
113
  this.mcpClientIdentity = identity;
62
114
  }
63
115
  /**
64
- * Return the MCP client identity for this session. Prefers the value captured
65
- * at `initialize`; falls back to the SDK's `getClientVersion()` so callers
66
- * still get an answer if the explicit capture was skipped.
116
+ * Return the MCP client identity for the current caller.
117
+ *
118
+ * Resolution order: the metadata this request carried in `_meta` (modern
119
+ * era over HTTP, per request), then the value captured at `initialize`
120
+ * (legacy era, per connection), then the process-wide identity (which is how
121
+ * modern-era stdio records its single client), then the SDK's
122
+ * `getClientVersion()` so callers still get an answer if every capture was
123
+ * skipped.
67
124
  */
68
125
  getMcpClientIdentity() {
69
- return this.mcpClientIdentity ?? toClientIdentity(this.server.getClientVersion());
126
+ const modernMeta = getRequestClientMeta();
127
+ if (modernMeta) {
128
+ return toClientIdentity(
129
+ modernMeta.clientInfo,
130
+ modernMeta.protocolVersion
131
+ );
132
+ }
133
+ return this.mcpClientIdentity ?? getCurrentClientIdentity() ?? toClientIdentity(this.server.getClientVersion());
70
134
  }
71
135
  /**
72
136
  * Attach MCP client attribution to a Bugsnag event so errors can be segmented
@@ -115,13 +179,19 @@ class SmartBearMcpServer extends McpServer {
115
179
  `The tool is not configured - configuration options for ${client.name} are missing or invalid.`
116
180
  );
117
181
  }
118
- const result = await cb(args, ctx);
182
+ const result = await runWithElicitationScope(
183
+ ctx,
184
+ () => cb(args, ctx)
185
+ );
119
186
  if (result) {
120
187
  this.validateCallbackResult(result, params);
121
188
  this.addStructuredContentAsText(result);
122
189
  }
123
190
  return result;
124
191
  } catch (e) {
192
+ if (e instanceof InputRequiredSignal) {
193
+ return e.result;
194
+ }
125
195
  if (e instanceof ToolError) {
126
196
  return {
127
197
  isError: true,
@@ -221,6 +291,26 @@ ${result.instructions}`
221
291
  );
222
292
  });
223
293
  }
294
+ this.sortToolsDeterministically();
295
+ }
296
+ /**
297
+ * Re-key the SDK's tool registry alphabetically so `tools/list` output is
298
+ * deterministic regardless of client registration order.
299
+ *
300
+ * The SDK's `tools/list` handler enumerates its registry in insertion
301
+ * order and offers no ordering hook, so this reaches into the private
302
+ * `_registeredTools` map. `server.test.ts` asserts the resulting order, so
303
+ * an SDK upgrade that changes the storage shape fails loudly there.
304
+ */
305
+ sortToolsDeterministically() {
306
+ const registry = this._registeredTools;
307
+ const sorted = Object.fromEntries(
308
+ Object.entries(registry).sort(([a], [b]) => a.localeCompare(b))
309
+ );
310
+ for (const key of Object.keys(registry)) {
311
+ delete registry[key];
312
+ }
313
+ Object.assign(registry, sorted);
224
314
  }
225
315
  validateCallbackResult(result, params) {
226
316
  if (result.isError) {
@@ -1,12 +1,13 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { createServer } from "node:http";
3
4
  import querystring from "node:querystring";
4
- import { NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node";
5
- import { isInitializeRequest } from "@modelcontextprotocol/server";
5
+ import { toNodeHandler, toWebRequest, NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node";
6
+ import { createMcpHandler, isLegacyRequest, isInitializeRequest } from "@modelcontextprotocol/server";
6
7
  import { SSEServerTransport } from "@modelcontextprotocol/server-legacy/sse";
7
8
  import { clientRegistry } from "./client-registry.js";
8
- import { handleInitializeMessage } from "./initialize.js";
9
- import { withRequestContext, setRequestMcpClient } from "./request-context.js";
9
+ import { handleInitializeMessage, extractModernClientMeta } from "./initialize.js";
10
+ import { withRequestHeaders, withRequestContext, setRequestMcpClient, setModernRequestClient } from "./request-context.js";
10
11
  import { SmartBearMcpServer } from "./server.js";
11
12
  import { isDraining, registerShutdownHandler } from "./shutdown.js";
12
13
  import { getEnvVarName } from "./transport-stdio.js";
@@ -37,21 +38,36 @@ function handleReadyRequest(res, draining = isDraining) {
37
38
  JSON.stringify({ status: "ready", timestamp: (/* @__PURE__ */ new Date()).toISOString() })
38
39
  );
39
40
  }
40
- function getBaseUrl(req) {
41
+ function getForwardedProtocol(headers) {
42
+ const forwarded = headers["x-forwarded-proto"] || "";
43
+ const protocol = forwarded.split(",")[0]?.trim().toLowerCase();
44
+ return protocol === "https" ? "https" : "http";
45
+ }
46
+ function getBaseUrlFromHeaders(headers) {
41
47
  const baseUrlOverride = process.env.BASE_URL;
42
48
  if (baseUrlOverride) {
43
49
  return baseUrlOverride;
44
50
  }
45
- const protocol = req.headers["x-forwarded-proto"] || "http";
46
- const host = req.headers["x-forwarded-host"] || req.headers.host;
51
+ const protocol = getForwardedProtocol(headers);
52
+ const hostHeader = headers.host;
53
+ const host = process.env.TRUST_PROXY === "true" ? headers["x-forwarded-host"] || hostHeader : hostHeader;
47
54
  return `${protocol}://${host}`;
48
55
  }
56
+ function getBaseUrl(req) {
57
+ return getBaseUrlFromHeaders(req.headers);
58
+ }
49
59
  async function runHttpMode() {
50
60
  const PORT = process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 3e3;
51
61
  const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",") || [
52
62
  "http://localhost:3000"
53
63
  ];
54
64
  const transports = /* @__PURE__ */ new Map();
65
+ const modernHandler = createModernHandler();
66
+ const modernNodeHandler = toNodeHandler(modernHandler, {
67
+ onerror: (error) => {
68
+ console.error("[MCP][modern] Node adapter error:", error);
69
+ }
70
+ });
55
71
  const allowedAuthHeaders = getHttpHeaders();
56
72
  const allowedHeaders = [
57
73
  "Content-Type",
@@ -61,6 +77,11 @@ async function runHttpMode() {
61
77
  "x-custom-auth-headers",
62
78
  // used by mcp-inspector
63
79
  "mcp-protocol-version",
80
+ // Modern (2026-07-28) per-request routing headers. Browser-based modern
81
+ // clients are blocked by CORS preflight without these.
82
+ "mcp-method",
83
+ "mcp-name",
84
+ "Smartbear-Toolsets",
64
85
  ...allowedAuthHeaders
65
86
  ].join(", ");
66
87
  const httpServer = createServer(
@@ -102,7 +123,7 @@ async function runHttpMode() {
102
123
  return;
103
124
  }
104
125
  if (url.pathname === "/mcp") {
105
- await handleStreamableHttpRequest(req, res, transports);
126
+ await handleMcpEndpoint(req, res, transports, modernNodeHandler);
106
127
  return;
107
128
  }
108
129
  if (req.method === "GET" && url.pathname === "/sse") {
@@ -140,6 +161,11 @@ ${headerHelp.join("\n")}`
140
161
  }
141
162
  });
142
163
  registerShutdownHandler("http-transport", async () => {
164
+ try {
165
+ await modernHandler.close();
166
+ } catch (err) {
167
+ console.error("[MCP][shutdown] Error closing modern handler:", err);
168
+ }
143
169
  await drainHttpTransport(httpServer, transports);
144
170
  });
145
171
  }
@@ -223,7 +249,68 @@ async function createNewTransport(req, res, transports) {
223
249
  await server.connect(transport);
224
250
  return transport;
225
251
  }
226
- async function handleStreamableHttpRequest(req, res, transports) {
252
+ const modernServerStorage = new AsyncLocalStorage();
253
+ function createModernHandler() {
254
+ return createMcpHandler(
255
+ () => {
256
+ const server = modernServerStorage.getStore();
257
+ if (!server) {
258
+ throw new Error(
259
+ "No configured server available for the modern MCP request"
260
+ );
261
+ }
262
+ return server;
263
+ },
264
+ {
265
+ legacy: "reject",
266
+ onerror: (error) => {
267
+ console.error("[MCP][modern] Handler error:", error);
268
+ }
269
+ }
270
+ );
271
+ }
272
+ async function handleMcpEndpoint(req, res, transports, modern) {
273
+ if (req.headers["mcp-session-id"]) {
274
+ await handleStreamableHttpRequest(req, res, transports);
275
+ return;
276
+ }
277
+ const parsedBody = await parseRequestBody(req);
278
+ const probe = await toWebRequest(req, parsedBody);
279
+ if (await isLegacyRequest(probe, parsedBody)) {
280
+ await handleStreamableHttpRequest(req, res, transports, {
281
+ body: parsedBody
282
+ });
283
+ return;
284
+ }
285
+ const server = await newServerFromWebRequest(probe, res);
286
+ if (!server) {
287
+ return;
288
+ }
289
+ const headers = webHeadersToRecord(probe.headers);
290
+ const clientMeta = extractModernClientMetaFromBody(parsedBody);
291
+ await modernServerStorage.run(
292
+ server,
293
+ () => withRequestHeaders(headers, () => {
294
+ if (clientMeta) {
295
+ setModernRequestClient(clientMeta);
296
+ }
297
+ return modern(req, res, parsedBody);
298
+ })
299
+ );
300
+ }
301
+ function extractModernClientMetaFromBody(parsedBody) {
302
+ if (Array.isArray(parsedBody)) {
303
+ for (const message of parsedBody) {
304
+ const meta = extractModernClientMeta(message);
305
+ if (meta) {
306
+ return meta;
307
+ }
308
+ }
309
+ return void 0;
310
+ }
311
+ return extractModernClientMeta(parsedBody);
312
+ }
313
+ async function handleStreamableHttpRequest(req, res, transports, preParsed) {
227
314
  try {
228
315
  const sessionId = req.headers["mcp-session-id"];
229
316
  if (sessionId && !transports.has(sessionId)) {
@@ -241,7 +328,7 @@ async function handleStreamableHttpRequest(req, res, transports) {
241
328
  );
242
329
  return;
243
330
  }
244
- const parsedBody = await parseRequestBody(req);
331
+ const parsedBody = preParsed ? preParsed.body : await parseRequestBody(req);
245
332
  let transport;
246
333
  if (sessionId) {
247
334
  const existingTransport = getExistingTransport(
@@ -347,16 +434,33 @@ function getConfigValue(clientPrefix, key, req) {
347
434
  const envVarName = getEnvVarName(clientPrefix, key);
348
435
  return process.env[envVarName] || null;
349
436
  }
350
- async function newServer(req, res) {
351
- const enabledToolsets = getConfigValue("smartbear", "toolsets", req) || void 0;
352
- const server = new SmartBearMcpServer(enabledToolsets);
437
+ function getConfigValueFromWebRequest(clientPrefix, key, request) {
438
+ const queryStringName = getQueryStringName(clientPrefix, key);
439
+ const searchParams = new URL(request.url).searchParams;
440
+ const queryValue = searchParams.get(queryStringName) ?? searchParams.get(queryStringName.toLowerCase());
441
+ if (queryValue) {
442
+ return queryValue;
443
+ }
444
+ const headerValue = request.headers.get(getHeaderName(clientPrefix, key));
445
+ if (headerValue) {
446
+ return headerValue;
447
+ }
448
+ const envVarName = getEnvVarName(clientPrefix, key);
449
+ return process.env[envVarName] || null;
450
+ }
451
+ function webHeadersToRecord(headers) {
452
+ return Object.fromEntries(headers.entries());
453
+ }
454
+ async function buildConfiguredServer(getConfig, headers, host, res, era) {
455
+ const enabledToolsets = getConfig("smartbear", "toolsets") || void 0;
456
+ const server = new SmartBearMcpServer(enabledToolsets, era);
353
457
  try {
354
- const configuredCount = await withRequestContext(
355
- req,
458
+ const configuredCount = await withRequestHeaders(
459
+ headers,
356
460
  () => clientRegistry.configure(
357
461
  server,
358
462
  (client, key) => {
359
- return getConfigValue(client.configPrefix, key, req);
463
+ return getConfig(client.configPrefix, key);
360
464
  },
361
465
  true
362
466
  // ignoreMissingRequiredConfigs
@@ -370,8 +474,8 @@ async function newServer(req, res) {
370
474
  "No clients successfully configured. Missing authentication headers."
371
475
  );
372
476
  }
373
- const hasAuth = withRequestContext(
374
- req,
477
+ const hasAuth = withRequestHeaders(
478
+ headers,
375
479
  () => server.getClients().some((client) => {
376
480
  if (!client.getAuthToken) return true;
377
481
  return client.getAuthToken() !== null;
@@ -386,18 +490,36 @@ async function newServer(req, res) {
386
490
  const headerHelp = getHttpHeadersHelp();
387
491
  const errorMessage = headerHelp.length > 0 ? `Configuration error: ${error instanceof Error ? error.message : String(error)}. Please provide valid headers:
388
492
  ${headerHelp.join("\n")}` : "No clients support HTTP header configuration.";
389
- const headers = {
493
+ const responseHeaders = {
390
494
  "Content-Type": "text/plain"
391
495
  };
392
- if (req.headers.host) {
393
- headers["WWW-Authenticate"] = `OAuth resource_metadata="http://${req.headers.host}/.well-known/oauth-protected-resource"`;
496
+ if (process.env.BASE_URL || host) {
497
+ responseHeaders["WWW-Authenticate"] = `OAuth resource_metadata="${getBaseUrlFromHeaders(headers)}/.well-known/oauth-protected-resource"`;
394
498
  }
395
- res.writeHead(401, headers);
499
+ res.writeHead(401, responseHeaders);
396
500
  res.end(errorMessage);
397
501
  return null;
398
502
  }
399
503
  return server;
400
504
  }
505
+ async function newServer(req, res) {
506
+ return buildConfiguredServer(
507
+ (clientPrefix, key) => getConfigValue(clientPrefix, key, req),
508
+ req.headers,
509
+ req.headers.host,
510
+ res,
511
+ "legacy"
512
+ );
513
+ }
514
+ async function newServerFromWebRequest(request, res) {
515
+ return buildConfiguredServer(
516
+ (clientPrefix, key) => getConfigValueFromWebRequest(clientPrefix, key, request),
517
+ webHeadersToRecord(request.headers),
518
+ request.headers.get("host") ?? void 0,
519
+ res,
520
+ "modern"
521
+ );
522
+ }
401
523
  function getHeaderName(clientPrefix, key) {
402
524
  return `${clientPrefix}-${key.split("_").map(
403
525
  (part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()
@@ -434,11 +556,13 @@ function getHttpHeadersHelp() {
434
556
  export {
435
557
  drainHttpTransport,
436
558
  getBaseUrl,
559
+ getBaseUrlFromHeaders,
437
560
  getHeaderName,
438
561
  getQueryStringName,
439
562
  handleHealthRequest,
440
563
  handleReadyRequest,
441
564
  handleStreamableHttpRequest,
442
565
  newServer,
566
+ newServerFromWebRequest,
443
567
  runHttpMode
444
568
  };