@smartbear/mcp 0.9.0 → 0.11.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.
Files changed (64) hide show
  1. package/README.md +38 -11
  2. package/dist/bugsnag/client/api/index.js +2 -0
  3. package/dist/bugsnag/client/filters.js +0 -6
  4. package/dist/bugsnag/client.js +238 -380
  5. package/dist/bugsnag/input-schemas.js +51 -0
  6. package/dist/collaborator/client.js +377 -0
  7. package/dist/common/cache.js +63 -0
  8. package/dist/common/client-registry.js +128 -0
  9. package/dist/common/register-clients.js +31 -0
  10. package/dist/common/server.js +77 -28
  11. package/dist/common/transport-http.js +377 -0
  12. package/dist/common/transport-stdio.js +43 -0
  13. package/dist/index.js +18 -60
  14. package/dist/pactflow/client/tools.js +4 -4
  15. package/dist/pactflow/client.js +39 -19
  16. package/dist/qmetry/client/auto-resolve.js +22 -0
  17. package/dist/qmetry/client/handlers.js +18 -4
  18. package/dist/qmetry/client/issues.js +98 -1
  19. package/dist/qmetry/client/project.js +18 -1
  20. package/dist/qmetry/client/testcase.js +79 -1
  21. package/dist/qmetry/client/testsuite.js +156 -1
  22. package/dist/qmetry/client/tools/index.js +17 -0
  23. package/dist/qmetry/client/tools/issue-tools.js +545 -0
  24. package/dist/qmetry/client/tools/project-tools.js +348 -0
  25. package/dist/qmetry/client/tools/requirement-tools.js +530 -0
  26. package/dist/qmetry/client/tools/testcase-tools.js +526 -0
  27. package/dist/qmetry/client/tools/testsuite-tools.js +772 -0
  28. package/dist/qmetry/client/tools/types.js +1 -0
  29. package/dist/qmetry/client.js +33 -11
  30. package/dist/qmetry/config/constants.js +14 -0
  31. package/dist/qmetry/config/rest-endpoints.js +10 -0
  32. package/dist/qmetry/types/common.js +287 -2
  33. package/dist/qmetry/types/issues.js +11 -1
  34. package/dist/qmetry/types/project.js +7 -0
  35. package/dist/qmetry/types/testcase.js +6 -0
  36. package/dist/qmetry/types/testsuite.js +19 -1
  37. package/dist/reflect/client.js +10 -4
  38. package/dist/{api-hub → swagger}/client/api.js +190 -2
  39. package/dist/{api-hub → swagger}/client/configuration.js +6 -1
  40. package/dist/swagger/client/index.js +6 -0
  41. package/dist/{api-hub → swagger}/client/portal-types.js +126 -0
  42. package/dist/swagger/client/tools.js +161 -0
  43. package/dist/swagger/client/user-management-types.js +24 -0
  44. package/dist/swagger/client.js +141 -0
  45. package/dist/swagger/config-utils.js +18 -0
  46. package/dist/zephyr/client.js +44 -6
  47. package/dist/zephyr/common/api-client.js +8 -0
  48. package/dist/zephyr/common/rest-api-schemas.js +5174 -0
  49. package/dist/zephyr/tool/priority/get-priorities.js +43 -0
  50. package/dist/zephyr/tool/project/get-project.js +39 -0
  51. package/dist/zephyr/tool/project/get-projects.js +7 -13
  52. package/dist/zephyr/tool/status/get-statuses.js +49 -0
  53. package/dist/zephyr/tool/test-case/get-test-case.js +39 -0
  54. package/dist/zephyr/tool/test-case/get-test-cases.js +64 -0
  55. package/dist/zephyr/tool/test-cycle/get-test-cycle.js +39 -0
  56. package/dist/zephyr/tool/test-cycle/get-test-cycles.js +72 -0
  57. package/dist/zephyr/tool/test-execution/get-test-execution.js +39 -0
  58. package/package.json +2 -2
  59. package/dist/api-hub/client/index.js +0 -5
  60. package/dist/api-hub/client/tools.js +0 -104
  61. package/dist/api-hub/client.js +0 -98
  62. package/dist/qmetry/client/tools.js +0 -1673
  63. package/dist/zephyr/common/types.js +0 -35
  64. /package/dist/{api-hub → swagger}/client/registry-types.js +0 -0
