@smartbear/mcp 0.41.3 → 0.42.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,12 +315,17 @@ Add the following configuration to your `claude_desktop_config.json` to launch t
315
315
  }
316
316
  ```
317
317
 
318
+ ### Loading only the products you use
319
+
320
+ Set `MCP_CLIENTS` to a comma-separated, case-insensitive list of product names (for example `"MCP_CLIENTS": "QMetry"`) to load only those products. This reduces startup time, which helps on clients with a short `initialize` timeout. Valid names are `BearQ`, `BugSnag`, `Collaborator`, `Contract Testing`, `QMetry`, `QTM4J`, `Reflect`, `Swagger` and `Zephyr`. When unset, all products are loaded.
321
+
318
322
  ## Server Configuration (HTTP mode)
319
323
 
320
324
  | Variable | Default | Purpose |
321
325
  |---|---|---|
322
326
  | `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
327
  | `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. |
328
+ | `MCP_SERVER_AMPLITUDE_API_KEY` | *(unset — analytics off)* | API key for the shared SmartBear Amplitude project. When set, the server reports `Server Initialized`, `Session Started`, `Session Ended`, `Tool Called` and `Tools Listed` usage events (tool outcome and timing only — never tool arguments, results, credentials or raw email). Unset, nothing is tracked. HTTP mode only. |
324
329
 
325
330
  ## Documentation
326
331
 
@@ -124,6 +124,7 @@ class BugsnagClient {
124
124
  configPrefix = "Bugsnag";
125
125
  config = ConfigurationSchema;
126
126
  defaultToolsets = ["Projects"];
127
+ analytics = { appName: "BugSnag", userId: ["sub"] };
127
128
  async configure(_server, config) {
128
129
  this._endpoint = config.endpoint;
129
130
  this._appEndpoint = this.getEndpoint(
@@ -0,0 +1,341 @@
1
+ import { randomUUID, createHash } from "node:crypto";
2
+ import { createInstance, Types } from "@amplitude/analytics-node";
3
+ import { getUserAgent, MCP_SERVER_VERSION } from "./info.js";
4
+ import { requestBearerClaims, getClaim, firstClaim } from "./jwt.js";
5
+ const ANALYTICS_API_KEY_ENV = "MCP_SERVER_AMPLITUDE_API_KEY";
6
+ const ANALYTICS_SOURCE = "MCP";
7
+ const FLUSH_TIMEOUT_MS = 5e3;
8
+ const AnalyticsEvent = {
9
+ SERVER_INITIALIZED: "Server Initialized",
10
+ SESSION_STARTED: "Session Started",
11
+ SESSION_ENDED: "Session Ended",
12
+ TOOL_CALLED: "Tool Called",
13
+ TOOLS_LISTED: "Tools Listed"
14
+ };
15
+ let amplitude;
16
+ const processDeviceId = randomUUID();
17
+ function analyticsIdFromEmail(email) {
18
+ return sha256(email.trim().toLowerCase());
19
+ }
20
+ function analyticsIdFromUserId(integration, userId) {
21
+ return sha256(`${integration}:${userId.trim()}`);
22
+ }
23
+ function sha256(value) {
24
+ return createHash("sha256").update(value).digest("hex");
25
+ }
26
+ function initAnalytics(env = process.env) {
27
+ if (amplitude) {
28
+ return true;
29
+ }
30
+ const apiKey = env[ANALYTICS_API_KEY_ENV]?.trim();
31
+ if (!apiKey) {
32
+ return false;
33
+ }
34
+ try {
35
+ const instance = createInstance();
36
+ instance.init(apiKey, {
37
+ // The SDK must never write to the MCP process's stdout/stderr on our
38
+ // behalf; failures are swallowed by design.
39
+ logLevel: Types.LogLevel.None
40
+ });
41
+ amplitude = instance;
42
+ return true;
43
+ } catch {
44
+ amplitude = void 0;
45
+ return false;
46
+ }
47
+ }
48
+ function resolveClientIdentity(client) {
49
+ const {
50
+ appName,
51
+ userId: userIdPaths,
52
+ organizationId,
53
+ tokenHeader
54
+ } = client.analytics ?? {};
55
+ const claims = requestBearerClaims(tokenHeader);
56
+ const email = getClaim(claims, "email");
57
+ const userId = email ? void 0 : firstClaim(claims, userIdPaths);
58
+ return {
59
+ analytics_id: email ? analyticsIdFromEmail(email) : userId ? analyticsIdFromUserId(client.capabilityPrefix, userId) : void 0,
60
+ organization: firstClaim(claims, organizationId),
61
+ app_name: appName?.trim() || void 0
62
+ };
63
+ }
64
+ function resolveSessionIdentity(clients) {
65
+ let fallback = {};
66
+ for (const client of clients) {
67
+ const resolved = resolveClientIdentity(client);
68
+ if (resolved.analytics_id || resolved.organization) {
69
+ return resolved;
70
+ }
71
+ if (!fallback.app_name && resolved.app_name) {
72
+ fallback = resolved;
73
+ }
74
+ }
75
+ return fallback;
76
+ }
77
+ function mcpClientProperties(identity) {
78
+ return {
79
+ mcp_client_name: identity.name ?? null,
80
+ mcp_client_version: identity.version ?? null,
81
+ protocol_version: identity.protocolVersion ?? null
82
+ };
83
+ }
84
+ function isToolsListRequest(message) {
85
+ if (Array.isArray(message)) {
86
+ return message.some((entry) => isToolsListRequest(entry));
87
+ }
88
+ return typeof message === "object" && message !== null && message.method === "tools/list";
89
+ }
90
+ function trackEvent(eventType, identity, properties, context = {}) {
91
+ if (!amplitude) {
92
+ return;
93
+ }
94
+ try {
95
+ const eventProperties = stripUndefined({
96
+ app_name: identity.app_name,
97
+ organization: identity.organization,
98
+ analytics_id: identity.analytics_id,
99
+ source: ANALYTICS_SOURCE,
100
+ user_agent: context.userAgent ?? getUserAgent(),
101
+ ...properties
102
+ });
103
+ amplitude.track(eventType, eventProperties, {
104
+ user_id: identity.analytics_id,
105
+ // A session-scoped device id lets a session's anonymous and identified
106
+ // events resolve to the same Amplitude user without ever sharing a
107
+ // device id between two real users.
108
+ device_id: context.sessionId ?? (identity.analytics_id ? void 0 : processDeviceId),
109
+ session_id: context.sessionStartedAt,
110
+ time: Date.now(),
111
+ insert_id: randomUUID(),
112
+ app_version: MCP_SERVER_VERSION
113
+ });
114
+ } catch {
115
+ }
116
+ }
117
+ let flushing;
118
+ let flushAgain = false;
119
+ function flushAnalytics() {
120
+ if (!amplitude) {
121
+ return Promise.resolve();
122
+ }
123
+ if (flushing) {
124
+ flushAgain = true;
125
+ return flushing;
126
+ }
127
+ flushing = (async () => {
128
+ do {
129
+ flushAgain = false;
130
+ await flushOnce();
131
+ } while (flushAgain);
132
+ flushing = void 0;
133
+ })();
134
+ return flushing;
135
+ }
136
+ async function flushOnce() {
137
+ let timer;
138
+ try {
139
+ await Promise.race([
140
+ amplitude?.flush().promise,
141
+ new Promise((resolve) => {
142
+ timer = setTimeout(resolve, FLUSH_TIMEOUT_MS);
143
+ timer.unref?.();
144
+ })
145
+ ]);
146
+ } catch {
147
+ } finally {
148
+ if (timer) clearTimeout(timer);
149
+ }
150
+ }
151
+ function trackToolCalled(outcome) {
152
+ if (!amplitude) {
153
+ return;
154
+ }
155
+ try {
156
+ outcome.session?.recordToolCall();
157
+ trackEvent(
158
+ AnalyticsEvent.TOOL_CALLED,
159
+ resolveClientIdentity(outcome.client),
160
+ {
161
+ session_id: outcome.session?.sessionId ?? null,
162
+ tool_name: outcome.toolName,
163
+ integration: outcome.client.capabilityPrefix,
164
+ success: outcome.success,
165
+ duration_ms: outcome.durationMs,
166
+ error_type: outcome.errorType,
167
+ ...mcpClientProperties(outcome.mcpClient)
168
+ },
169
+ {
170
+ sessionId: outcome.session?.sessionId,
171
+ sessionStartedAt: outcome.session?.startedAt
172
+ }
173
+ );
174
+ } catch {
175
+ }
176
+ }
177
+ function trackToolsListed(server) {
178
+ if (!amplitude) {
179
+ return;
180
+ }
181
+ try {
182
+ const session = server.getAnalyticsSession();
183
+ trackEvent(
184
+ AnalyticsEvent.TOOLS_LISTED,
185
+ resolveSessionIdentity(server.getClients()),
186
+ {
187
+ session_id: session?.sessionId ?? null,
188
+ ...mcpClientProperties(server.getMcpClientIdentity())
189
+ },
190
+ {
191
+ sessionId: session?.sessionId,
192
+ sessionStartedAt: session?.startedAt
193
+ }
194
+ );
195
+ } catch {
196
+ }
197
+ }
198
+ function errorTypeOf(error) {
199
+ if (error instanceof Error) {
200
+ return error.constructor?.name || error.name || "Error";
201
+ }
202
+ return "UnknownError";
203
+ }
204
+ class AnalyticsSession {
205
+ sessionId;
206
+ startedAt = Date.now();
207
+ transport;
208
+ server;
209
+ integrations;
210
+ identity = {};
211
+ userAgent;
212
+ toolCallCount = 0;
213
+ started = false;
214
+ ended = false;
215
+ constructor(options) {
216
+ this.sessionId = options.sessionId;
217
+ this.transport = options.transport;
218
+ this.server = options.server;
219
+ this.integrations = options.integrations;
220
+ }
221
+ /**
222
+ * Called once the `initialize` request has been applied to the server, i.e.
223
+ * with the client identity known and inside the request context that
224
+ * carries the caller's credential. Emits `Session Started` then
225
+ * `Server Initialized`. Subsequent calls are ignored.
226
+ */
227
+ onInitialized() {
228
+ if (this.started || !amplitude) {
229
+ return;
230
+ }
231
+ this.started = true;
232
+ try {
233
+ const mcpClient = this.server.getMcpClientIdentity();
234
+ const clients = this.server.getClients();
235
+ this.identity = resolveSessionIdentity(clients);
236
+ this.userAgent = getUserAgent();
237
+ const configured = clients.filter((client) => isConfiguredWithAuth(client)).map((client) => client.capabilityPrefix);
238
+ const notConfigured = this.integrations.filter(
239
+ (integration) => !configured.includes(integration)
240
+ );
241
+ trackEvent(
242
+ AnalyticsEvent.SESSION_STARTED,
243
+ this.identity,
244
+ {
245
+ session_id: this.sessionId,
246
+ transport: this.transport,
247
+ ...mcpClientProperties(mcpClient),
248
+ enabled_toolsets: this.server.getEnabledToolsets() ?? null,
249
+ enabled_integrations: this.integrations,
250
+ configured_integrations: configured,
251
+ not_configured_integrations: notConfigured
252
+ },
253
+ this.context()
254
+ );
255
+ trackEvent(
256
+ AnalyticsEvent.SERVER_INITIALIZED,
257
+ this.identity,
258
+ {
259
+ transport: this.transport,
260
+ ...mcpClientProperties(mcpClient),
261
+ server_version: MCP_SERVER_VERSION
262
+ },
263
+ this.context()
264
+ );
265
+ } catch {
266
+ }
267
+ }
268
+ recordToolCall() {
269
+ this.toolCallCount++;
270
+ }
271
+ /**
272
+ * Emit `Session Ended` and kick off a flush so the event is not stranded in
273
+ * the SDK's buffer when the session's transport goes away. No-op for a
274
+ * session that never completed `initialize`, and idempotent.
275
+ */
276
+ end(reason) {
277
+ if (!this.started || this.ended || !amplitude) {
278
+ return;
279
+ }
280
+ this.ended = true;
281
+ try {
282
+ trackEvent(
283
+ AnalyticsEvent.SESSION_ENDED,
284
+ this.identity,
285
+ {
286
+ session_id: this.sessionId,
287
+ duration_ms: Date.now() - this.startedAt,
288
+ tool_call_count: this.toolCallCount,
289
+ end_reason: reason
290
+ },
291
+ this.context()
292
+ );
293
+ } catch {
294
+ }
295
+ void flushAnalytics();
296
+ }
297
+ context() {
298
+ return {
299
+ sessionId: this.sessionId,
300
+ sessionStartedAt: this.startedAt,
301
+ userAgent: this.userAgent
302
+ };
303
+ }
304
+ }
305
+ function createAnalyticsSession(options) {
306
+ return amplitude ? new AnalyticsSession(options) : void 0;
307
+ }
308
+ function isConfiguredWithAuth(client) {
309
+ try {
310
+ if (!client.isConfigured()) {
311
+ return false;
312
+ }
313
+ return client.getAuthToken ? client.getAuthToken() !== null : true;
314
+ } catch {
315
+ return false;
316
+ }
317
+ }
318
+ function stripUndefined(record) {
319
+ return Object.fromEntries(
320
+ Object.entries(record).filter(([, value]) => value !== void 0)
321
+ );
322
+ }
323
+ export {
324
+ ANALYTICS_API_KEY_ENV,
325
+ ANALYTICS_SOURCE,
326
+ AnalyticsEvent,
327
+ AnalyticsSession,
328
+ analyticsIdFromEmail,
329
+ analyticsIdFromUserId,
330
+ createAnalyticsSession,
331
+ errorTypeOf,
332
+ flushAnalytics,
333
+ initAnalytics,
334
+ isToolsListRequest,
335
+ mcpClientProperties,
336
+ resolveClientIdentity,
337
+ resolveSessionIdentity,
338
+ trackEvent,
339
+ trackToolCalled,
340
+ trackToolsListed
341
+ };
@@ -40,6 +40,7 @@ function handleInitializeMessage(server, message) {
40
40
  server.setElicitationSupported(true);
41
41
  }
42
42
  }
43
+ server.getAnalyticsSession()?.onInitialized();
43
44
  }
44
45
  export {
45
46
  extractModernClientMeta,
@@ -0,0 +1,83 @@
1
+ import { getRequestHeader } from "./request-context.js";
2
+ function decodeJwtClaims(token) {
3
+ const segments = token?.trim().split(".") ?? [];
4
+ if (segments.length !== 3 || !segments[1]) {
5
+ return void 0;
6
+ }
7
+ try {
8
+ const parsed = JSON.parse(
9
+ Buffer.from(segments[1], "base64url").toString("utf8")
10
+ );
11
+ return isRecord(parsed) ? parsed : void 0;
12
+ } catch {
13
+ return void 0;
14
+ }
15
+ }
16
+ const AUTHORIZATION_HEADER = "Authorization";
17
+ function requestBearerClaims(tokenHeader) {
18
+ for (const header of candidateHeaders(tokenHeader)) {
19
+ const claims = decodeJwtClaims(readRequestToken(header));
20
+ if (claims) {
21
+ return claims;
22
+ }
23
+ }
24
+ return void 0;
25
+ }
26
+ function candidateHeaders(tokenHeader) {
27
+ const declared = tokenHeader?.trim();
28
+ if (!declared || declared.toLowerCase() === AUTHORIZATION_HEADER.toLowerCase()) {
29
+ return [AUTHORIZATION_HEADER];
30
+ }
31
+ return [declared, AUTHORIZATION_HEADER];
32
+ }
33
+ function readRequestToken(name) {
34
+ const header = getRequestHeader(name);
35
+ const value = Array.isArray(header) ? header[0] : header;
36
+ return value?.replace(/^Bearer\s+/i, "");
37
+ }
38
+ function getClaim(claims, path) {
39
+ const segments = path.split(".");
40
+ const leaf = segments.pop();
41
+ let node = claims;
42
+ for (const segment of segments) {
43
+ node = isRecord(node) ? node[segment] : void 0;
44
+ }
45
+ if (!isRecord(node)) {
46
+ return void 0;
47
+ }
48
+ const direct = asClaimString(node[leaf]);
49
+ if (direct) {
50
+ return direct;
51
+ }
52
+ const namespaced = Object.entries(node).find(
53
+ ([key]) => key.endsWith(`/${leaf}`)
54
+ );
55
+ return asClaimString(namespaced?.[1]);
56
+ }
57
+ function firstClaim(claims, paths) {
58
+ for (const path of paths ?? []) {
59
+ const value = getClaim(claims, path);
60
+ if (value) {
61
+ return value;
62
+ }
63
+ }
64
+ return void 0;
65
+ }
66
+ function isRecord(value) {
67
+ return typeof value === "object" && value !== null && !Array.isArray(value);
68
+ }
69
+ function asClaimString(value) {
70
+ if (typeof value === "number" && Number.isFinite(value)) {
71
+ return String(value);
72
+ }
73
+ if (typeof value === "string" && value.trim()) {
74
+ return value.trim();
75
+ }
76
+ return void 0;
77
+ }
78
+ export {
79
+ decodeJwtClaims,
80
+ firstClaim,
81
+ getClaim,
82
+ requestBearerClaims
83
+ };
@@ -1,19 +1,17 @@
1
- import { BearQClient } from "../bearq/client.js";
2
- import { BugsnagClient } from "../bugsnag/client.js";
3
- import { CollaboratorClient } from "../collaborator/client.js";
4
- import { PactflowClient } from "../pactflow/client.js";
5
- import { QmetryClient } from "../qmetry/client.js";
6
- import { Qtm4jClient } from "../qtm4j/client.js";
7
- import { ReflectClient } from "../reflect/client.js";
8
- import { SwaggerClient } from "../swagger/client.js";
9
- import { ZephyrClient } from "../zephyr/client.js";
10
1
  import { clientRegistry } from "./client-registry.js";
11
- clientRegistry.register(new BearQClient());
12
- clientRegistry.register(new ReflectClient());
13
- clientRegistry.register(new BugsnagClient());
14
- clientRegistry.register(new SwaggerClient());
15
- clientRegistry.register(new PactflowClient());
16
- clientRegistry.register(new QmetryClient());
17
- clientRegistry.register(new ZephyrClient());
18
- clientRegistry.register(new Qtm4jClient());
19
- clientRegistry.register(new CollaboratorClient());
2
+ const clientLoaders = {
3
+ BearQ: async () => new (await import("../bearq/client.js")).BearQClient(),
4
+ Reflect: async () => new (await import("../reflect/client.js")).ReflectClient(),
5
+ BugSnag: async () => new (await import("../bugsnag/client.js")).BugsnagClient(),
6
+ Swagger: async () => new (await import("../swagger/client.js")).SwaggerClient(),
7
+ "Contract Testing": async () => new (await import("../pactflow/client.js")).PactflowClient(),
8
+ QMetry: async () => new (await import("../qmetry/client.js")).QmetryClient(),
9
+ Zephyr: async () => new (await import("../zephyr/client.js")).ZephyrClient(),
10
+ QTM4J: async () => new (await import("../qtm4j/client.js")).Qtm4jClient(),
11
+ Collaborator: async () => new (await import("../collaborator/client.js")).CollaboratorClient()
12
+ };
13
+ for (const [name, loadClient] of Object.entries(clientLoaders)) {
14
+ if (clientRegistry.isClientEnabled(name)) {
15
+ clientRegistry.register(await loadClient());
16
+ }
17
+ }
@@ -1,6 +1,7 @@
1
1
  import { McpServer, ResourceTemplate } from "@modelcontextprotocol/server";
2
2
  import { z, ZodObject } from "zod";
3
3
  import Bugsnag from "./bugsnag.js";
4
+ import { errorTypeOf, trackToolCalled } from "./analytics.js";
4
5
  import { isCachingEnabled, CacheService, getConfiguredCacheTtlSeconds } from "./cache.js";
5
6
  import { toClientIdentity, getCurrentClientIdentity } from "./client-identity.js";
6
7
  import { MCP_SERVER_VERSION, MCP_SERVER_NAME } from "./info.js";
@@ -28,6 +29,7 @@ class SmartBearMcpServer extends McpServer {
28
29
  clients = [];
29
30
  enabledToolsets;
30
31
  mcpClientIdentity;
32
+ analyticsSession;
31
33
  constructor(enabledToolsets, era = "legacy") {
32
34
  super(
33
35
  {
@@ -105,6 +107,21 @@ class SmartBearMcpServer extends McpServer {
105
107
  getClients() {
106
108
  return this.clients;
107
109
  }
110
+ /** Toolsets enabled for this instance (normalised), or `undefined` for all. */
111
+ getEnabledToolsets() {
112
+ return this.enabledToolsets;
113
+ }
114
+ /**
115
+ * Attach the usage-analytics state for the HTTP session this instance
116
+ * serves. Set by the HTTP transport once a session id exists; never set for
117
+ * stdio or for modern-era (sessionless) requests.
118
+ */
119
+ setAnalyticsSession(session) {
120
+ this.analyticsSession = session;
121
+ }
122
+ getAnalyticsSession() {
123
+ return this.analyticsSession;
124
+ }
108
125
  /**
109
126
  * Record the MCP client identity reported in the `initialize` handshake.
110
127
  * Captured once per session by the transport layer.
@@ -173,6 +190,9 @@ class SmartBearMcpServer extends McpServer {
173
190
  annotations: this.getAnnotations(toolTitle, params)
174
191
  },
175
192
  async (args, ctx) => {
193
+ const startedAt = Date.now();
194
+ let success = true;
195
+ let errorType = null;
176
196
  try {
177
197
  if (!client.isConfigured()) {
178
198
  throw new ToolError(
@@ -186,12 +206,18 @@ class SmartBearMcpServer extends McpServer {
186
206
  if (result) {
187
207
  this.validateCallbackResult(result, params);
188
208
  this.addStructuredContentAsText(result);
209
+ if (result.isError) {
210
+ success = false;
211
+ errorType = "ToolResultError";
212
+ }
189
213
  }
190
214
  return result;
191
215
  } catch (e) {
192
216
  if (e instanceof InputRequiredSignal) {
193
217
  return e.result;
194
218
  }
219
+ success = false;
220
+ errorType = errorTypeOf(e);
195
221
  if (e instanceof ToolError) {
196
222
  return {
197
223
  isError: true,
@@ -210,6 +236,16 @@ class SmartBearMcpServer extends McpServer {
210
236
  });
211
237
  }
212
238
  throw e;
239
+ } finally {
240
+ trackToolCalled({
241
+ client,
242
+ toolName,
243
+ success,
244
+ errorType,
245
+ durationMs: Date.now() - startedAt,
246
+ mcpClient: this.getMcpClientIdentity(),
247
+ session: this.analyticsSession
248
+ });
213
249
  }
214
250
  }
215
251
  );
@@ -5,11 +5,12 @@ import querystring from "node:querystring";
5
5
  import { toNodeHandler, toWebRequest, NodeStreamableHTTPServerTransport } from "@modelcontextprotocol/node";
6
6
  import { createMcpHandler, isLegacyRequest, isInitializeRequest } from "@modelcontextprotocol/server";
7
7
  import { SSEServerTransport } from "@modelcontextprotocol/server-legacy/sse";
8
+ import { initAnalytics, isToolsListRequest, trackToolsListed, createAnalyticsSession, flushAnalytics } from "./analytics.js";
8
9
  import { clientRegistry } from "./client-registry.js";
9
- import { handleInitializeMessage, extractModernClientMeta } from "./initialize.js";
10
+ import { extractModernClientMeta, handleInitializeMessage } from "./initialize.js";
10
11
  import { withRequestHeaders, withRequestContext, setRequestMcpClient, setModernRequestClient } from "./request-context.js";
11
12
  import { SmartBearMcpServer } from "./server.js";
12
- import { isDraining, registerShutdownHandler } from "./shutdown.js";
13
+ import { registerShutdownHandler, isDraining } from "./shutdown.js";
13
14
  import { getEnvVarName } from "./transport-stdio.js";
14
15
  import { isOptionalType, getTypeDescription } from "./zod-utils.js";
15
16
  const PROBE_HEADERS = {
@@ -62,6 +63,10 @@ async function runHttpMode() {
62
63
  "http://localhost:3000"
63
64
  ];
64
65
  const transports = /* @__PURE__ */ new Map();
66
+ if (initAnalytics()) {
67
+ console.log("[MCP HTTP Server] Usage analytics enabled");
68
+ registerShutdownHandler("analytics", flushAnalytics);
69
+ }
65
70
  const modernHandler = createModernHandler();
66
71
  const modernNodeHandler = toNodeHandler(modernHandler, {
67
72
  onerror: (error) => {
@@ -236,19 +241,40 @@ async function createNewTransport(req, res, transports) {
236
241
  onsessioninitialized: (newSessionId) => {
237
242
  console.log(`[MCP] New session initialized: ${newSessionId}`);
238
243
  transports.set(newSessionId, { server, transport });
244
+ attachSessionAnalytics(server, newSessionId, "streamable-http");
239
245
  }
240
246
  });
241
- transport.onmessage = (message) => handleInitializeMessage(server, message);
247
+ transport.onmessage = (message) => handleSessionMessage(server, message);
242
248
  transport.onclose = () => {
243
249
  if (transport.sessionId) {
244
250
  console.log(`[MCP] Session closed: ${transport.sessionId}`);
245
251
  transports.delete(transport.sessionId);
252
+ endSessionAnalytics(server);
246
253
  server.cleanupSession(transport.sessionId);
247
254
  }
248
255
  };
249
256
  await server.connect(transport);
250
257
  return transport;
251
258
  }
259
+ function handleSessionMessage(server, message) {
260
+ handleInitializeMessage(server, message);
261
+ if (isToolsListRequest(message)) {
262
+ trackToolsListed(server);
263
+ }
264
+ }
265
+ function attachSessionAnalytics(server, sessionId, transport) {
266
+ server.setAnalyticsSession(
267
+ createAnalyticsSession({
268
+ sessionId,
269
+ transport,
270
+ server,
271
+ integrations: clientRegistry.getAll().map((client) => client.capabilityPrefix)
272
+ })
273
+ );
274
+ }
275
+ function endSessionAnalytics(server) {
276
+ server.getAnalyticsSession()?.end(isDraining() ? "server_shutdown" : "client_disconnected");
277
+ }
252
278
  const modernServerStorage = new AsyncLocalStorage();
253
279
  function createModernHandler() {
254
280
  return createMcpHandler(
@@ -290,11 +316,14 @@ async function handleMcpEndpoint(req, res, transports, modern) {
290
316
  const clientMeta = extractModernClientMetaFromBody(parsedBody);
291
317
  await modernServerStorage.run(
292
318
  server,
293
- () => withRequestHeaders(headers, () => {
319
+ () => withRequestHeaders(headers, async () => {
294
320
  if (clientMeta) {
295
321
  setModernRequestClient(clientMeta);
296
322
  }
297
- return modern(req, res, parsedBody);
323
+ await modern(req, res, parsedBody);
324
+ if (res.statusCode < 400 && isToolsListRequest(parsedBody)) {
325
+ trackToolsListed(server);
326
+ }
298
327
  })
299
328
  );
300
329
  }
@@ -375,10 +404,12 @@ async function handleLegacySseRequest(req, res, transports) {
375
404
  return;
376
405
  }
377
406
  const transport = new SSEServerTransport("/message", res);
378
- transport.onmessage = (message) => handleInitializeMessage(server, message);
407
+ transport.onmessage = (message) => handleSessionMessage(server, message);
379
408
  transports.set(transport.sessionId, { server, transport });
409
+ attachSessionAnalytics(server, transport.sessionId, "sse");
380
410
  res.on("close", () => {
381
411
  transports.delete(transport.sessionId);
412
+ endSessionAnalytics(server);
382
413
  server.cleanupSession(transport.sessionId);
383
414
  });
384
415
  await server.connect(transport);
@@ -554,13 +585,16 @@ function getHttpHeadersHelp() {
554
585
  return messages;
555
586
  }
556
587
  export {
588
+ attachSessionAnalytics,
557
589
  drainHttpTransport,
590
+ endSessionAnalytics,
558
591
  getBaseUrl,
559
592
  getBaseUrlFromHeaders,
560
593
  getHeaderName,
561
594
  getQueryStringName,
562
595
  handleHealthRequest,
563
596
  handleReadyRequest,
597
+ handleSessionMessage,
564
598
  handleStreamableHttpRequest,
565
599
  newServer,
566
600
  newServerFromWebRequest,
@@ -1,4 +1,4 @@
1
- const version = "0.41.3";
1
+ const version = "0.42.0";
2
2
  const config = { "mcpServerName": "SmartBear MCP Server" };
3
3
  const packageJson = {
4
4
  version,
@@ -1,4 +1,4 @@
1
- import { randomBytes, scryptSync, createHmac } from "node:crypto";
1
+ import { scryptSync, createHmac, randomBytes } from "node:crypto";
2
2
  const PAGINATION_CACHE_TTL_SECONDS = 30;
3
3
  const CACHE_KEY_SECRET = randomBytes(32);
4
4
  function stableStringify(value) {
@@ -1,5 +1,4 @@
1
1
  import yaml from "js-yaml";
2
- import Swagger from "swagger-client";
3
2
  import { ToolError } from "../../common/tools.js";
4
3
  import { RemoteOpenAPIDocumentSchema } from "./ai.js";
5
4
  async function resolveOpenAPISpec(remoteOpenAPIDocument) {
@@ -14,6 +13,7 @@ async function resolveOpenAPISpec(remoteOpenAPIDocument) {
14
13
  );
15
14
  }
16
15
  const unresolvedSpec = await getRemoteSpecContents(openAPISchema.data);
16
+ const { default: Swagger } = await import("swagger-client");
17
17
  const resolvedSpec = await Swagger.resolve({ spec: unresolvedSpec });
18
18
  if (resolvedSpec.errors?.length) {
19
19
  throw new ToolError(
@@ -1,6 +1,6 @@
1
1
  import zod__default from "zod";
2
2
  import { getRequestHeader } from "../common/request-context.js";
3
- import { CONFIG_KEYS, API_CONFIG, SCHEMA_DESCRIPTIONS, CLIENT_CONFIG, ERROR_MESSAGES } from "./config/constants.js";
3
+ import { CLIENT_CONFIG, API_CONFIG, CONFIG_KEYS, ERROR_MESSAGES, SCHEMA_DESCRIPTIONS } from "./config/constants.js";
4
4
  import { ApiClient } from "./http/api-client.js";
5
5
  import { ResolverRegistry } from "./resolver/resolver-registry.js";
6
6
  const ConfigurationSchema = zod__default.object({
@@ -907,7 +907,10 @@ class SwaggerAPI {
907
907
  owner: params.owner,
908
908
  apiName: params.apiName
909
909
  });
910
- return this.saveApiDefinition(params, exists ? {} : { isPrivate: true });
910
+ return this.saveApiDefinition(params, {
911
+ ...exists ? {} : { isPrivate: true },
912
+ version: params.version ?? void 0
913
+ });
911
914
  }
912
915
  /**
913
916
  * Check whether an API (any version) already exists for the given owner/name.
@@ -997,6 +1000,7 @@ class SwaggerAPI {
997
1000
  const searchParams = new URLSearchParams();
998
1001
  const specType = params.specType ?? "openapi30x";
999
1002
  searchParams.append("specType", specType);
1003
+ if (params.version) searchParams.append("version", params.version);
1000
1004
  searchParams.append("createOnly", "true");
1001
1005
  const url = `${this.config.registryBasePath}/apis/${encodeURIComponent(
1002
1006
  params.owner
@@ -32,7 +32,10 @@ const CreateApiParamsSchema = z.object({
32
32
  owner: z.string().describe("Organization name (owner of the API)"),
33
33
  apiName: z.string().describe("API name"),
34
34
  definition: z.string().describe(
35
- "API definition content (OpenAPI/AsyncAPI specification in JSON or YAML format). Format is automatically detected. On create, fixed values are used: version 1.0.0, private visibility, automock disabled, and no project assignment. On update, the API's existing visibility is preserved."
35
+ "API definition content (OpenAPI/AsyncAPI specification in JSON or YAML format). Format is automatically detected. On create, private visibility, automock disabled, and no project assignment are always used. On update, the API's existing visibility is preserved. The version is taken from the version parameter if provided, otherwise from this definition's info.version field — include a non-empty info.version if you omit the version parameter, or the request fails."
36
+ ),
37
+ version: z.string().nullish().describe(
38
+ "API version to create or update (e.g. '1.0.0'). If omitted, the version is taken from the definition's info.version field, which must then be a non-empty value or the request fails with a 400 error."
36
39
  )
37
40
  });
38
41
  const ScanStandardizationParamsSchema = z.object({
@@ -84,6 +87,9 @@ const CreateApiFromPromptParamsSchema = z.object({
84
87
  "asyncapi30x"
85
88
  ]).default("openapi30x").describe(
86
89
  "Specification type for the generated API definition. Use: 'openapi20' for OpenAPI 2.0, 'openapi30x' for OpenAPI 3.0.x (default), 'openapi31x' for OpenAPI 3.1.x, 'asyncapi2xx' for AsyncAPI 2.x, 'asyncapi30x' for AsyncAPI 3.0.x"
90
+ ),
91
+ version: z.string().nullish().describe(
92
+ "API version to save the AI-generated definition as (e.g. '1.0.0'). If omitted, the version is taken from the generated definition's info.version field."
87
93
  )
88
94
  });
89
95
  const StandardizeApiParamsSchema = z.object({
@@ -194,7 +194,7 @@ const TOOLS = [
194
194
  {
195
195
  title: "Create or Update API",
196
196
  toolset: "Registry API",
197
- summary: "Create a new API or update an existing API in SwaggerHub Registry for Swagger Studio. The API specification type (OpenAPI, AsyncAPI) is automatically detected from the definition content. APIs are always created with fixed values: version 1.0.0, private visibility, and automock disabled (these values cannot be changed). Returns HTTP 201 for creation, HTTP 200 for update. Response includes 'operation' field indicating whether it was a 'create' or 'update' operation along with API details and SwaggerHub URL.",
197
+ summary: "Create a new API or update an existing API in SwaggerHub Registry for Swagger Studio. The API specification type (OpenAPI, AsyncAPI) is automatically detected from the definition content. On create, private visibility and automock disabled are always used and cannot be changed via this tool. The version is taken from 'version' if provided, otherwise from the definition's info.version field — include a non-empty info.version if you omit 'version', or the request fails with a 400 error. Returns HTTP 201 for creation, HTTP 200 for update. Response includes 'operation' field indicating whether it was a 'create' or 'update' operation along with API details and SwaggerHub URL.",
198
198
  inputSchema: CreateApiParamsSchema,
199
199
  outputSchema: CreateApiOutputSchema,
200
200
  handler: "createOrUpdateApi",
@@ -240,7 +240,7 @@ const TOOLS = [
240
240
  {
241
241
  title: "Create API from Prompt",
242
242
  toolset: "Registry API",
243
- summary: "Generate and save a new API or a new version of an existing API based on a prompt using SmartBear AI. This tool automatically applies organization governance and standardization rules during API generation. The specType parameter determines the format of the generated definition. Use: 'openapi20' for OpenAPI 2.0, 'openapi30x' for OpenAPI 3.0.x, 'openapi31x' for OpenAPI 3.1.x, 'asyncapi2xx' for AsyncAPI 2.x, 'asyncapi30x' for AsyncAPI 3.0.x. Use this tool when creating APIs that comply with governance policies or when generating APIs from natural language descriptions. Use this tool when users ask to create, generate, or design APIs with governance or standardization requirements. Fails with a conflict error if the API version already exists. Returns API details and SwaggerHub URL.",
243
+ summary: "Generate and save a new API or a new version of an existing API based on a prompt using SmartBear AI. This tool automatically applies organization governance and standardization rules during API generation. The specType parameter determines the format of the generated definition. Use: 'openapi20' for OpenAPI 2.0, 'openapi30x' for OpenAPI 3.0.x, 'openapi31x' for OpenAPI 3.1.x, 'asyncapi2xx' for AsyncAPI 2.x, 'asyncapi30x' for AsyncAPI 3.0.x. Optionally provide 'version' to save the generated definition as a specific version — omitting it uses the version from the generated definition's info.version field. Use this tool when creating APIs that comply with governance policies or when generating APIs from natural language descriptions. Use this tool when users ask to create, generate, or design APIs with governance or standardization requirements. Fails with a conflict error if the API version already exists. Returns API details and SwaggerHub URL.",
244
244
  inputSchema: CreateApiFromPromptParamsSchema,
245
245
  outputSchema: CreateApiFromPromptOutputSchema,
246
246
  handler: "createApiFromPrompt",
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { Tool } from "../../../common/tools.js";
3
- import { GetIssueLinkTestCases200Response, GetIssueLinkTestCasesParams } from "../../common/rest-api-schemas.js";
3
+ import { GetIssueLinkTestCasesParams, GetIssueLinkTestCases200Response } from "../../common/rest-api-schemas.js";
4
4
  const UpdatedGetIssueLinkTestCasesResponse = z.strictObject({
5
5
  testCases: GetIssueLinkTestCases200Response
6
6
  });
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { Tool } from "../../../common/tools.js";
3
- import { GetIssueLinkTestCycles200Response, GetIssueLinkTestCyclesParams } from "../../common/rest-api-schemas.js";
3
+ import { GetIssueLinkTestCyclesParams, GetIssueLinkTestCycles200Response } from "../../common/rest-api-schemas.js";
4
4
  const UpdatedGetIssueLinkTestCyclesResponse = z.strictObject({
5
5
  testCycles: GetIssueLinkTestCycles200Response
6
6
  });
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { Tool } from "../../../common/tools.js";
3
- import { GetIssueLinkTestExecutions200Response, GetIssueLinkTestExecutionsParams } from "../../common/rest-api-schemas.js";
3
+ import { GetIssueLinkTestExecutionsParams, GetIssueLinkTestExecutions200Response } from "../../common/rest-api-schemas.js";
4
4
  const UpdatedGetIssueLinkTestExecutionsResponse = z.strictObject({
5
5
  testExecutions: GetIssueLinkTestExecutions200Response
6
6
  });
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { Tool } from "../../../common/tools.js";
3
- import { UpdateTestCaseBody, updateTestCaseBodyOwnerAccountIdRegExp, UpdateTestCaseParams } from "../../common/rest-api-schemas.js";
3
+ import { UpdateTestCaseParams, UpdateTestCaseBody, updateTestCaseBodyOwnerAccountIdRegExp } from "../../common/rest-api-schemas.js";
4
4
  import { deepMerge } from "../../common/utils.js";
5
5
  const UpdateTestCaseBodyToolInput = UpdateTestCaseBody.extend({
6
6
  folder: z.number().min(1).nullish().describe("The ID of the folder to move the test case into."),
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { Tool } from "../../../common/tools.js";
3
- import { UpdateTestCycleBody, updateTestCycleBodyOwnerAccountIdRegExp, UpdateTestCycleParams } from "../../common/rest-api-schemas.js";
3
+ import { UpdateTestCycleParams, UpdateTestCycleBody, updateTestCycleBodyOwnerAccountIdRegExp } from "../../common/rest-api-schemas.js";
4
4
  import { deepMerge } from "../../common/utils.js";
5
5
  const UpdateTestCycleBodyToolInput = UpdateTestCycleBody.extend({
6
6
  folder: z.number().min(1).nullish().describe("The ID of the folder to move the test cycle into."),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smartbear/mcp",
3
- "version": "0.41.3",
3
+ "version": "0.42.0",
4
4
  "engines": {
5
5
  "node": ">=22"
6
6
  },
@@ -53,9 +53,10 @@
53
53
  "bump": "node scripts/bump.js"
54
54
  },
55
55
  "dependencies": {
56
+ "@amplitude/analytics-node": "^1.5.71",
56
57
  "@bugsnag/js": "^8.8.1",
57
- "@modelcontextprotocol/server": "^2.0.0-beta.5",
58
58
  "@modelcontextprotocol/node": "^2.0.0-beta.5",
59
+ "@modelcontextprotocol/server": "^2.0.0-beta.5",
59
60
  "@modelcontextprotocol/server-legacy": "^2.0.0-beta.5",
60
61
  "js-yaml": "^4.2.0",
61
62
  "node-cache": "^5.1.2",