@smartbear/mcp 0.41.0 → 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.0";
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({
@@ -224,7 +224,7 @@ const TOOL_NAMES = {
224
224
  /** Create Test Cycle tool */
225
225
  CREATE_TEST_CYCLE: {
226
226
  TITLE: "Create Test Cycle",
227
- SUMMARY: "Create a new test cycle in a QTM4J project. Supports auto-resolving human-readable names for priority and status. Always creates in the 'MCP Generated' folder. projectId is injected automatically from the active project context."
227
+ SUMMARY: "Create a new test cycle in a QTM4J project. Supports auto-resolving human-readable names for priority and status. projectId is injected automatically from the active project context."
228
228
  },
229
229
  /** Update Test Cycle tool */
230
230
  UPDATE_TEST_CYCLE: {
@@ -411,6 +411,10 @@ const SORT_DEFAULTS = {
411
411
  /** Default sort expression for test cycle search */
412
412
  TEST_CYCLES: "key:asc"
413
413
  };
414
+ const DEFAULT_FOLDER_NAMES = {
415
+ /** Default folder name used when no folderId is supplied by the user */
416
+ MCP_GENERATED: "MCP Generated"
417
+ };
414
418
  const EMPTY_VALUES = {
415
419
  /** Empty object */
416
420
  OBJECT: {},
@@ -426,6 +430,7 @@ export {
426
430
  CLIENT_CONFIG,
427
431
  CONFIG_KEYS,
428
432
  CONTENT_TYPES,
433
+ DEFAULT_FOLDER_NAMES,
429
434
  EMPTY_VALUES,
430
435
  ENDPOINTS,
431
436
  ERROR_MESSAGES,
@@ -19,8 +19,8 @@ const SearchTestCaseFilter = zod.object({
19
19
  components: zod.array(zod.string()).optional().describe(
20
20
  "Component names to include (OR logic within array). Example: ['UI', 'Cloud', 'API']. Use exact component names as configured in the project."
21
21
  ),
22
- folders: zod.array(zod.number()).optional().describe(
23
- "Folder IDs (numeric, OR logic within array). Example: [123, 456]. Retrieve folder IDs from the project's folder structure."
22
+ folderId: zod.number().int().positive().optional().describe(
23
+ "Numeric folder ID to filter test cases by. Right-click the target folder in QTM4J and select 'Copy Folder Id' to get this value."
24
24
  ),
25
25
  assignee: zod.array(zod.string()).optional().describe(
26
26
  "Jira account IDs of assignees (OR logic within array). Example: ['712020:ddc8e24b-2de7-404b-b9ed-3d7b241e2ced']. Multiple IDs match test cases assigned to any of them."
@@ -11,7 +11,9 @@ const TestStepSchema = zod.object({
11
11
  const CreateTestCaseBody = zod.object({
12
12
  summary: zod.string().describe("Test case summary/title"),
13
13
  description: zod.string().optional().describe("Test case description"),
14
- folderId: zod.number().optional().describe("Folder ID to place the test case in"),
14
+ folderId: zod.number().int().positive().optional().describe(
15
+ "Numeric folder ID where the test case will be created. If omitted, the test case is created in the 'MCP Generated' folder automatically."
16
+ ),
15
17
  priority: zod.string().optional().describe(
16
18
  "Priority name (e.g., 'High', 'Medium', 'Low'). Auto-resolved to ID."
17
19
  ),
@@ -10,6 +10,9 @@ const CreateTestCycleBody = zod.object({
10
10
  status: zod.string().optional().describe(
11
11
  "Status name (e.g., 'To Do', 'In Progress', 'Done'). Auto-resolved to ID."
12
12
  ),
13
+ folderId: zod.number().int().positive().optional().describe(
14
+ "Numeric folder ID where the test cycle will be created. If omitted, the cycle is created in the 'MCP Generated' folder automatically."
15
+ ),
13
16
  assignee: zod.string().optional().describe("Assignee account ID"),
14
17
  reporter: zod.string().optional().describe("Reporter account ID"),
15
18
  labels: zod.array(zod.string()).optional().describe(
@@ -1,6 +1,6 @@
1
1
  import { Tool } from "../../../common/tools.js";
2
- import { TOOL_NAMES, TOOLSETS, ENDPOINTS } from "../../config/constants.js";
3
- import { ResolverKeys, InputField } from "../../config/field-resolution.types.js";
2
+ import { TOOL_NAMES, TOOLSETS, DEFAULT_FOLDER_NAMES, ENDPOINTS } from "../../config/constants.js";
3
+ import { InputField, ResolverKeys } from "../../config/field-resolution.types.js";
4
4
  import { CreateTestCaseResponse, CreateTestCaseBody } from "../../schema/test-case.schema.js";
5
5
  const FIELD_CONFIG = {
6
6
  [InputField.PRIORITY]: ResolverKeys.CommonAttribute.PRIORITY,
@@ -82,7 +82,7 @@ class CreateTestCase extends Tool {
82
82
  "If priority or status name is not found, the operation proceeds without that field and a warning is returned.",
83
83
  "Labels and components are resolved on demand. If a name is not found, it is skipped with a warning.",
84
84
  "Steps: ALWAYS include all three fields — stepDetails, testData, and expectedResult. Generate reasonable values if not provided.",
85
- "folderId is optional. assignee and reporter accept Jira account IDs."
85
+ "FOLDER ID: folderId is optional. If omitted, defaults to the 'MCP Generated' folder. To place in a specific folder, ask the user to right-click the target folder in QTM4J and select 'Copy Folder Id' — never try to look it up."
86
86
  ],
87
87
  outputDescription: "JSON object with test case ID, key, version number, and summary. Warnings included if any fields were skipped."
88
88
  };
@@ -90,14 +90,20 @@ class CreateTestCase extends Tool {
90
90
  handle = async (rawArgs) => {
91
91
  const fieldResolver = this.client.getResolverRegistry();
92
92
  const context = fieldResolver.requireProjectContext();
93
+ const parsed = CreateTestCaseBody.parse(rawArgs);
93
94
  const body = {
94
- ...CreateTestCaseBody.parse(rawArgs),
95
- projectId: String(context.projectId),
96
- folderId: "MCP Generated"
95
+ ...parsed,
96
+ projectId: String(context.projectId)
97
97
  };
98
+ const activeFieldConfig = { ...FIELD_CONFIG };
99
+ if (typeof body[InputField.FOLDER] === "number") {
100
+ delete activeFieldConfig[InputField.FOLDER];
101
+ } else {
102
+ body[InputField.FOLDER] = DEFAULT_FOLDER_NAMES.MCP_GENERATED;
103
+ }
98
104
  const warnings = [];
99
105
  await Promise.all(
100
- Object.entries(FIELD_CONFIG).map(
106
+ Object.entries(activeFieldConfig).map(
101
107
  ([inputField, resolverKey]) => fieldResolver.getResolver(resolverKey).resolve(inputField, resolverKey, body, context, warnings)
102
108
  )
103
109
  );
@@ -151,11 +151,11 @@ class GetTestCases extends Tool {
151
151
  description: "Filter by folder and fix version",
152
152
  parameters: {
153
153
  filter: {
154
- folders: [123, 456],
154
+ folderId: 123,
155
155
  fixVersions: [789]
156
156
  }
157
157
  },
158
- expectedOutput: "Test cases in the specified folders and fix versions"
158
+ expectedOutput: "Test cases in the specified folder and fix version"
159
159
  },
160
160
  {
161
161
  description: "Complex filter: multiple criteria combined with multi-field sort",
@@ -1,6 +1,6 @@
1
1
  import { Tool } from "../../../common/tools.js";
2
- import { TOOL_NAMES, TOOLSETS, ENDPOINTS } from "../../config/constants.js";
3
- import { ResolverKeys, InputField } from "../../config/field-resolution.types.js";
2
+ import { TOOL_NAMES, TOOLSETS, DEFAULT_FOLDER_NAMES, ENDPOINTS } from "../../config/constants.js";
3
+ import { InputField, ResolverKeys } from "../../config/field-resolution.types.js";
4
4
  import { CreateTestCycleResponse, CreateTestCycleBody } from "../../schema/test-cycle.schema.js";
5
5
  const FIELD_CONFIG = {
6
6
  [InputField.PRIORITY]: ResolverKeys.CommonAttribute.PRIORITY,
@@ -48,7 +48,7 @@ class CreateTestCycle extends Tool {
48
48
  hints: [
49
49
  "PREREQUISITE: set_project_context must be called before this tool. NEVER auto-select a project.",
50
50
  "If any priority, status, label, or component name cannot be resolved, the cycle is still created but a warning is returned. Suggest the closest available value from the set_project_context response and ask the user to confirm before retrying.",
51
- "All cycles are placed in the 'MCP Generated' folder — do not pass folderId.",
51
+ "FOLDER ID: folderId is optional. If omitted, defaults to the 'MCP Generated' folder. To place in a specific folder, ask the user to right-click the target folder in QTM4J and select 'Copy Folder Id' — never try to look it up.",
52
52
  "Date format: 'dd/MMM/yyyy HH:mm' e.g. '10/May/2026 00:00'. Month must be capitalised. plannedStartDate must be ≤ plannedEndDate."
53
53
  ],
54
54
  outputDescription: "JSON object with the new test cycle's id and key (e.g. 'TRWT-TR-218'). Warnings included if any fields were skipped."
@@ -57,14 +57,20 @@ class CreateTestCycle extends Tool {
57
57
  handle = async (rawArgs) => {
58
58
  const fieldResolver = this.client.getResolverRegistry();
59
59
  const context = fieldResolver.requireProjectContext();
60
+ const parsed = CreateTestCycleBody.parse(rawArgs);
60
61
  const body = {
61
- ...CreateTestCycleBody.parse(rawArgs),
62
- projectId: context.projectId,
63
- folderId: "MCP Generated"
62
+ ...parsed,
63
+ projectId: context.projectId
64
64
  };
65
+ const activeFieldConfig = { ...FIELD_CONFIG };
66
+ if (typeof body[InputField.FOLDER] === "number") {
67
+ delete activeFieldConfig[InputField.FOLDER];
68
+ } else {
69
+ body[InputField.FOLDER] = DEFAULT_FOLDER_NAMES.MCP_GENERATED;
70
+ }
65
71
  const warnings = [];
66
72
  await Promise.all(
67
- Object.entries(FIELD_CONFIG).map(
73
+ Object.entries(activeFieldConfig).map(
68
74
  ([inputField, resolverKey]) => fieldResolver.getResolver(resolverKey).resolve(inputField, resolverKey, body, context, warnings)
69
75
  )
70
76
  );
@@ -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
@@ -1120,6 +1124,84 @@ class SwaggerAPI {
1120
1124
  }
1121
1125
  return results;
1122
1126
  }
1127
+ /**
1128
+ * Validate an API definition using server-side apidom-ls.
1129
+ * Accepts either a raw definition or an existing API identified by owner/apiName/version.
1130
+ * @param params Parameters including definition or registry coordinates
1131
+ * @returns Apidom validation result with findings (line, severity, message)
1132
+ */
1133
+ async validateApi(params) {
1134
+ let definition = params.definition;
1135
+ const coordinates = {
1136
+ owner: params.owner,
1137
+ apiName: params.apiName,
1138
+ version: params.version
1139
+ };
1140
+ const providedCoordinates = Object.keys(coordinates).filter(
1141
+ (key) => coordinates[key]
1142
+ );
1143
+ if (definition && providedCoordinates.length > 0) {
1144
+ throw new ToolError(
1145
+ "Provide either 'definition' or 'owner' + 'apiName' + 'version', not both"
1146
+ );
1147
+ }
1148
+ if (!definition && providedCoordinates.length > 0 && providedCoordinates.length < 3) {
1149
+ const missing = Object.keys(coordinates).filter(
1150
+ (key) => !providedCoordinates.includes(key)
1151
+ );
1152
+ throw new ToolError(
1153
+ `Missing ${missing.map((key) => `'${key}'`).join(", ")} - 'owner', 'apiName' and 'version' are all required to validate an existing API`
1154
+ );
1155
+ }
1156
+ if (!definition && params.owner && params.apiName && params.version) {
1157
+ const fetched = await this.getApiDefinition(
1158
+ {
1159
+ owner: params.owner,
1160
+ api: params.apiName,
1161
+ version: params.version
1162
+ },
1163
+ { accept: "text/plain" }
1164
+ );
1165
+ if (typeof fetched !== "string") {
1166
+ throw new ToolError(
1167
+ `Failed to fetch API definition for ${params.owner}/${params.apiName}/${params.version}`
1168
+ );
1169
+ }
1170
+ definition = fetched;
1171
+ }
1172
+ if (!definition) {
1173
+ throw new ToolError(
1174
+ "Either 'definition' or 'owner' + 'apiName' + 'version' must be provided"
1175
+ );
1176
+ }
1177
+ const searchParams = new URLSearchParams();
1178
+ if (params.maxProblems !== void 0) {
1179
+ searchParams.set("maxProblems", String(params.maxProblems));
1180
+ }
1181
+ if (params.uri) {
1182
+ searchParams.set("uri", params.uri);
1183
+ }
1184
+ const queryString = searchParams.toString();
1185
+ const url = `${this.config.registryBasePath}/specs/validate${queryString ? `?${queryString}` : ""}`;
1186
+ const response = await fetch(url, {
1187
+ method: "POST",
1188
+ headers: {
1189
+ ...this.headers,
1190
+ "Content-Type": "application/json"
1191
+ },
1192
+ body: JSON.stringify({ definition })
1193
+ });
1194
+ if (response.status === 422) {
1195
+ return this.parseResponse(response, {});
1196
+ }
1197
+ if (!response.ok) {
1198
+ const errorText = await response.text().catch(() => "");
1199
+ throw new ToolError(
1200
+ `SwaggerHub Registry API specs/validate failed - status: ${response.status} ${response.statusText}${errorText ? ` - ${errorText}` : ""}`
1201
+ );
1202
+ }
1203
+ return this.handleResponse(response);
1204
+ }
1123
1205
  /**
1124
1206
  * Standardize and fix an API definition using AI
1125
1207
  * @param params Parameters including owner, API name, version, and optional newVersion
@@ -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({
@@ -48,6 +51,28 @@ const ScanApiStandardizationFromRegistryParamsSchema = z.object({
48
51
  apiName: z.string().describe("API name (case-sensitive)"),
49
52
  version: z.string().describe("Version identifier")
50
53
  });
54
+ const ValidateApiParamsSchema = z.object({
55
+ definition: z.string().optional().describe(
56
+ "API definition content (OpenAPI/AsyncAPI in JSON or YAML). Provide this or owner/apiName/version, not both."
57
+ ),
58
+ owner: z.string().optional().describe(
59
+ "API owner (organization or user). Use with apiName and version to fetch an existing API from the registry."
60
+ ),
61
+ apiName: z.string().optional().describe("API name"),
62
+ version: z.string().optional().describe("Version identifier"),
63
+ maxProblems: z.number().int().min(1).max(1e3).optional().describe(
64
+ "Cap on the number of findings returned (default 100, max 1000)"
65
+ ),
66
+ uri: z.string().optional().describe(
67
+ "Optional pseudo-URI hint for the parser (e.g. inmemory://spec.yaml)"
68
+ )
69
+ }).refine(
70
+ (data) => Boolean(data.definition) !== Boolean(data.owner && data.apiName && data.version),
71
+ {
72
+ message: "Provide either 'definition' OR 'owner' + 'apiName' + 'version', not both and not neither.",
73
+ path: ["definition"]
74
+ }
75
+ );
51
76
  const CreateApiFromPromptParamsSchema = z.object({
52
77
  owner: z.string().describe("API owner (organization or user, case-sensitive)"),
53
78
  apiName: z.string().describe("API name"),
@@ -62,6 +87,9 @@ const CreateApiFromPromptParamsSchema = z.object({
62
87
  "asyncapi30x"
63
88
  ]).default("openapi30x").describe(
64
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."
65
93
  )
66
94
  });
67
95
  const StandardizeApiParamsSchema = z.object({
@@ -116,6 +144,32 @@ const StandardizationErrorSchema = z.object({
116
144
  description: z.string().optional(),
117
145
  severity: z.string().optional()
118
146
  });
147
+ const ApidomValidationFindingSchema = z.looseObject({
148
+ line: z.number().describe("Line number where the issue was found (1-based)"),
149
+ column: z.number().optional().describe("Column number where the issue starts (0-based)"),
150
+ severity: z.enum(["error", "warning", "info"]).describe("Severity of the finding"),
151
+ message: z.string().describe("Human-readable validation message"),
152
+ code: z.union([z.number(), z.string()]).optional().describe("Rule or lint code (string or number)"),
153
+ source: z.string().optional().describe("Source of the rule")
154
+ });
155
+ const ApidomValidationOutputSchema = z.looseObject({
156
+ valid: z.boolean().optional().describe("True if the spec has no error findings"),
157
+ recognized: z.boolean().optional().describe("True if the spec was recognized as OpenAPI/AsyncAPI"),
158
+ spec: z.looseObject({
159
+ namespace: z.string().optional().describe("Detected spec namespace"),
160
+ version: z.string().optional().describe("Detected spec version"),
161
+ format: z.string().optional().describe("Detected format (JSON or YAML)"),
162
+ mediaType: z.string().optional().describe("Detected media type")
163
+ }).optional().describe("Detected specification info"),
164
+ findings: z.array(ApidomValidationFindingSchema).optional().describe("List of validation findings"),
165
+ summary: z.looseObject({
166
+ errors: z.number().optional(),
167
+ warnings: z.number().optional(),
168
+ info: z.number().optional(),
169
+ total: z.number().optional(),
170
+ durationMs: z.number().optional()
171
+ }).optional()
172
+ });
119
173
  const ScanOutputSchema = z.looseObject({
120
174
  count: z.number().optional(),
121
175
  countsBySeverity: z.record(z.string(), z.number()).optional(),
@@ -166,6 +220,8 @@ export {
166
220
  ApiDefinitionOutputSchema,
167
221
  ApiDefinitionParamsSchema,
168
222
  ApiSearchParamsSchema,
223
+ ApidomValidationFindingSchema,
224
+ ApidomValidationOutputSchema,
169
225
  CreateApiFromPromptOutputSchema,
170
226
  CreateApiFromPromptParamsSchema,
171
227
  CreateApiOutputSchema,
@@ -180,5 +236,6 @@ export {
180
236
  ScanStandardizationParamsSchema,
181
237
  SearchApisOutputSchema,
182
238
  StandardizeApiParamsSchema,
183
- StandardizeOutputSchema
239
+ StandardizeOutputSchema,
240
+ ValidateApiParamsSchema
184
241
  };
@@ -1,6 +1,6 @@
1
1
  import { FUNCTIONAL_TESTING_TOOLS } from "./functional-testing-tools.js";
2
2
  import { PortalsListOutputSchema, PortalOutputSchema, CreatePortalArgsSchema, PortalArgsSchema, UpdatePortalArgsSchema, ResolvePortalOutputSchema, ResolveOrganizationPortalArgsSchema, ProductsListOutputSchema, ProductOutputSchema, CreateProductArgsSchema, ProductArgsSchema, DeleteProductOutputSchema, UpdateProductArgsSchema, PublishOutputSchema, PublishProductArgsSchema, SectionsListOutputSchema, GetProductSectionsArgsSchema, CreateTocOutputSchema, CreateTableOfContentsArgsSchema, TocListOutputSchema, GetTableOfContentsArgsSchema, DeleteTableOfContentsOutputSchema, DeleteTableOfContentsArgsSchema, CreateDocPageOutputSchema, CreateDocumentationPageArgsSchema, DocumentOutputSchema, GetDocumentArgsSchema, UpdateDocumentArgsSchema } from "./portal-types.js";
3
- import { SearchApisOutputSchema, ApiSearchParamsSchema, ApiDefinitionOutputSchema, ApiDefinitionParamsSchema, CreateApiOutputSchema, CreateApiParamsSchema, ScanOutputSchema, ScanStandardizationParamsSchema, ScanFromRegistryOutputSchema, ScanApiStandardizationFromRegistryParamsSchema, CreateApiFromPromptOutputSchema, CreateApiFromPromptParamsSchema, StandardizeOutputSchema, StandardizeApiParamsSchema, PatchApiOutputSchema, PatchApiParamsSchema } from "./registry-types.js";
3
+ import { SearchApisOutputSchema, ApiSearchParamsSchema, ApiDefinitionOutputSchema, ApiDefinitionParamsSchema, CreateApiOutputSchema, CreateApiParamsSchema, ScanOutputSchema, ScanStandardizationParamsSchema, ScanFromRegistryOutputSchema, ScanApiStandardizationFromRegistryParamsSchema, ApidomValidationOutputSchema, ValidateApiParamsSchema, CreateApiFromPromptOutputSchema, CreateApiFromPromptParamsSchema, StandardizeOutputSchema, StandardizeApiParamsSchema, PatchApiOutputSchema, PatchApiParamsSchema } from "./registry-types.js";
4
4
  import { READ_ONLY, WRITE, WRITE_DESTRUCTIVE } from "./tool-constants.js";
5
5
  import { OrganizationsListOutputSchema, OrganizationsQuerySchema } from "./user-management-types.js";
6
6
  const TOOLS = [
@@ -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",
@@ -228,10 +228,19 @@ const TOOLS = [
228
228
  handler: "scanApiStandardizationFromRegistry",
229
229
  ...READ_ONLY
230
230
  },
231
+ {
232
+ title: "Validate API",
233
+ toolset: "Registry API",
234
+ summary: "Validate an OpenAPI or AsyncAPI definition using server-side apidom-ls. Returns structured diagnostics with line number, severity, and message for each finding. Supports OpenAPI 2.0, 3.0, 3.1, and AsyncAPI. Provide either the raw definition (JSON or YAML) OR an existing API by owner, apiName, and version. Use this tool when the user asks to validate, lint, or check an API spec for structural errors matching the Studio Validation tab.",
235
+ inputSchema: ValidateApiParamsSchema,
236
+ outputSchema: ApidomValidationOutputSchema,
237
+ handler: "validateApi",
238
+ ...READ_ONLY
239
+ },
231
240
  {
232
241
  title: "Create API from Prompt",
233
242
  toolset: "Registry API",
234
- 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.",
235
244
  inputSchema: CreateApiFromPromptParamsSchema,
236
245
  outputSchema: CreateApiFromPromptOutputSchema,
237
246
  handler: "createApiFromPrompt",
@@ -169,6 +169,9 @@ class SwaggerClient {
169
169
  async scanApiStandardizationFromRegistry(args) {
170
170
  return this.getApi().scanApiStandardizationFromRegistry(args);
171
171
  }
172
+ async validateApi(args) {
173
+ return this.getApi().validateApi(args);
174
+ }
172
175
  async standardizeApi(args) {
173
176
  return this.getApi().standardizeApi(args);
174
177
  }
@@ -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.0",
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",