@@ -1,9 +1,11 @@
1
1
  import { McpServer, ResourceTemplate, } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { ZodAny, ZodArray, ZodBoolean, ZodEnum, ZodLiteral, ZodNumber, ZodObject, ZodOptional, ZodString, ZodUnion, } from "zod";
2
+ import { ZodAny, ZodArray, ZodBoolean, ZodDefault, ZodEnum, ZodIntersection, ZodLiteral, ZodNumber, ZodObject, ZodOptional, ZodRecord, ZodString, ZodUnion, } from "zod";
3
3
  import Bugsnag from "../common/bugsnag.js";
4
+ import { CacheService } from "./cache.js";
4
5
  import { MCP_SERVER_NAME, MCP_SERVER_VERSION } from "./info.js";
5
6
  import { ToolError } from "./types.js";
6
7
  export class SmartBearMcpServer extends McpServer {
8
+ cache;
7
9
  constructor() {
8
10
  super({
9
11
  name: MCP_SERVER_NAME,
@@ -18,19 +20,29 @@ export class SmartBearMcpServer extends McpServer {
18
20
  prompts: {}, // Server supports sending prompts to Host
19
21
  },
20
22
  });
23
+ this.cache = new CacheService();
24
+ }
25
+ getCache() {
26
+ return this.cache;
21
27
  }
22
28
  addClient(client) {
23
29
  client.registerTools((params, cb) => {
24
- const toolName = `${client.prefix}_${params.title.replace(/\s+/g, "_").toLowerCase()}`;
30
+ const toolName = `${client.toolPrefix}_${params.title.replace(/\s+/g, "_").toLowerCase()}`;
25
31
  const toolTitle = `${client.name}: ${params.title}`;
26
32
  return super.registerTool(toolName, {
27
33
  title: toolTitle,
28
34
  description: this.getDescription(params),
29
35
  inputSchema: this.getInputSchema(params),
36
+ outputSchema: this.getOutputSchema(params),
30
37
  annotations: this.getAnnotations(toolTitle, params),
31
38
  }, async (args, extra) => {
32
39
  try {
33
- return await cb(args, extra);
40
+ const result = await cb(args, extra);
41
+ if (result) {
42
+ this.validateCallbackResult(result, params);
43
+ this.addStructuredContentAsText(result);
44
+ }
45
+ return result;
34
46
  }
35
47
  catch (e) {
36
48
  // ToolErrors should not be reported to BugSnag
@@ -59,7 +71,7 @@ export class SmartBearMcpServer extends McpServer {
59
71
  });
60
72
  if (client.registerResources) {
61
73
  client.registerResources((name, path, cb) => {
62
- const url = `${client.prefix}://${name}/${path}`;
74
+ const url = `${client.toolPrefix}://${name}/${path}`;
63
75
  return super.registerResource(name, new ResourceTemplate(url, {
64
76
  list: undefined,
65
77
  }), {}, async (url, variables, extra) => {
@@ -82,6 +94,24 @@ export class SmartBearMcpServer extends McpServer {
82
94
  });
83
95
  }
84
96
  }
97
+ validateCallbackResult(result, params) {
98
+ if (result.isError) {
99
+ return;
100
+ }
101
+ if (params.outputSchema && !result.structuredContent) {
102
+ throw new Error(`The result of the tool '${params.title}' must include 'structuredContent'`);
103
+ }
104
+ }
105
+ addStructuredContentAsText(result) {
106
+ if (result.structuredContent && !result.content?.length) {
107
+ result.content = [
108
+ {
109
+ type: "text",
110
+ text: JSON.stringify(result.structuredContent),
111
+ },
112
+ ];
113
+ }
114
+ }
85
115
  getAnnotations(toolTitle, params) {
86
116
  const annotations = {
87
117
  title: toolTitle,
@@ -103,24 +133,28 @@ export class SmartBearMcpServer extends McpServer {
103
133
  args[param.name] = args[param.name].optional();
104
134
  }
105
135
  }
106
- if (params.zodSchema && params.zodSchema instanceof ZodObject) {
107
- for (const key of Object.keys(params.zodSchema.shape)) {
108
- const field = params.zodSchema.shape[key];
109
- args[key] = field;
110
- if (field.description) {
111
- args[key] = args[key].describe(field.description);
112
- }
113
- if (field.isOptional()) {
114
- args[key] = args[key].optional();
115
- }
136
+ return { ...args, ...this.schemaToRawShape(params.inputSchema) };
137
+ }
138
+ schemaToRawShape(schema) {
139
+ if (schema) {
140
+ if (schema instanceof ZodObject) {
141
+ return schema.shape;
142
+ }
143
+ if (schema instanceof ZodIntersection) {
144
+ const leftShape = this.schemaToRawShape(schema._def.left);
145
+ const rightShape = this.schemaToRawShape(schema._def.right);
146
+ return { ...leftShape, ...rightShape };
116
147
  }
117
148
  }
118
- return args;
149
+ return undefined;
150
+ }
151
+ getOutputSchema(params) {
152
+ return this.schemaToRawShape(params.outputSchema);
119
153
  }
120
154
  getDescription(params) {
121
- const { summary, useCases, examples, parameters, zodSchema, hints, outputFormat, } = params;
155
+ const { summary, useCases, examples, parameters, inputSchema, hints, outputDescription, } = params;
122
156
  let description = summary;
123
- // Parameters if available otherwise use zodSchema
157
+ // Parameters if available otherwise use inputSchema
124
158
  if ((parameters ?? []).length > 0) {
125
159
  description += `\n\n**Parameters:**\n${parameters
126
160
  ?.map((p) => `- ${p.name} (${this.getReadableTypeName(p.type)})${p.required ? " *required*" : ""}` +
@@ -129,14 +163,14 @@ export class SmartBearMcpServer extends McpServer {
129
163
  `${p.constraints ? `\n - ${p.constraints.join("\n - ")}` : ""}`)
130
164
  .join("\n")}`;
131
165
  }
132
- if (zodSchema && zodSchema instanceof ZodObject) {
166
+ if (inputSchema && inputSchema instanceof ZodObject) {
133
167
  description += "\n\n**Parameters:**\n";
134
- description += Object.keys(zodSchema.shape)
135
- .map((key) => this.formatParameterDescription(key, zodSchema.shape[key]))
168
+ description += Object.keys(inputSchema.shape)
169
+ .map((key) => this.formatParameterDescription(key, inputSchema.shape[key]))
136
170
  .join("\n");
137
171
  }
138
- if (outputFormat) {
139
- description += `\n\n**Output Format:** ${outputFormat}`;
172
+ if (outputDescription) {
173
+ description += `\n\n**Output Description:** ${outputDescription}`;
140
174
  }
141
175
  // Use Cases
142
176
  if (useCases && useCases.length > 0) {
@@ -156,16 +190,31 @@ export class SmartBearMcpServer extends McpServer {
156
190
  }
157
191
  return description.trim();
158
192
  }
159
- formatParameterDescription(key, field) {
193
+ formatParameterDescription(key, field, description = null, isOptional = false, defaultValue = null) {
194
+ description = description ?? (field.description || null);
195
+ if (field instanceof ZodOptional) {
196
+ field = field.unwrap();
197
+ return this.formatParameterDescription(key, field, description, true, defaultValue);
198
+ }
199
+ if (field instanceof ZodDefault) {
200
+ defaultValue = JSON.stringify(field._def.defaultValue());
201
+ field = field.removeDefault();
202
+ return this.formatParameterDescription(key, field, description, true, defaultValue);
203
+ }
160
204
  return (`- ${key} (${this.getReadableTypeName(field)})` +
161
- `${field.isOptional() ? "" : " *required*"}` +
162
- `${field.description ? `: ${field.description}` : ""}` +
163
- `${key === "examples" && field instanceof ZodEnum ? ` (e.g. ${Object.keys(field.enum).join(", ")})` : ""}` +
164
- `${key === "constraints" && field instanceof ZodEnum ? `\n - ${Object.keys(field.enum).join("\n - ")}` : ""}`);
205
+ `${isOptional ? "" : " *required*"}` +
206
+ `${description ? `: ${description}` : ""}` +
207
+ `${defaultValue ? ` (default: ${defaultValue})` : ""}`);
165
208
  }
166
209
  getReadableTypeName(zodType) {
167
210
  if (zodType instanceof ZodOptional) {
168
- zodType = zodType._def.innerType;
211
+ return this.getReadableTypeName(zodType.unwrap());
212
+ }
213
+ if (zodType instanceof ZodDefault) {
214
+ return this.getReadableTypeName(zodType.removeDefault());
215
+ }
216
+ if (zodType instanceof ZodRecord) {
217
+ return `record<${this.getReadableTypeName(zodType.keySchema)}, ${this.getReadableTypeName(zodType.valueSchema)}>`;
169
218
  }
170
219
  if (zodType instanceof ZodString)
171
220
  return "string";
@@ -0,0 +1,377 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
4
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
5
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
6
+ import { clientRegistry } from "./client-registry.js";
7
+ import { SmartBearMcpServer } from "./server.js";
8
+ /**
9
+ * Run server in HTTP mode with Streamable HTTP transport
10
+ * Supports both SSE (legacy) and StreamableHTTP transports for backwards compatibility
11
+ */
12
+ export async function runHttpMode() {
13
+ const PORT = process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 3000;
14
+ const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(",") || [
15
+ "http://localhost:3000",
16
+ ];
17
+ // Store transports by session ID
18
+ const transports = new Map();
19
+ // Get dynamic list of allowed headers from registered clients
20
+ const allowedAuthHeaders = getHttpHeaders();
21
+ const allowedHeaders = [
22
+ "Content-Type",
23
+ "Authorization",
24
+ "MCP-Session-Id", // Required for StreamableHTTP
25
+ "x-custom-auth-headers", // used by mcp-inspector
26
+ ...allowedAuthHeaders,
27
+ ].join(", ");
28
+ const httpServer = createServer(async (req, res) => {
29
+ // Enable CORS
30
+ const origin = req.headers.origin || "";
31
+ if (allowedOrigins.includes(origin)) {
32
+ res.setHeader("Access-Control-Allow-Origin", origin);
33
+ }
34
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
35
+ res.setHeader("Access-Control-Allow-Headers", allowedHeaders);
36
+ res.setHeader("Access-Control-Expose-Headers", "MCP-Session-Id");
37
+ if (req.method === "OPTIONS") {
38
+ res.writeHead(200);
39
+ res.end();
40
+ return;
41
+ }
42
+ const url = new URL(req.url || "/", `http://${req.headers.host}`);
43
+ // HEALTH CHECK ENDPOINT
44
+ if (req.method === "GET" && url.pathname === "/health") {
45
+ res.writeHead(200, { "Content-Type": "application/json" });
46
+ res.end(JSON.stringify({ status: "ok", timestamp: new Date().toISOString() }));
47
+ return;
48
+ }
49
+ // STREAMABLE HTTP ENDPOINT (modern, preferred)
50
+ if (url.pathname === "/mcp") {
51
+ await handleStreamableHttpRequest(req, res, transports);
52
+ return;
53
+ }
54
+ // LEGACY SSE ENDPOINT (for backwards compatibility)
55
+ if (req.method === "GET" && url.pathname === "/sse") {
56
+ await handleLegacySseRequest(req, res, transports);
57
+ return;
58
+ }
59
+ if (req.method === "POST" && url.pathname === "/message") {
60
+ await handleLegacyMessageRequest(req, res, url, transports);
61
+ return;
62
+ }
63
+ res.writeHead(404, { "Content-Type": "text/plain" });
64
+ res.end("Not found");
65
+ });
66
+ httpServer.listen(PORT, () => {
67
+ console.log(`[MCP HTTP Server] Listening on http://localhost:${PORT}`);
68
+ console.log(`[MCP HTTP Server] Health check: http://localhost:${PORT}/health`);
69
+ console.log(`[MCP HTTP Server] Modern endpoint: http://localhost:${PORT}/mcp (Streamable HTTP)`);
70
+ console.log(`[MCP HTTP Server] Legacy endpoint: http://localhost:${PORT}/sse (SSE)`);
71
+ const headerHelp = getHttpHeadersHelp();
72
+ if (headerHelp.length > 0) {
73
+ console.log(`[MCP HTTP Server] Send configuration headers:\n${headerHelp.join("\n")}`);
74
+ }
75
+ else {
76
+ console.warn(`[MCP HTTP Server] No clients support HTTP header configuration`);
77
+ }
78
+ });
79
+ }
80
+ /**
81
+ * Parse request body for POST requests
82
+ * Reads the request stream and parses it as JSON
83
+ * @returns Parsed JSON object or undefined if not a POST request or parsing fails
84
+ */
85
+ async function parseRequestBody(req) {
86
+ if (req.method !== "POST") {
87
+ return undefined;
88
+ }
89
+ let body = "";
90
+ req.on("data", (chunk) => {
91
+ body += chunk.toString();
92
+ });
93
+ return new Promise((resolve) => {
94
+ req.on("end", () => {
95
+ try {
96
+ resolve(JSON.parse(body));
97
+ }
98
+ catch (error) {
99
+ console.error("Error parsing request body:", error);
100
+ resolve(undefined);
101
+ }
102
+ });
103
+ });
104
+ }
105
+ /**
106
+ * Get existing transport for session or return error response
107
+ * Validates that the session exists and uses StreamableHTTP transport
108
+ * @returns StreamableHTTPServerTransport if valid, null otherwise (with error response sent)
109
+ */
110
+ function getExistingTransport(sessionId, transports, res) {
111
+ const existing = transports.get(sessionId);
112
+ if (existing && existing.transport instanceof StreamableHTTPServerTransport) {
113
+ return existing.transport;
114
+ }
115
+ // Session doesn't exist or is using a different transport (e.g., SSE)
116
+ res.writeHead(400, { "Content-Type": "application/json" });
117
+ res.end(JSON.stringify({
118
+ jsonrpc: "2.0",
119
+ error: {
120
+ code: -32000,
121
+ message: "Bad Request: Session exists but uses a different transport protocol",
122
+ },
123
+ id: null,
124
+ }));
125
+ return null;
126
+ }
127
+ /**
128
+ * Create new transport for initialize request
129
+ * Sets up a new MCP server instance with configuration from HTTP headers,
130
+ * creates a StreamableHTTP transport, and registers session lifecycle handlers
131
+ * @returns StreamableHTTPServerTransport if successful, null if server initialization fails
132
+ */
133
+ async function createNewTransport(req, res, transports) {
134
+ // Create and configure server with headers from the request
135
+ const server = await newServer(req, res);
136
+ if (!server) {
137
+ return null;
138
+ }
139
+ // Create transport with session management
140
+ const transport = new StreamableHTTPServerTransport({
141
+ sessionIdGenerator: () => randomUUID(),
142
+ onsessioninitialized: (newSessionId) => {
143
+ console.log(`[MCP] New session initialized: ${newSessionId}`);
144
+ // Store session so subsequent requests can find it
145
+ transports.set(newSessionId, { server, transport });
146
+ },
147
+ });
148
+ // Clean up session on close
149
+ transport.onclose = () => {
150
+ if (transport.sessionId) {
151
+ console.log(`[MCP] Session closed: ${transport.sessionId}`);
152
+ transports.delete(transport.sessionId);
153
+ }
154
+ };
155
+ // Connect server to transport to start handling messages
156
+ await server.connect(transport);
157
+ return transport;
158
+ }
159
+ /**
160
+ * Handle modern Streamable HTTP requests
161
+ * This is the main endpoint (/mcp) for the modern MCP StreamableHTTP transport.
162
+ *
163
+ * Request flow:
164
+ * 1. First request (initialize): No session ID, body contains initialize request
165
+ * - Creates new server + transport, generates session ID
166
+ * 2. Subsequent requests: Include MCP-Session-Id header
167
+ * - Routes to existing transport for the session
168
+ */
169
+ async function handleStreamableHttpRequest(req, res, transports) {
170
+ try {
171
+ const sessionId = req.headers["mcp-session-id"];
172
+ const parsedBody = await parseRequestBody(req);
173
+ let transport;
174
+ // Case 1: Existing session - route to existing transport
175
+ if (sessionId && transports.has(sessionId)) {
176
+ const existingTransport = getExistingTransport(sessionId, transports, res);
177
+ if (!existingTransport)
178
+ return;
179
+ transport = existingTransport;
180
+ }
181
+ // Case 2: New session - must be an initialize request
182
+ else if (!sessionId &&
183
+ req.method === "POST" &&
184
+ parsedBody &&
185
+ isInitializeRequest(parsedBody)) {
186
+ const newTransport = await createNewTransport(req, res, transports);
187
+ if (!newTransport)
188
+ return;
189
+ transport = newTransport;
190
+ }
191
+ // Case 3: Invalid request
192
+ else {
193
+ res.writeHead(400, { "Content-Type": "application/json" });
194
+ res.end(JSON.stringify({
195
+ jsonrpc: "2.0",
196
+ error: {
197
+ code: -32000,
198
+ message: "Bad Request: Invalid request",
199
+ },
200
+ id: null,
201
+ }));
202
+ return;
203
+ }
204
+ // Delegate to transport to handle the MCP protocol message
205
+ await transport.handleRequest(req, res, parsedBody);
206
+ }
207
+ catch (error) {
208
+ console.error("Error handling StreamableHTTP request:", error);
209
+ res.writeHead(500, { "Content-Type": "text/plain" });
210
+ res.end("Internal server error");
211
+ }
212
+ }
213
+ /**
214
+ * Handle legacy SSE connection requests (GET /sse)
215
+ *
216
+ * SSE (Server-Sent Events) transport maintains a long-lived connection
217
+ * for server-to-client messages, with a separate POST endpoint for client-to-server.
218
+ *
219
+ * This is kept for backwards compatibility with older MCP clients.
220
+ * New integrations should use the modern StreamableHTTP transport (/mcp).
221
+ */
222
+ async function handleLegacySseRequest(req, res, transports) {
223
+ // Create a new server instance for this connection
224
+ const server = await newServer(req, res);
225
+ if (!server) {
226
+ return;
227
+ }
228
+ // SSE transport keeps the connection open and sends events to the client
229
+ const transport = new SSEServerTransport("/message", res);
230
+ // Store the session so POST /message requests can find it
231
+ transports.set(transport.sessionId, { server, transport });
232
+ // Clean up session when connection closes
233
+ res.on("close", () => {
234
+ transports.delete(transport.sessionId);
235
+ });
236
+ // Connect server to transport (this also starts the transport automatically)
237
+ await server.connect(transport);
238
+ }
239
+ /**
240
+ * Handle legacy POST message requests (POST /message?sessionId=xxx)
241
+ *
242
+ * This endpoint is part of the legacy SSE transport, handling client-to-server messages.
243
+ * The SSE transport uses:
244
+ * - GET /sse: Server-to-client events (long-lived connection)
245
+ * - POST /message: Client-to-server messages (individual requests)
246
+ *
247
+ * New integrations should use the modern StreamableHTTP transport (/mcp).
248
+ */
249
+ async function handleLegacyMessageRequest(req, res, url, transports) {
250
+ // Extract session ID from query parameter
251
+ const sessionId = url.searchParams.get("sessionId");
252
+ if (!sessionId) {
253
+ res.writeHead(400, { "Content-Type": "text/plain" });
254
+ res.end("Missing sessionId parameter");
255
+ return;
256
+ }
257
+ // Find the session created by the SSE connection
258
+ const session = transports.get(sessionId);
259
+ if (!session) {
260
+ res.writeHead(404, { "Content-Type": "text/plain" });
261
+ res.end("Session not found");
262
+ return;
263
+ }
264
+ // Validate this session is using SSE transport
265
+ if (!(session.transport instanceof SSEServerTransport)) {
266
+ res.writeHead(400, { "Content-Type": "text/plain" });
267
+ res.end("Invalid transport for this endpoint");
268
+ return;
269
+ }
270
+ // Read and parse the request body
271
+ let body = "";
272
+ req.on("data", (chunk) => {
273
+ body += chunk.toString();
274
+ });
275
+ req.on("end", async () => {
276
+ try {
277
+ const parsedBody = JSON.parse(body);
278
+ // Route message to the SSE transport for processing
279
+ await session.transport.handlePostMessage(req, res, parsedBody);
280
+ }
281
+ catch (error) {
282
+ console.error("Error handling POST message:", error);
283
+ res.writeHead(500, { "Content-Type": "text/plain" });
284
+ res.end("Internal server error");
285
+ }
286
+ });
287
+ }
288
+ /**
289
+ * Create a new MCP server instance with configuration from HTTP headers
290
+ *
291
+ * Configuration is read from HTTP headers in the format:
292
+ * {ClientPrefix}-{Field-Name} (e.g., Bugsnag-Auth-Token, Reflect-Api-Token)
293
+ *
294
+ * The ClientRegistry validates the configuration and initializes enabled clients.
295
+ * If configuration fails, an error response is sent and null is returned.
296
+ *
297
+ * @returns SmartBearMcpServer instance if successful, null if configuration fails
298
+ */
299
+ async function newServer(req, res) {
300
+ const server = new SmartBearMcpServer();
301
+ try {
302
+ // Configure server with values from HTTP headers
303
+ await clientRegistry.configure(server, (client, key) => {
304
+ const headerName = getHeaderName(client, key);
305
+ // Check both original case and lower-case headers for compatibility
306
+ // (HTTP headers are case-insensitive, but Node.js lowercases them)
307
+ const value = req.headers[headerName] || req.headers[headerName.toLowerCase()];
308
+ if (typeof value === "string") {
309
+ return value;
310
+ }
311
+ return null;
312
+ });
313
+ }
314
+ catch (error) {
315
+ // Configuration failed - provide helpful error message
316
+ const headerHelp = getHttpHeadersHelp();
317
+ const errorMessage = headerHelp.length > 0
318
+ ? `Configuration error: ${error instanceof Error ? error.message : String(error)}. Please provide valid headers:\n${headerHelp.join("\n")}`
319
+ : "No clients support HTTP header configuration.";
320
+ res.writeHead(401, { "Content-Type": "text/plain" });
321
+ res.end(errorMessage);
322
+ return null;
323
+ }
324
+ return server;
325
+ }
326
+ /**
327
+ * Convert a config key to HTTP header name format
328
+ *
329
+ * Examples:
330
+ * - auth_token -> Auth-Token
331
+ * - project_api_key -> Project-Api-Key
332
+ * - base_url -> Base-Url
333
+ *
334
+ * Combined with configPrefix: Bugsnag-Auth-Token, Reflect-Api-Token, etc.
335
+ *
336
+ * @param client The client instance (provides configPrefix)
337
+ * @param key The config key in snake_case
338
+ * @returns Header name in format: {ConfigPrefix}-{Pascal-Kebab-Case}
339
+ */
340
+ function getHeaderName(client, key) {
341
+ return `${client.configPrefix}-${key
342
+ .split("_")
343
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
344
+ .join("-")}`;
345
+ }
346
+ /**
347
+ * Get all HTTP headers that clients support for authentication
348
+ * Returns a list of header names (in kebab-case) that should be allowed
349
+ */
350
+ function getHttpHeaders() {
351
+ const headers = new Set();
352
+ // Use getAll() to respect MCP_ENABLED_CLIENTS filtering
353
+ for (const entry of clientRegistry.getAll()) {
354
+ for (const configKey of Object.keys(entry.config.shape)) {
355
+ headers.add(getHeaderName(entry, configKey));
356
+ }
357
+ }
358
+ return Array.from(headers).sort((a, b) => a.localeCompare(b));
359
+ }
360
+ /**
361
+ * Get human-readable list of HTTP headers for logging/error messages
362
+ * Organized by client
363
+ */
364
+ function getHttpHeadersHelp() {
365
+ const messages = [];
366
+ for (const entry of clientRegistry.getAll()) {
367
+ messages.push(` - ${entry.name}:`);
368
+ for (const [configKey, requirement] of Object.entries(entry.config.shape)) {
369
+ const headerName = getHeaderName(entry, configKey);
370
+ const requiredTag = requirement.isOptional()
371
+ ? " (optional)"
372
+ : " (required)";
373
+ messages.push(` - ${headerName}${requiredTag}: ${requirement.description}`);
374
+ }
375
+ }
376
+ return messages;
377
+ }
@@ -0,0 +1,43 @@
1
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
2
+ import { clientRegistry } from "./client-registry.js";
3
+ import { SmartBearMcpServer } from "./server.js";
4
+ /**
5
+ * Generate a dynamic error message listing all available clients and their required env vars
6
+ */
7
+ function getNoConfigErrorMessage() {
8
+ const messages = [];
9
+ for (const entry of clientRegistry.getAll()) {
10
+ messages.push(` - ${entry.name}:`);
11
+ for (const [configKey, requirement] of Object.entries(entry.config.shape)) {
12
+ const envVarName = getEnvVarName(entry, configKey);
13
+ const requiredTag = requirement.isOptional()
14
+ ? " (optional)"
15
+ : " (required)";
16
+ messages.push(` - ${envVarName}${requiredTag}: ${requirement.description}`);
17
+ }
18
+ }
19
+ return messages;
20
+ }
21
+ /**
22
+ * Run server in STDIO mode (default)
23
+ */
24
+ export async function runStdioMode() {
25
+ const server = new SmartBearMcpServer();
26
+ // Setup clients from environment variables
27
+ const configuredCount = await clientRegistry.configure(server, (client, key) => {
28
+ const envVarName = getEnvVarName(client, key);
29
+ return process.env[envVarName] || null;
30
+ });
31
+ if (configuredCount === 0) {
32
+ const errorMessage = getNoConfigErrorMessage();
33
+ console.error(errorMessage.length > 0
34
+ ? `No clients configured. Please provide valid environment variables for at least one client:\n${errorMessage.join("\n")}`
35
+ : "No clients support environment variable configuration.");
36
+ process.exit(1);
37
+ }
38
+ const transport = new StdioServerTransport();
39
+ await server.connect(transport);
40
+ }
41
+ function getEnvVarName(client, key) {
42
+ return `${client.configPrefix.toUpperCase().replace(/-/g, "_")}_${key.toUpperCase()}`;
43
+ }