@smartbear/mcp 0.40.0 → 0.41.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/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
  };
@@ -1,8 +1,9 @@
1
1
  import { enableCompileCache } from "node:module";
2
- import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
2
+ import { StdioServerTransport, serveStdio } from "@modelcontextprotocol/server/stdio";
3
+ import { setProcessClientIdentity, toClientIdentity } from "./client-identity.js";
3
4
  import { clientRegistry } from "./client-registry.js";
4
5
  import { USER_AGENT } from "./info.js";
5
- import { handleInitializeMessage } from "./initialize.js";
6
+ import { handleInitializeMessage, extractModernClientMeta } from "./initialize.js";
6
7
  import { SmartBearMcpServer } from "./server.js";
7
8
  import { registerShutdownHandler } from "./shutdown.js";
8
9
  import { isOptionalType, getTypeDescription } from "./zod-utils.js";
@@ -20,19 +21,8 @@ function getNoConfigMessage() {
20
21
  }
21
22
  return messages;
22
23
  }
23
- async function runStdioMode() {
24
- if (process.argv.includes("--version")) {
25
- console.log(`User-Agent: ${USER_AGENT}`);
26
- process.exit(0);
27
- } else if (process.argv.includes("--help")) {
28
- console.log(
29
- "The following environment variables can be set to configure each of the SmartBear clients:"
30
- );
31
- console.log(getNoConfigMessage().join("\n"));
32
- process.exit(0);
33
- }
34
- enableCompileCache();
35
- const server = new SmartBearMcpServer(process.env.MCP_TOOLSETS);
24
+ async function buildStdioServer(era = "legacy") {
25
+ const server = new SmartBearMcpServer(process.env.MCP_TOOLSETS, era);
36
26
  const configuredCount = await clientRegistry.configure(
37
27
  server,
38
28
  (client, key) => {
@@ -50,21 +40,91 @@ ${message.join("\n")}` : "No clients support environment variable configuration.
50
40
  await server.addClient(entry);
51
41
  }
52
42
  }
43
+ return server;
44
+ }
45
+ function createInitializeCaptureTap() {
46
+ let activeServer;
47
+ const pending = [];
48
+ return {
49
+ observe(message) {
50
+ const modernMeta = extractModernClientMeta(message);
51
+ if (modernMeta) {
52
+ setProcessClientIdentity(
53
+ toClientIdentity(modernMeta.clientInfo, modernMeta.protocolVersion)
54
+ );
55
+ return;
56
+ }
57
+ if (activeServer) {
58
+ handleInitializeMessage(activeServer, message);
59
+ return;
60
+ }
61
+ pending.push(message);
62
+ },
63
+ attachServer(server) {
64
+ activeServer = server;
65
+ for (const message of pending) {
66
+ handleInitializeMessage(server, message);
67
+ }
68
+ pending.length = 0;
69
+ }
70
+ };
71
+ }
72
+ async function runStdioMode() {
73
+ if (process.argv.includes("--version")) {
74
+ console.log(`User-Agent: ${USER_AGENT}`);
75
+ process.exit(0);
76
+ } else if (process.argv.includes("--help")) {
77
+ console.log(
78
+ "The following environment variables can be set to configure each of the SmartBear clients:"
79
+ );
80
+ console.log(getNoConfigMessage().join("\n"));
81
+ process.exit(0);
82
+ }
83
+ enableCompileCache();
53
84
  const transport = new StdioServerTransport();
85
+ const capture = createInitializeCaptureTap();
86
+ let onmessage;
87
+ Object.defineProperty(transport, "onmessage", {
88
+ configurable: true,
89
+ get: () => onmessage,
90
+ set: (handler) => {
91
+ onmessage = (message) => {
92
+ capture.observe(message);
93
+ handler?.(message);
94
+ };
95
+ }
96
+ });
97
+ const handle = serveStdio(
98
+ async (ctx) => {
99
+ const server = await buildStdioServer(ctx.era);
100
+ capture.attachServer(server);
101
+ return server;
102
+ },
103
+ {
104
+ // Serve 2025-era openings alongside modern ones (this is also the
105
+ // default; stated explicitly so the backwards-compatibility guarantee
106
+ // is visible at the call site).
107
+ legacy: "serve",
108
+ transport,
109
+ onerror: (error) => {
110
+ console.error("[MCP][stdio] Transport error:", error);
111
+ }
112
+ }
113
+ );
54
114
  registerShutdownHandler("stdio-transport", async () => {
55
115
  try {
56
- await transport.close();
116
+ await handle.close();
57
117
  } catch (err) {
58
118
  console.error("[MCP][shutdown] Error closing stdio transport:", err);
59
119
  }
60
120
  });
61
- transport.onmessage = (message) => handleInitializeMessage(server, message);
62
- await server.connect(transport);
63
121
  }
64
122
  function getEnvVarName(clientPrefix, key) {
65
123
  return `${clientPrefix.toUpperCase().replace(/-/g, "_")}_${key.toUpperCase()}`;
66
124
  }
67
125
  export {
126
+ buildStdioServer,
127
+ createInitializeCaptureTap,
68
128
  getEnvVarName,
69
129
  runStdioMode
70
130
  };
@@ -1,4 +1,4 @@
1
- const version = "0.40.0";
1
+ const version = "0.41.0";
2
2
  const config = { "mcpServerName": "SmartBear MCP Server" };
3
3
  const packageJson = {
4
4
  version,
@@ -232,7 +232,7 @@ class FunctionalTestingAPI {
232
232
  ],
233
233
  [
234
234
  409,
235
- "Suite execution cannot be cancelled because it has already finished."
235
+ "Suite execution cannot be canceled because it has already finished."
236
236
  ]
237
237
  ]),
238
238
  errorMessageFor("cancel suite execution")
@@ -4,7 +4,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
4
4
  {
5
5
  title: "List Tests",
6
6
  toolset: "Functional Testing",
7
- summary: "Lists all API tests available in your Swagger Functional Testing account. Use this tool when you need to discover available tests before running them or checking their status. Do not use this tool to retrieve test execution results or history.",
7
+ summary: "Lists all API tests available in your Swagger Functional Testing account. Use this tool when you need to discover available tests before running them or checking their status. Returns test IDs usable with `swagger_run_test` to execute a single test, or passable to `swagger_create_suite` to group tests into a suite. Do not use this tool to retrieve test execution results or history.",
8
8
  handler: "listFunctionalTestingTests",
9
9
  idempotent: true,
10
10
  ...READ_ONLY
@@ -32,7 +32,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
32
32
  {
33
33
  title: "Get Test Status",
34
34
  toolset: "Functional Testing",
35
- summary: "Get the status of a Swagger Functional Testing test execution. It returns information about the execution such as its status (running, passed or failed), run time, as well as the break down of the status of each test step.",
35
+ summary: "Get the status of a Swagger Functional Testing test execution. Returns the execution status (`running`, `passed`, or `failed`), run time, and a per-step breakdown. Poll this tool after calling `swagger_run_test` until status is `passed` or `failed`; `running` means the execution is still in progress.",
36
36
  inputSchema: GetFunctionalTestingExecutionTestSchema,
37
37
  handler: "getFunctionalTestingExecution",
38
38
  idempotent: true,
@@ -50,7 +50,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
50
50
  {
51
51
  title: "Cancel Suite Execution",
52
52
  toolset: "Functional Testing",
53
- summary: "Cancels an ongoing test suite execution in your Swagger Functional Testing workspace. Use this tool when you need to stop a long-running or accidentally triggered suite run. Do not use this tool to cancel individual test runs.",
53
+ summary: "Cancels an ongoing test suite execution in your Swagger Functional Testing workspace. Use this tool when you need to stop a long-running or accidentally triggered suite run. The canceled execution is preserved in run history with status `canceled`. Do not use this tool to cancel individual test runs.",
54
54
  inputSchema: CancelFunctionalTestingSuiteExecutionSchema,
55
55
  handler: "cancelFunctionalTestingSuiteExecution",
56
56
  ...WRITE_DESTRUCTIVE,
@@ -87,7 +87,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
87
87
  {
88
88
  title: "Get Suite Status",
89
89
  toolset: "Functional Testing",
90
- summary: "Get the status of a Swagger Functional Testing suite execution. Returns the overall status (pending, canceled, passed or failed), whether the run is finished, and a per-test breakdown with pass/fail. Use this to poll for the outcome of a suite run triggered by `swagger_run_suite`. Requires the suite's `slug` and the `executionId` returned by `swagger_run_suite`.",
90
+ summary: "Get the status of a Swagger Functional Testing suite execution. Returns the overall status (`pending`, `canceled`, `passed`, or `failed`), whether the run is finished, and a per-test breakdown with pass/fail, runtime, step count, and for failed tests a `failedStepsByIndex` map of step index to error message. `pending` means the execution has not yet finished (queued or actively running). Poll this tool after calling `swagger_run_suite` until `finished` is `true`. Requires the suite's `slug` and the `executionId` returned by `swagger_run_suite`.",
91
91
  inputSchema: GetFunctionalTestingSuiteExecutionSchema,
92
92
  handler: "getFunctionalTestingSuiteExecution",
93
93
  idempotent: true,
@@ -96,7 +96,7 @@ const FUNCTIONAL_TESTING_TOOLS = [
96
96
  {
97
97
  title: "Get Test Execution History",
98
98
  toolset: "Functional Testing",
99
- summary: "Retrieves the execution history for a given test in your Swagger Functional Testing workspace. Returns a list of past runs, each including pass/fail status, run time, creation timestamp, and — for failed runs — a per-step breakdown of failure details. Use this tool when you need to check past run results, identify failures, or assess test reliability over time. Do not use this tool to run a test or retrieve suite-level execution results.",
99
+ summary: "Retrieves the execution history for a given test in your Swagger Functional Testing workspace. Returns the total run count and a list of past runs, each including pass/fail status, run time, creation timestamp, and — for failed runs — a per-step breakdown of failure details. Supports pagination via `limit` (1–100, default 25) and `offset` (default 0). Use this tool when you need to check past run results, identify failures, or assess test reliability over time. Do not use this tool to run a test or retrieve suite-level execution results.",
100
100
  inputSchema: GetFunctionalTestHistoryParamsSchema,
101
101
  handler: "getFunctionalTestingTestHistory",
102
102
  idempotent: true,
@@ -1,5 +1,9 @@
1
+ import { z } from "zod";
1
2
  import { Tool } from "../../../common/tools.js";
2
3
  import { GetIssueLinkTestCases200Response, GetIssueLinkTestCasesParams } from "../../common/rest-api-schemas.js";
4
+ const UpdatedGetIssueLinkTestCasesResponse = z.strictObject({
5
+ testCases: GetIssueLinkTestCases200Response
6
+ });
3
7
  class GetTestCases extends Tool {
4
8
  specification = {
5
9
  title: "Get Issue Link Test Cases",
@@ -8,7 +12,7 @@ class GetTestCases extends Tool {
8
12
  readOnly: true,
9
13
  idempotent: true,
10
14
  inputSchema: GetIssueLinkTestCasesParams,
11
- outputSchema: GetIssueLinkTestCases200Response,
15
+ outputSchema: UpdatedGetIssueLinkTestCasesResponse,
12
16
  examples: [
13
17
  {
14
18
  description: "Check which test cases are linked to Jira issue PROJ-123",
@@ -30,5 +34,6 @@ class GetTestCases extends Tool {
30
34
  };
31
35
  }
32
36
  export {
33
- GetTestCases
37
+ GetTestCases,
38
+ UpdatedGetIssueLinkTestCasesResponse
34
39
  };
@@ -1,5 +1,9 @@
1
+ import { z } from "zod";
1
2
  import { Tool } from "../../../common/tools.js";
2
3
  import { GetIssueLinkTestCycles200Response, GetIssueLinkTestCyclesParams } from "../../common/rest-api-schemas.js";
4
+ const UpdatedGetIssueLinkTestCyclesResponse = z.strictObject({
5
+ testCycles: GetIssueLinkTestCycles200Response
6
+ });
3
7
  class GetTestCycles extends Tool {
4
8
  specification = {
5
9
  title: "Get Test Cycles linked to a Jira issue",
@@ -8,7 +12,7 @@ class GetTestCycles extends Tool {
8
12
  readOnly: true,
9
13
  idempotent: true,
10
14
  inputSchema: GetIssueLinkTestCyclesParams,
11
- outputSchema: GetIssueLinkTestCycles200Response,
15
+ outputSchema: UpdatedGetIssueLinkTestCyclesResponse,
12
16
  examples: [
13
17
  {
14
18
  description: "Check which test cycles are linked to Jira issue PROJ-123",
@@ -29,5 +33,6 @@ class GetTestCycles extends Tool {
29
33
  };
30
34
  }
31
35
  export {
32
- GetTestCycles
36
+ GetTestCycles,
37
+ UpdatedGetIssueLinkTestCyclesResponse
33
38
  };
@@ -1,5 +1,9 @@
1
+ import { z } from "zod";
1
2
  import { Tool } from "../../../common/tools.js";
2
3
  import { GetIssueLinkTestExecutions200Response, GetIssueLinkTestExecutionsParams } from "../../common/rest-api-schemas.js";
4
+ const UpdatedGetIssueLinkTestExecutionsResponse = z.strictObject({
5
+ testExecutions: GetIssueLinkTestExecutions200Response
6
+ });
3
7
  class GetTestExecutions extends Tool {
4
8
  specification = {
5
9
  title: "Get test executions linked to a Jira issue",
@@ -8,7 +12,7 @@ class GetTestExecutions extends Tool {
8
12
  readOnly: true,
9
13
  idempotent: true,
10
14
  inputSchema: GetIssueLinkTestExecutionsParams,
11
- outputSchema: GetIssueLinkTestExecutions200Response,
15
+ outputSchema: UpdatedGetIssueLinkTestExecutionsResponse,
12
16
  examples: [
13
17
  {
14
18
  description: "Check which test executions are linked to Jira issue PROJ-123",
@@ -29,5 +33,6 @@ class GetTestExecutions extends Tool {
29
33
  };
30
34
  }
31
35
  export {
32
- GetTestExecutions
36
+ GetTestExecutions,
37
+ UpdatedGetIssueLinkTestExecutionsResponse
33
38
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartbear/mcp",
3
- "version": "0.40.0",
3
+ "version": "0.41.0",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },