@qcentriq/mcp 0.3.1 → 0.4.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/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
5
+ import { McpServer as McpServer2 } from "@modelcontextprotocol/server";
6
6
 
7
7
  // src/config.ts
8
8
  import { Command } from "commander";
@@ -39,13 +39,19 @@ var logger = {
39
39
  var DEFAULT_BASE_URL = "https://api.qcentriq.com";
40
40
  function loadConfig(argv = process.argv) {
41
41
  const program = new Command();
42
- program.name("qcentriq-mcp").description("QCentriq Model Context Protocol (MCP) Server for automated test discovery and execution").option("-k, --api-key <key>", "QCentriq API key (or QCENTRIQ_API_KEY env var)").option("-u, --base-url <url>", "QCentriq API base URL (or QCENTRIQ_BASE_URL env var)").option("-p, --project-id <id>", "Default QCentriq project UUID (or QCENTRIQ_PROJECT_ID env var)").option("-d, --debug", "Enable debug logging to stderr (or DEBUG/QCENTRIQ_DEBUG env var)").allowUnknownOption(true).parse(argv);
42
+ program.name("qcentriq-mcp").description("QCentriq Model Context Protocol (MCP) Server for automated test discovery and execution").option("-k, --api-key <key>", "QCentriq API key (or QCENTRIQ_API_KEY env var)").option("-u, --base-url <url>", "QCentriq API base URL (or QCENTRIQ_BASE_URL env var)").option("-p, --project-id <id>", "Default QCentriq project UUID (or QCENTRIQ_PROJECT_ID env var)").option("-d, --debug", "Enable debug logging to stderr (or DEBUG/QCENTRIQ_DEBUG env var)").option(
43
+ "--require-upload-confirmation",
44
+ "Refuse uploads when the MCP client cannot show a confirmation prompt (or QCENTRIQ_REQUIRE_UPLOAD_CONFIRMATION=true)"
45
+ ).allowUnknownOption(true).parse(argv);
43
46
  const opts = program.opts();
44
47
  const apiKey = opts.apiKey || process.env.QCENTRIQ_API_KEY || "";
45
48
  const rawBaseUrl = opts.baseUrl || process.env.QCENTRIQ_BASE_URL || DEFAULT_BASE_URL;
46
49
  const baseUrl = rawBaseUrl.replace(/\/+$/, "");
47
50
  const defaultProjectId = opts.projectId || process.env.QCENTRIQ_PROJECT_ID;
48
51
  const debug = Boolean(opts.debug || process.env.DEBUG || process.env.QCENTRIQ_DEBUG);
52
+ const requireUploadConfirmation = Boolean(
53
+ opts.requireUploadConfirmation || isTruthy(process.env.QCENTRIQ_REQUIRE_UPLOAD_CONFIRMATION)
54
+ );
49
55
  if (debug) {
50
56
  setDebugLogging(true);
51
57
  }
@@ -59,9 +65,13 @@ function loadConfig(argv = process.argv) {
59
65
  apiKey,
60
66
  baseUrl,
61
67
  defaultProjectId,
62
- debug
68
+ debug,
69
+ requireUploadConfirmation
63
70
  };
64
71
  }
72
+ function isTruthy(value) {
73
+ return ["1", "true", "yes"].includes((value ?? "").trim().toLowerCase());
74
+ }
65
75
 
66
76
  // src/utils/sanitizer.ts
67
77
  var QCENTRIQ_KEY_REGEX = /qc_[0-9a-fA-F]{30,45}/g;
@@ -96,6 +106,7 @@ function sanitizePayload(value) {
96
106
  }
97
107
 
98
108
  // src/client/api.ts
109
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
99
110
  async function readErrorDetail(res) {
100
111
  let text;
101
112
  try {
@@ -112,164 +123,87 @@ async function readErrorDetail(res) {
112
123
  }
113
124
  }
114
125
  var QCentriqApiClient = class {
115
- config;
116
126
  constructor(config) {
117
127
  this.config = config;
118
128
  }
119
129
  /**
120
- * Make an authenticated HTTP request to the QCentriq backend (/api/v1/mcp-client/...).
130
+ * Authenticated GET against the QCentriq backend (/api/v1/mcp-client/...).
131
+ * Undefined and null params are left out of the query string.
121
132
  */
122
- async request(path5, params = {}) {
123
- const cleanPath = path5.startsWith("/") ? path5 : `/${path5}`;
124
- const url = new URL(`${this.config.baseUrl}/api/v1/mcp-client${cleanPath}`);
133
+ async request(path6, params = {}) {
134
+ const query = new URLSearchParams();
125
135
  for (const [key, value] of Object.entries(params)) {
126
136
  if (value !== void 0 && value !== null) {
127
- url.searchParams.set(key, String(value));
128
- }
129
- }
130
- logger.debug(`[mcp-client] HTTP GET ${url.toString()}`);
131
- const res = await fetch(url.toString(), {
132
- method: "GET",
133
- headers: {
134
- Authorization: `Bearer ${this.config.apiKey}`,
135
- Accept: "application/json"
137
+ query.set(key, String(value));
136
138
  }
137
- });
138
- if (!res.ok) {
139
- throw new Error(`API error (${res.status}): ${await readErrorDetail(res)}`);
140
139
  }
141
- const data = await res.json();
142
- return sanitizePayload(data);
140
+ return this.call("GET", path6, query);
143
141
  }
144
- /**
145
- * Make an authenticated write request to the QCentriq backend.
146
- *
147
- * Separate from `request`, which is GET-only: a write must never be retried
148
- * or cached the way a read can be.
149
- */
150
- async send(method, path5, body) {
151
- const cleanPath = path5.startsWith("/") ? path5 : `/${path5}`;
152
- const url = `${this.config.baseUrl}/api/v1/mcp-client${cleanPath}`;
142
+ /** Authenticated JSON write against the QCentriq backend. */
143
+ async send(method, path6, body) {
144
+ return this.call(method, path6, void 0, body);
145
+ }
146
+ async call(method, path6, query, body) {
147
+ const cleanPath = path6.startsWith("/") ? path6 : `/${path6}`;
148
+ const qs = query?.toString();
149
+ const url = `${this.config.baseUrl}/api/v1/mcp-client${cleanPath}${qs ? `?${qs}` : ""}`;
153
150
  logger.debug(`[mcp-client] HTTP ${method} ${url}`);
154
- const res = await fetch(url, {
155
- method,
156
- headers: {
157
- Authorization: `Bearer ${this.config.apiKey}`,
158
- Accept: "application/json",
159
- "Content-Type": "application/json"
160
- },
161
- body: JSON.stringify(body)
151
+ const headers = {
152
+ Authorization: `Bearer ${this.config.apiKey}`,
153
+ Accept: "application/json"
154
+ };
155
+ if (body) headers["Content-Type"] = "application/json";
156
+ const res = await this.fetchWithTimeout(method, cleanPath, url, {
157
+ headers,
158
+ body: body ? JSON.stringify(body) : void 0
162
159
  });
163
160
  if (!res.ok) {
164
161
  throw new Error(`API error (${res.status}): ${await readErrorDetail(res)}`);
165
162
  }
166
- const data = await res.json();
167
- return sanitizePayload(data);
163
+ return sanitizePayload(await res.json());
168
164
  }
169
165
  /**
170
- * Invoke remote tool via /api/v1/mcp-client REST endpoints and wrap
171
- * response in standard MCP CallToolResult format.
166
+ * Issue a request that is aborted after the configured timeout, reporting
167
+ * the timeout as such rather than as a bare AbortError.
172
168
  */
173
- async callRemoteTool(toolName, args) {
174
- logger.debug(`Invoking remote tool "${toolName}" with arguments:`, args);
175
- let data;
176
- switch (toolName) {
177
- case "qcentriq_list_tests": {
178
- const { project_id, group_id, priority, test_type, status, limit, offset } = args;
179
- data = await this.request("/tests", {
180
- project_id,
181
- group_id,
182
- priority,
183
- test_type,
184
- status,
185
- limit,
186
- offset
187
- });
188
- break;
189
- }
190
- case "qcentriq_get_test": {
191
- const { test_case_id, project_id } = args;
192
- data = await this.request(`/tests/${test_case_id}`, { project_id });
193
- break;
194
- }
195
- case "qcentriq_get_test_groups": {
196
- const { project_id, group_id, limit, offset } = args;
197
- data = await this.request("/groups", {
198
- project_id,
199
- group_id,
200
- limit,
201
- offset
202
- });
203
- break;
204
- }
205
- case "qcentriq_download_script": {
206
- const { group_id, project_id, include_fixtures } = args;
207
- data = await this.request(`/groups/${group_id}/script`, {
208
- project_id,
209
- include_fixtures
210
- });
211
- break;
212
- }
213
- case "qcentriq_get_environment": {
214
- const { project_id, environment_id, environment_name } = args;
215
- data = await this.request("/environment", {
216
- project_id,
217
- environment_id,
218
- environment_name
219
- });
220
- break;
221
- }
222
- case "qcentriq_get_test_run_logs": {
223
- const {
224
- test_case_id,
225
- project_id,
226
- run_id,
227
- status,
228
- latest_only,
229
- from_date,
230
- to_date,
231
- limit,
232
- offset
233
- } = args;
234
- data = await this.request(`/tests/${test_case_id}/run-logs`, {
235
- project_id,
236
- run_id,
237
- status,
238
- latest_only,
239
- from_date,
240
- to_date,
241
- limit,
242
- offset
243
- });
244
- break;
169
+ async fetchWithTimeout(method, path6, url, init) {
170
+ const timeoutMs = this.config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
171
+ try {
172
+ return await fetch(url, { ...init, method, signal: AbortSignal.timeout(timeoutMs) });
173
+ } catch (err) {
174
+ if (err?.name === "TimeoutError") {
175
+ throw new Error(`${method} ${path6} timed out after ${timeoutMs}ms`);
245
176
  }
246
- default:
247
- throw new Error(`Unknown tool: ${toolName}`);
177
+ throw err;
248
178
  }
249
- return {
250
- content: [
251
- {
252
- type: "text",
253
- text: JSON.stringify(data, null, 2)
254
- }
255
- ]
256
- };
257
- }
258
- /**
259
- * Close client session on shutdown (no-op for stateless HTTP client).
260
- */
261
- async close() {
262
179
  }
263
180
  };
264
181
 
265
182
  // src/tools/list-tests.ts
266
183
  import { z } from "zod";
184
+
185
+ // src/tools/results.ts
186
+ function jsonResult(data) {
187
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
188
+ }
189
+ function errorResult(text) {
190
+ return { isError: true, content: [{ type: "text", text }] };
191
+ }
192
+ async function backendCall(tool, run) {
193
+ try {
194
+ return jsonResult(await run());
195
+ } catch (err) {
196
+ return errorResult(`Error in ${tool}: ${err.message}`);
197
+ }
198
+ }
199
+
200
+ // src/tools/list-tests.ts
267
201
  function registerListTestsTool(server, client, config) {
268
202
  server.registerTool(
269
203
  "qcentriq_list_tests",
270
204
  {
271
205
  description: "Discover and list automated test cases and test groups for a project with status, priority, and update dates. Test group script availability is indicated in test_groups. Blocked test cases have no script.",
272
- inputSchema: {
206
+ inputSchema: z.object({
273
207
  project_id: z.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
274
208
  group_id: z.uuid().optional().describe("Optional test group UUID filter."),
275
209
  priority: z.enum(["low", "medium", "high", "critical"]).optional().describe("Filter by priority."),
@@ -277,23 +211,12 @@ function registerListTestsTool(server, client, config) {
277
211
  status: z.enum(["failed", "passed", "error", "never_run", "blocked", "active", "flaky"]).optional().describe("Filter by test status (e.g. 'failed' or 'blocked')."),
278
212
  limit: z.number().int().min(1).max(100).default(50).describe("Max number of test cases to return (default 50)."),
279
213
  offset: z.number().int().min(0).default(0).describe("Pagination offset.")
280
- }
214
+ })
281
215
  },
282
- async (args) => {
283
- try {
284
- const projectId = args.project_id || config.defaultProjectId;
285
- const response = await client.callRemoteTool("qcentriq_list_tests", {
286
- ...args,
287
- project_id: projectId
288
- });
289
- return response;
290
- } catch (err) {
291
- return {
292
- isError: true,
293
- content: [{ type: "text", text: `Error in qcentriq_list_tests: ${err.message}` }]
294
- };
295
- }
296
- }
216
+ async (args) => backendCall(
217
+ "qcentriq_list_tests",
218
+ () => client.request("/tests", { ...args, project_id: args.project_id || config.defaultProjectId })
219
+ )
297
220
  );
298
221
  }
299
222
 
@@ -304,26 +227,15 @@ function registerGetTestTool(server, client, config) {
304
227
  "qcentriq_get_test",
305
228
  {
306
229
  description: "Retrieve detailed test case information including step definitions, preconditions, latest execution diagnostics, error stack traces, and parent test group script metadata.",
307
- inputSchema: {
230
+ inputSchema: z2.object({
308
231
  test_case_id: z2.uuid().describe("UUID of the target test case."),
309
232
  project_id: z2.uuid().optional().describe("Optional project UUID (inferred from API key if omitted).")
310
- }
233
+ })
311
234
  },
312
- async (args) => {
313
- try {
314
- const projectId = args.project_id || config.defaultProjectId;
315
- const response = await client.callRemoteTool("qcentriq_get_test", {
316
- ...args,
317
- project_id: projectId
318
- });
319
- return response;
320
- } catch (err) {
321
- return {
322
- isError: true,
323
- content: [{ type: "text", text: `Error in qcentriq_get_test: ${err.message}` }]
324
- };
325
- }
326
- }
235
+ async ({ test_case_id, ...query }) => backendCall(
236
+ "qcentriq_get_test",
237
+ () => client.request(`/tests/${test_case_id}`, { ...query, project_id: query.project_id || config.defaultProjectId })
238
+ )
327
239
  );
328
240
  }
329
241
 
@@ -334,35 +246,22 @@ function registerGetTestGroupsTool(server, client, config) {
334
246
  "qcentriq_get_test_groups",
335
247
  {
336
248
  description: "Discover and inspect test groups for a project. Returns what each group is about (title, description), total/active/blocked test case counts, and whether a test script exists. Provide group_id to inspect member test cases.",
337
- inputSchema: {
249
+ inputSchema: z3.object({
338
250
  project_id: z3.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
339
251
  group_id: z3.uuid().optional().describe("Optional test group UUID filter to inspect a specific group."),
340
252
  limit: z3.number().int().min(1).max(100).default(50).describe("Max test groups to return (default 50)."),
341
253
  offset: z3.number().int().min(0).default(0).describe("Pagination offset.")
342
- }
254
+ })
343
255
  },
344
- async (args) => {
345
- try {
346
- const projectId = args.project_id || config.defaultProjectId;
347
- const response = await client.callRemoteTool("qcentriq_get_test_groups", {
348
- ...args,
349
- project_id: projectId
350
- });
351
- return response;
352
- } catch (err) {
353
- return {
354
- isError: true,
355
- content: [{ type: "text", text: `Error in qcentriq_get_test_groups: ${err.message}` }]
356
- };
357
- }
358
- }
256
+ async (args) => backendCall(
257
+ "qcentriq_get_test_groups",
258
+ () => client.request("/groups", { ...args, project_id: args.project_id || config.defaultProjectId })
259
+ )
359
260
  );
360
261
  }
361
262
 
362
263
  // src/tools/download-script.ts
363
264
  import { z as z5 } from "zod";
364
- import * as fs2 from "fs/promises";
365
- import * as path2 from "path";
366
265
 
367
266
  // src/tools/save-script.ts
368
267
  import { z as z4 } from "zod";
@@ -374,129 +273,86 @@ function registerSaveScriptTool(server) {
374
273
  "qcentriq_save_script",
375
274
  {
376
275
  description: "Save downloaded Playwright Python test script and fixtures directly to the local workspace disk so they can be run or edited locally.",
377
- inputSchema: {
276
+ inputSchema: z4.object({
378
277
  file_name: z4.string().describe("Target filename (e.g. 'test_login.py')."),
379
278
  content: z4.string().describe("Python test script source code."),
380
279
  conftest_content: z4.string().optional().describe("Accompanying conftest.py source code if present."),
381
280
  destination_dir: z4.string().default(DEFAULT_SCRIPT_DIR).describe(`Destination directory in the local workspace (default '${DEFAULT_SCRIPT_DIR}'). Kept separate from a project's own ./tests so an existing conftest.py is never overwritten.`)
382
- }
281
+ })
383
282
  },
384
283
  async (args) => {
385
284
  try {
386
- const targetDir = path.resolve(process.cwd(), args.destination_dir ?? DEFAULT_SCRIPT_DIR);
387
- await fs.mkdir(targetDir, { recursive: true });
388
- const savedFiles = [];
389
- const safeFileName = path.basename(args.file_name);
390
- if (!safeFileName || safeFileName === "." || safeFileName === "..") {
391
- throw new Error(`Invalid file name: "${args.file_name}"`);
392
- }
393
- const scriptPath = path.join(targetDir, safeFileName);
394
- if (!path.resolve(scriptPath).startsWith(targetDir)) {
395
- throw new Error(`Path traversal detected for file name: "${args.file_name}"`);
396
- }
397
- await fs.writeFile(scriptPath, args.content, "utf-8");
398
- savedFiles.push(scriptPath);
399
- logger.info(`Saved test script to: ${scriptPath}`);
400
- if (args.conftest_content) {
401
- const conftestPath = path.join(targetDir, "conftest.py");
402
- await fs.writeFile(conftestPath, args.conftest_content, "utf-8");
403
- savedFiles.push(conftestPath);
404
- logger.info(`Saved conftest.py to: ${conftestPath}`);
405
- }
406
- return {
407
- content: [
408
- {
409
- type: "text",
410
- text: JSON.stringify(
411
- {
412
- status: "success",
413
- message: `Successfully saved ${savedFiles.length} file(s) to ${targetDir}`,
414
- saved_files: savedFiles
415
- },
416
- null,
417
- 2
418
- )
419
- }
420
- ]
421
- };
285
+ const savedFiles = await saveScriptFiles(args.destination_dir ?? DEFAULT_SCRIPT_DIR, args.file_name, args.content, args.conftest_content);
286
+ return jsonResult({
287
+ status: "success",
288
+ message: `Successfully saved ${savedFiles.length} file(s) to ${path.dirname(savedFiles[0])}`,
289
+ saved_files: savedFiles
290
+ });
422
291
  } catch (err) {
423
- return {
424
- isError: true,
425
- content: [
426
- {
427
- type: "text",
428
- text: `Failed to save test script to disk: ${err.message}`
429
- }
430
- ]
431
- };
292
+ return errorResult(`Failed to save test script to disk: ${err.message}`);
432
293
  }
433
294
  }
434
295
  );
435
296
  }
297
+ async function saveScriptFiles(destinationDir, fileName, content, conftest) {
298
+ const safeFileName = path.basename(fileName);
299
+ if (!safeFileName || safeFileName === "." || safeFileName === "..") {
300
+ throw new Error(`Invalid file name: "${fileName}"`);
301
+ }
302
+ const targetDir = path.resolve(process.cwd(), destinationDir);
303
+ await fs.mkdir(targetDir, { recursive: true });
304
+ const scriptPath = path.join(targetDir, safeFileName);
305
+ await fs.writeFile(scriptPath, content, "utf-8");
306
+ logger.info(`Saved test script to: ${scriptPath}`);
307
+ const saved = [scriptPath];
308
+ if (conftest) {
309
+ const conftestPath = path.join(targetDir, "conftest.py");
310
+ await fs.writeFile(conftestPath, conftest, "utf-8");
311
+ logger.info(`Saved conftest.py to: ${conftestPath}`);
312
+ saved.push(conftestPath);
313
+ }
314
+ return saved;
315
+ }
436
316
 
437
317
  // src/tools/download-script.ts
438
318
  function registerDownloadScriptTool(server, client, config) {
439
319
  server.registerTool(
440
320
  "qcentriq_download_script",
441
321
  {
442
- description: "Download test group script and accompanying fixture files (e.g. conftest.py) for local test execution and editing. Optionally writes files directly to the local filesystem.",
443
- inputSchema: {
322
+ description: `Download test group script and accompanying fixture files (e.g. conftest.py) for local test execution and editing. By default the files are written to '${DEFAULT_SCRIPT_DIR}', the same directory qcentriq_save_script uses, and their paths are returned in saved_files.`,
323
+ inputSchema: z5.object({
444
324
  group_id: z5.uuid().describe("UUID of the target test group."),
445
325
  project_id: z5.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
446
326
  include_fixtures: z5.boolean().default(true).describe("Whether to retrieve accompanying conftest.py / fixtures (default True)."),
447
- save_to_disk: z5.boolean().default(false).describe("If true, saves the downloaded test script and fixtures directly to the local filesystem."),
327
+ save_to_disk: z5.boolean().default(true).describe("Saves the downloaded test script and fixtures to destination_dir (default True). Set false to only return the content."),
448
328
  destination_dir: z5.string().default(DEFAULT_SCRIPT_DIR).describe(`Destination directory when save_to_disk is true (default '${DEFAULT_SCRIPT_DIR}'). Kept separate from a project's own ./tests so an existing conftest.py is never overwritten.`)
449
- }
329
+ })
450
330
  },
451
331
  async (args) => {
332
+ let data;
452
333
  try {
453
- const projectId = args.project_id || config.defaultProjectId;
454
- const response = await client.callRemoteTool("qcentriq_download_script", {
455
- group_id: args.group_id,
456
- project_id: projectId,
334
+ data = await client.request(`/groups/${args.group_id}/script`, {
335
+ project_id: args.project_id || config.defaultProjectId,
457
336
  include_fixtures: args.include_fixtures
458
337
  });
459
- if (args.save_to_disk && response && response.content) {
460
- try {
461
- const textItem = response.content.find((c) => c.type === "text");
462
- if (textItem && textItem.text) {
463
- const data = JSON.parse(textItem.text);
464
- const targetDir = path2.resolve(process.cwd(), args.destination_dir ?? DEFAULT_SCRIPT_DIR);
465
- await fs2.mkdir(targetDir, { recursive: true });
466
- const savedFiles = [];
467
- if (data.file_name && data.content) {
468
- const safeFileName = path2.basename(data.file_name);
469
- if (!safeFileName || safeFileName === "." || safeFileName === "..") {
470
- throw new Error(`Invalid file name returned: "${data.file_name}"`);
471
- }
472
- const scriptPath = path2.join(targetDir, safeFileName);
473
- if (!path2.resolve(scriptPath).startsWith(targetDir)) {
474
- throw new Error(`Path traversal detected in returned file name: "${data.file_name}"`);
475
- }
476
- await fs2.writeFile(scriptPath, data.content, "utf-8");
477
- savedFiles.push(scriptPath);
478
- logger.info(`Saved test script to: ${scriptPath}`);
479
- }
480
- if (data.conftest_content) {
481
- const conftestPath = path2.join(targetDir, "conftest.py");
482
- await fs2.writeFile(conftestPath, data.conftest_content, "utf-8");
483
- savedFiles.push(conftestPath);
484
- logger.info(`Saved conftest.py to: ${conftestPath}`);
485
- }
486
- if (savedFiles.length > 0) {
487
- data.saved_files = savedFiles;
488
- textItem.text = JSON.stringify(data, null, 2);
489
- }
490
- }
491
- } catch (writeErr) {
492
- logger.warn(`Failed to write downloaded script to disk: ${writeErr.message}`);
493
- }
494
- }
495
- return response;
496
338
  } catch (err) {
339
+ return errorResult(`Error in qcentriq_download_script: ${err.message}`);
340
+ }
341
+ if (!args.save_to_disk || !data?.file_name || !data?.content) return jsonResult(data);
342
+ try {
343
+ data.saved_files = await saveScriptFiles(args.destination_dir, data.file_name, data.content, data.conftest_content);
344
+ return jsonResult(data);
345
+ } catch (writeErr) {
346
+ logger.warn(`Failed to write downloaded script to disk: ${writeErr.message}`);
497
347
  return {
498
348
  isError: true,
499
- content: [{ type: "text", text: `Error in qcentriq_download_script: ${err.message}` }]
349
+ content: [
350
+ {
351
+ type: "text",
352
+ text: `The script was downloaded but could not be saved to "${args.destination_dir}": ${writeErr.message}. The downloaded content follows; save it with qcentriq_save_script.`
353
+ },
354
+ ...jsonResult(data).content
355
+ ]
500
356
  };
501
357
  }
502
358
  }
@@ -510,27 +366,16 @@ function registerEnvironmentTool(server, client, config) {
510
366
  "qcentriq_get_environment",
511
367
  {
512
368
  description: "Retrieve target test environment configuration, base URL (BASE_URL), environment variables, and required secret variable names for local test execution.",
513
- inputSchema: {
369
+ inputSchema: z6.object({
514
370
  project_id: z6.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
515
371
  environment_id: z6.uuid().optional().describe("Optional specific environment UUID."),
516
372
  environment_name: z6.string().optional().describe("Optional environment name filter (e.g. 'staging', 'dev', 'production').")
517
- }
373
+ })
518
374
  },
519
- async (args) => {
520
- try {
521
- const projectId = args.project_id || config.defaultProjectId;
522
- const response = await client.callRemoteTool("qcentriq_get_environment", {
523
- ...args,
524
- project_id: projectId
525
- });
526
- return response;
527
- } catch (err) {
528
- return {
529
- isError: true,
530
- content: [{ type: "text", text: `Error in qcentriq_get_environment: ${err.message}` }]
531
- };
532
- }
533
- }
375
+ async (args) => backendCall(
376
+ "qcentriq_get_environment",
377
+ () => client.request("/environment", { ...args, project_id: args.project_id || config.defaultProjectId })
378
+ )
534
379
  );
535
380
  }
536
381
 
@@ -541,7 +386,7 @@ function registerRunLogsTool(server, client, config) {
541
386
  "qcentriq_get_test_run_logs",
542
387
  {
543
388
  description: "Retrieve execution history and logs for a test case: per-run status, timing, error message, stack trace, and raw output logs across runs.",
544
- inputSchema: {
389
+ inputSchema: z7.object({
545
390
  test_case_id: z7.uuid().describe("UUID of the target test case."),
546
391
  project_id: z7.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
547
392
  run_id: z7.uuid().optional().describe("Optional specific run UUID to fetch a single run's full log."),
@@ -551,33 +396,23 @@ function registerRunLogsTool(server, client, config) {
551
396
  to_date: z7.string().optional().describe("Optional ISO-8601 end date filter."),
552
397
  limit: z7.number().int().min(1).max(100).default(20).describe("Max runs to return."),
553
398
  offset: z7.number().int().min(0).default(0).describe("Pagination offset.")
554
- }
399
+ })
555
400
  },
556
- async (args) => {
557
- try {
558
- const projectId = args.project_id || config.defaultProjectId;
559
- const response = await client.callRemoteTool("qcentriq_get_test_run_logs", {
560
- ...args,
561
- project_id: projectId
562
- });
563
- return response;
564
- } catch (err) {
565
- return {
566
- isError: true,
567
- content: [{ type: "text", text: `Error in qcentriq_get_test_run_logs: ${err.message}` }]
568
- };
569
- }
570
- }
401
+ async ({ test_case_id, ...query }) => backendCall(
402
+ "qcentriq_get_test_run_logs",
403
+ () => client.request(`/tests/${test_case_id}/run-logs`, { ...query, project_id: query.project_id || config.defaultProjectId })
404
+ )
571
405
  );
572
406
  }
573
407
 
574
408
  // src/tools/authoring-guide.ts
409
+ import { z as z8 } from "zod";
575
410
  function registerAuthoringGuideTool(server, client) {
576
411
  server.registerTool(
577
412
  "qcentriq_get_authoring_guide",
578
413
  {
579
414
  description: "Fetch the contract for authoring QCentriq test plans and scripts: the TaskPlan JSON schema, the ${VAR} environment-variable convention, the @allure.id rules a saved script is validated against, and the conftest fixtures a script may use. Call this before writing a plan or a test script \u2014 a script that violates the contract is rejected on save.",
580
- inputSchema: {},
415
+ inputSchema: z8.object({}),
581
416
  annotations: {
582
417
  readOnlyHint: true,
583
418
  destructiveHint: false,
@@ -602,16 +437,97 @@ function registerAuthoringGuideTool(server, client) {
602
437
  }
603
438
 
604
439
  // src/tools/create-plan.ts
605
- import { z as z8 } from "zod";
440
+ import { z as z10 } from "zod";
441
+
442
+ // src/tools/confirm-upload.ts
443
+ import {
444
+ CLIENT_CAPABILITIES_META_KEY,
445
+ inputRequired,
446
+ inputResponse,
447
+ acceptedContent
448
+ } from "@modelcontextprotocol/server";
449
+ import { z as z9 } from "zod";
450
+ var CONFIRM_KEY = "confirm_upload";
451
+ var ConfirmAnswer = z9.object({ confirm: z9.boolean() });
452
+ function confirmUpload(server, ctx, config, action, message) {
453
+ const response = inputResponse(ctx.mcpReq.inputResponses, CONFIRM_KEY);
454
+ if (response.kind === "elicit") {
455
+ const answer = acceptedContent(ctx.mcpReq.inputResponses, CONFIRM_KEY, ConfirmAnswer);
456
+ if (answer?.confirm === true) {
457
+ return { proceed: true };
458
+ }
459
+ return {
460
+ proceed: false,
461
+ result: {
462
+ content: [
463
+ {
464
+ type: "text",
465
+ text: `Upload declined: the user did not confirm ${action}, so nothing was sent to QCentriq. Do not retry unless the user asks you to.`
466
+ }
467
+ ]
468
+ }
469
+ };
470
+ }
471
+ if (supportsFormElicitation(server, ctx)) {
472
+ return {
473
+ proceed: false,
474
+ result: inputRequired({
475
+ inputRequests: {
476
+ [CONFIRM_KEY]: inputRequired.elicit({
477
+ message,
478
+ requestedSchema: {
479
+ type: "object",
480
+ properties: {
481
+ confirm: { type: "boolean", title: "Upload to QCentriq", description: "Tick to upload." }
482
+ },
483
+ required: ["confirm"]
484
+ }
485
+ })
486
+ }
487
+ })
488
+ };
489
+ }
490
+ if (config.requireUploadConfirmation) {
491
+ return {
492
+ proceed: false,
493
+ result: {
494
+ isError: true,
495
+ content: [
496
+ {
497
+ type: "text",
498
+ text: `Upload refused: --require-upload-confirmation is set, but this MCP client cannot show a confirmation prompt, so ${action} was not sent to QCentriq. Use a client that supports elicitation, or remove the flag.`
499
+ }
500
+ ]
501
+ }
502
+ };
503
+ }
504
+ logger.warn(`Client cannot show a confirmation prompt; uploading ${action} without one.`);
505
+ return { proceed: true };
506
+ }
507
+ function plural(count, noun) {
508
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
509
+ }
510
+ function supportsFormElicitation(server, ctx) {
511
+ const elicitation = clientCapabilities(server, ctx)?.elicitation;
512
+ if (!elicitation) return false;
513
+ return Boolean(elicitation.form) || !elicitation.url;
514
+ }
515
+ function clientCapabilities(server, ctx) {
516
+ const envelope = ctx.mcpReq.envelope;
517
+ const fromEnvelope = envelope?.[CLIENT_CAPABILITIES_META_KEY];
518
+ return fromEnvelope ?? server.server.getClientCapabilities();
519
+ }
520
+
521
+ // src/tools/create-plan.ts
606
522
  function registerCreatePlanTool(server, client, config) {
607
523
  server.registerTool(
608
524
  "qcentriq_create_plan",
609
525
  {
610
526
  description: "Create test groups and test cases in QCentriq from a plan you authored. Call qcentriq_get_authoring_guide first \u2014 the plan must match the TaskPlan schema, and any value that exists as a project environment variable must be written as ${VAR_NAME} rather than inlined. Returns one UUID per created test case; each must appear exactly once as @allure.id('<case_id>') in the script you then save with qcentriq_save_group_script. Requires an API key with the 'test:write' scope.",
611
- inputSchema: {
612
- plan: z8.record(z8.string(), z8.any()).describe("The plan object, matching the TaskPlan schema from qcentriq_get_authoring_guide."),
613
- project_id: z8.uuid().optional().describe("Optional project UUID (inferred from the API key if omitted).")
614
- },
527
+ inputSchema: z10.object({
528
+ plan: z10.record(z10.string(), z10.any()).describe("The plan object, matching the TaskPlan schema from qcentriq_get_authoring_guide."),
529
+ project_id: z10.uuid().optional().describe("Optional project UUID (inferred from the API key if omitted).")
530
+ }),
615
531
  annotations: {
616
532
  readOnlyHint: false,
617
533
  destructiveHint: false,
@@ -621,323 +537,83 @@ function registerCreatePlanTool(server, client, config) {
621
537
  openWorldHint: false
622
538
  }
623
539
  },
624
- async (args) => {
625
- try {
626
- const data = await client.send("POST", "/plans", {
627
- plan: args.plan,
628
- project_id: args.project_id || config.defaultProjectId
629
- });
630
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
631
- } catch (err) {
632
- return {
633
- isError: true,
634
- content: [{ type: "text", text: `Error in qcentriq_create_plan: ${err.message}` }]
635
- };
636
- }
540
+ async (args, ctx) => {
541
+ const gate = confirmUpload(server, ctx, config, "this test plan", describePlan(args.plan));
542
+ if (!gate.proceed) return gate.result;
543
+ return backendCall(
544
+ "qcentriq_create_plan",
545
+ () => client.send("POST", "/plans", { plan: args.plan, project_id: args.project_id || config.defaultProjectId })
546
+ );
637
547
  }
638
548
  );
639
549
  }
640
-
641
- // src/tools/save-group-script.ts
642
- import { z as z9 } from "zod";
643
- function registerSaveGroupScriptTool(server, client, config) {
644
- server.registerTool(
645
- "qcentriq_save_group_script",
646
- {
647
- description: "Save a test script you wrote back to QCentriq so the cloud runner executes exactly what you ran locally. The script is validated before it is stored: valid Python, and every test case in the group present exactly once as @allure.id('<case_id>') \u2014 no duplicates, no ids from other groups. A rejection names the offending id or line so you can correct it. Pass expected_updated_at from the last download to turn a concurrent edit into a conflict rather than a lost update. conftest.py cannot be saved; QCentriq provides it. Requires the 'test:write' scope.",
648
- inputSchema: {
649
- group_id: z9.uuid().describe("UUID of the target test group."),
650
- content: z9.string().describe("The Python test script source."),
651
- project_id: z9.uuid().optional().describe("Optional project UUID (inferred from the API key if omitted)."),
652
- filename: z9.string().optional().describe("Optional script filename; derived from the group title if omitted."),
653
- fixtures: z9.array(z9.object({ file_name: z9.string(), content: z9.string() })).optional().describe("Companion files to store next to the script (page objects, test data). conftest.py is rejected."),
654
- expected_updated_at: z9.string().optional().describe("ISO-8601 timestamp from the last download. Supply it to get a conflict instead of silently overwriting someone else's edit.")
655
- },
656
- annotations: {
657
- readOnlyHint: false,
658
- destructiveHint: true,
659
- // Replaces the group's existing script.
660
- idempotentHint: true,
661
- // Saving the same content twice leaves the same state.
662
- openWorldHint: false
663
- }
664
- },
665
- async (args) => {
666
- try {
667
- const { group_id, ...rest } = args;
668
- const data = await client.send("PUT", `/groups/${group_id}/script`, {
669
- ...rest,
670
- project_id: args.project_id || config.defaultProjectId
671
- });
672
- return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
673
- } catch (err) {
674
- return {
675
- isError: true,
676
- content: [{ type: "text", text: `Error in qcentriq_save_group_script: ${err.message}` }]
677
- };
678
- }
679
- }
680
- );
550
+ function describePlan(plan) {
551
+ const tasks = Array.isArray(plan.tasks) ? plan.tasks : [];
552
+ const groups = tasks.map((task, i) => ({
553
+ name: typeof task?.name === "string" && task.name ? task.name : `Group ${i + 1}`,
554
+ cases: Array.isArray(task?.test_cases) ? task.test_cases.length : 0
555
+ }));
556
+ const cases = groups.reduce((sum, g) => sum + g.cases, 0);
557
+ const list = groups.map((g) => `${g.name} (${g.cases})`).join(", ");
558
+ return `Create ${plural(groups.length, "test group")} with ${plural(cases, "test case")} in QCentriq?` + (list ? ` Groups: ${list}.` : "");
681
559
  }
682
560
 
683
- // src/tools/local-run.ts
684
- import { z as z10 } from "zod";
561
+ // src/tools/save-group-script.ts
562
+ import { z as z11 } from "zod";
685
563
 
686
- // src/local/runner.ts
687
- import { spawn } from "child_process";
688
- import * as path3 from "path";
689
- function buildTestEnv(params) {
690
- const env = {
691
- ...process.env,
692
- ...params.envVars || {}
693
- };
694
- if (params.baseUrl) {
695
- env.BASE_URL = params.baseUrl;
696
- }
697
- if (params.browser) {
698
- env.BROWSER = params.browser;
699
- }
700
- if (params.headless !== void 0) {
701
- env.HEADLESS = params.headless ? "true" : "false";
564
+ // src/local/passing-runs.ts
565
+ import { createHash } from "crypto";
566
+ import * as fs2 from "fs/promises";
567
+ import * as path2 from "path";
568
+ var PassingRunLedger = class {
569
+ runs = /* @__PURE__ */ new Map();
570
+ record(content, run) {
571
+ this.runs.set(contentHash(content), run);
702
572
  }
703
- if (params.groupId) {
704
- env.QCAQ_TEST_GROUP_ID = params.groupId;
573
+ find(content) {
574
+ return this.runs.get(contentHash(content));
705
575
  }
706
- return env;
576
+ };
577
+ function contentHash(content) {
578
+ return createHash("sha256").update(content).digest("hex");
707
579
  }
708
- function resolvePytestCommand() {
709
- if (process.env.VIRTUAL_ENV) {
710
- const venvPytest = path3.join(process.env.VIRTUAL_ENV, "bin", "pytest");
711
- return { cmd: venvPytest, baseArgs: [] };
712
- }
713
- return { cmd: "pytest", baseArgs: [] };
580
+ var NARROWING_FLAGS = ["-k", "-m", "--deselect", "--lf", "--last-failed", "--sw", "--stepwise", "--co", "--collect-only", "--setup-only", "--setup-plan", "--fixtures"];
581
+ function coversWholeFile(filePath, testName, extraArgs = []) {
582
+ if (testName || filePath.includes("::")) return false;
583
+ return !extraArgs.some(
584
+ (arg) => NARROWING_FLAGS.some((flag) => arg === flag || arg.startsWith(`${flag}=`) || /^-[a-z]$/.test(flag) && arg.startsWith(flag))
585
+ );
714
586
  }
715
- function killProcessTree(child) {
716
- if (child.pid) {
587
+ function reportsPassedTests(stdout) {
588
+ return /\b[1-9]\d* passed\b/.test(stdout);
589
+ }
590
+ async function fixtureMismatch(run, fixtures) {
591
+ for (const fixture of fixtures) {
592
+ const localPath = path2.resolve(run.dir, fixture.file_name);
593
+ if (path2.dirname(localPath) !== run.dir) {
594
+ return `companion file "${fixture.file_name}" is not a plain file name next to the script`;
595
+ }
596
+ let local;
597
+ let modifiedAt;
717
598
  try {
718
- if (process.platform !== "win32") {
719
- process.kill(-child.pid, "SIGKILL");
720
- return;
721
- }
599
+ [local, modifiedAt] = await Promise.all([fs2.readFile(localPath, "utf-8"), fs2.stat(localPath).then((s) => s.mtimeMs)]);
722
600
  } catch {
601
+ return `companion file "${fixture.file_name}" was not next to the script (${run.dir}) when it passed`;
723
602
  }
724
- }
725
- try {
726
- child.kill("SIGKILL");
727
- } catch {
728
- }
729
- }
730
- async function runLocalPytest(params) {
731
- const startTime = Date.now();
732
- const cwd = params.workingDir ? path3.resolve(params.workingDir) : process.cwd();
733
- const timeoutMs = (params.timeoutSeconds || 60) * 1e3;
734
- const { cmd, baseArgs } = resolvePytestCommand();
735
- const args = [...baseArgs, params.filePath];
736
- if (params.testName) {
737
- args.push("-k", params.testName);
738
- }
739
- if (params.extraArgs && params.extraArgs.length > 0) {
740
- args.push(...params.extraArgs);
741
- }
742
- if (!args.includes("-v") && !args.includes("-vv")) {
743
- args.push("-v");
744
- }
745
- const env = buildTestEnv(params);
746
- const fullCommand = `${cmd} ${args.join(" ")}`;
747
- logger.info(`Running local test command: ${fullCommand} in ${cwd}`);
748
- return new Promise((resolve5) => {
749
- let stdout = "";
750
- let stderr = "";
751
- let finished = false;
752
- const child = spawn(cmd, args, {
753
- cwd,
754
- env,
755
- detached: process.platform !== "win32",
756
- stdio: ["ignore", "pipe", "pipe"]
757
- });
758
- const timer = setTimeout(() => {
759
- if (!finished) {
760
- finished = true;
761
- killProcessTree(child);
762
- resolve5({
763
- passed: false,
764
- exitCode: -1,
765
- stdout,
766
- stderr: stderr + `
767
- [TIMEOUT] Test execution timed out after ${params.timeoutSeconds || 60} seconds.`,
768
- durationMs: Date.now() - startTime,
769
- command: fullCommand
770
- });
771
- }
772
- }, timeoutMs);
773
- child.stdout.on("data", (chunk) => {
774
- stdout += chunk.toString();
775
- });
776
- child.stderr.on("data", (chunk) => {
777
- stderr += chunk.toString();
778
- });
779
- child.on("error", (err) => {
780
- if (finished) return;
781
- finished = true;
782
- clearTimeout(timer);
783
- if (err.code === "ENOENT" && cmd !== "python3") {
784
- logger.warn("pytest binary not found directly, falling back to python3 -m pytest...");
785
- const fallbackChild = spawn("python3", ["-m", "pytest", ...args], {
786
- cwd,
787
- env,
788
- detached: process.platform !== "win32",
789
- stdio: ["ignore", "pipe", "pipe"]
790
- });
791
- let fbStdout = "";
792
- let fbStderr = "";
793
- let fbFinished = false;
794
- const fbTimer = setTimeout(() => {
795
- if (!fbFinished) {
796
- fbFinished = true;
797
- killProcessTree(fallbackChild);
798
- resolve5({
799
- passed: false,
800
- exitCode: -1,
801
- stdout: fbStdout,
802
- stderr: fbStderr + `
803
- [TIMEOUT] Test execution timed out after ${params.timeoutSeconds || 60} seconds.`,
804
- durationMs: Date.now() - startTime,
805
- command: `python3 -m pytest ${args.join(" ")}`
806
- });
807
- }
808
- }, timeoutMs);
809
- fallbackChild.stdout.on("data", (c) => fbStdout += c.toString());
810
- fallbackChild.stderr.on("data", (c) => fbStderr += c.toString());
811
- fallbackChild.on("close", (code) => {
812
- if (fbFinished) return;
813
- fbFinished = true;
814
- clearTimeout(fbTimer);
815
- resolve5({
816
- passed: code === 0,
817
- exitCode: code ?? -1,
818
- stdout: fbStdout,
819
- stderr: fbStderr,
820
- durationMs: Date.now() - startTime,
821
- command: `python3 -m pytest ${args.join(" ")}`
822
- });
823
- });
824
- fallbackChild.on("error", (fbErr) => {
825
- if (fbFinished) return;
826
- fbFinished = true;
827
- clearTimeout(fbTimer);
828
- resolve5({
829
- passed: false,
830
- exitCode: -1,
831
- stdout: "",
832
- stderr: `Failed to execute pytest or python3 -m pytest: ${fbErr.message}. Ensure pytest is installed in your Python environment.`,
833
- durationMs: Date.now() - startTime,
834
- command: fullCommand
835
- });
836
- });
837
- return;
838
- }
839
- resolve5({
840
- passed: false,
841
- exitCode: -1,
842
- stdout,
843
- stderr: `Failed to spawn process: ${err.message}. Ensure pytest is installed in your Python environment.`,
844
- durationMs: Date.now() - startTime,
845
- command: fullCommand
846
- });
847
- });
848
- child.on("close", (code) => {
849
- if (finished) return;
850
- finished = true;
851
- clearTimeout(timer);
852
- const durationMs = Date.now() - startTime;
853
- resolve5({
854
- passed: code === 0,
855
- exitCode: code ?? -1,
856
- stdout,
857
- stderr,
858
- durationMs,
859
- command: fullCommand
860
- });
861
- });
862
- });
863
- }
864
-
865
- // src/tools/local-run.ts
866
- function registerLocalRunTool(server) {
867
- server.registerTool(
868
- "qcentriq_run_local_test",
869
- {
870
- description: "Execute a downloaded Playwright/pytest test script locally in the developer's environment. Runs pytest as a local subprocess and returns stdout, stderr, exit code, and test diagnostics without using QCentriq cloud runners.",
871
- inputSchema: {
872
- file_path: z10.string().describe("Path to the local test file to run (e.g. 'tests/test_login.py')."),
873
- test_name: z10.string().optional().describe("Optional specific test function name or expression to run (passed to pytest -k)."),
874
- headless: z10.boolean().default(true).describe("Whether to run the browser in headless mode (default True). Set False to watch the browser execution live."),
875
- browser: z10.enum(["chromium", "firefox", "webkit"]).default("chromium").describe("Browser engine to execute against (default 'chromium')."),
876
- base_url: z10.url().optional().describe("Target application base URL (e.g. from qcentriq_get_environment). Injected as BASE_URL env var."),
877
- group_id: z10.string().optional().describe("Test group UUID this script belongs to. Injected as QCAQ_TEST_GROUP_ID so the Allure results stay mappable back to the QCentriq group."),
878
- env_vars: z10.record(z10.string(), z10.string()).optional().describe("Environment variables to inject into the local test process."),
879
- extra_args: z10.array(z10.string()).optional().describe("Additional CLI arguments to pass to pytest (e.g. ['-s', '--alluredir=allure-results'])."),
880
- timeout_seconds: z10.number().int().min(5).max(300).default(60).describe("Timeout in seconds for test execution (default 60)."),
881
- working_dir: z10.string().optional().describe("Working directory to run pytest in (defaults to current project directory).")
882
- }
883
- },
884
- async (args) => {
885
- try {
886
- const result = await runLocalPytest({
887
- filePath: args.file_path,
888
- testName: args.test_name,
889
- headless: args.headless,
890
- browser: args.browser,
891
- baseUrl: args.base_url,
892
- groupId: args.group_id,
893
- envVars: args.env_vars,
894
- extraArgs: args.extra_args,
895
- timeoutSeconds: args.timeout_seconds,
896
- workingDir: args.working_dir
897
- });
898
- const statusText = result.passed ? "PASSED" : "FAILED";
899
- const summary = [
900
- `Local Test Run Result: ${statusText} (exit code ${result.exitCode})`,
901
- `Duration: ${(result.durationMs / 1e3).toFixed(2)}s`,
902
- `Command: ${result.command}`,
903
- "",
904
- "--- STDOUT ---",
905
- result.stdout || "(no stdout)",
906
- "",
907
- "--- STDERR ---",
908
- result.stderr || "(no stderr)"
909
- ].join("\n");
910
- return {
911
- content: [
912
- {
913
- type: "text",
914
- text: summary
915
- }
916
- ],
917
- isError: !result.passed
918
- };
919
- } catch (err) {
920
- return {
921
- isError: true,
922
- content: [
923
- {
924
- type: "text",
925
- text: `Error executing local test: ${err.message}`
926
- }
927
- ]
928
- };
929
- }
603
+ if (local !== fixture.content) {
604
+ return `companion file "${fixture.file_name}" differs from ${localPath}, which the passing run used`;
930
605
  }
931
- );
606
+ if (modifiedAt > run.startedAt) {
607
+ return `companion file "${fixture.file_name}" changed after the passing run`;
608
+ }
609
+ }
610
+ return null;
932
611
  }
933
612
 
934
- // src/tools/setup-instructions.ts
935
- import { z as z11 } from "zod";
936
-
937
613
  // src/local/environment-setup.ts
938
- import { spawn as spawn2 } from "child_process";
614
+ import { spawn } from "child_process";
939
615
  import * as fs3 from "fs/promises";
940
- import * as path4 from "path";
616
+ import * as path3 from "path";
941
617
  var MANAGER_PRIORITY = ["uv", "poetry", "conda", "venv"];
942
618
  var PROBE_TIMEOUT_MS = 5e3;
943
619
  var DEFAULT_PYTHON_VERSION = "3.12";
@@ -956,23 +632,23 @@ function testDependencies(playwrightVersion, packages) {
956
632
  return [...base, `playwright==${playwrightVersion}`].join(" ");
957
633
  }
958
634
  function probeCommand(cmd, args) {
959
- return new Promise((resolve5) => {
635
+ return new Promise((resolve6) => {
960
636
  let output = "";
961
637
  let settled = false;
962
638
  const finish = (value) => {
963
639
  if (settled) return;
964
640
  settled = true;
965
641
  clearTimeout(timer);
966
- resolve5(value);
642
+ resolve6(value);
967
643
  };
968
644
  let child;
969
645
  try {
970
- child = spawn2(cmd, args, {
646
+ child = spawn(cmd, args, {
971
647
  stdio: ["ignore", "pipe", "pipe"],
972
648
  shell: process.platform === "win32"
973
649
  });
974
650
  } catch {
975
- resolve5(null);
651
+ resolve6(null);
976
652
  return;
977
653
  }
978
654
  const timer = setTimeout(() => {
@@ -1016,7 +692,7 @@ async function detectProjectFiles(workingDir) {
1016
692
  ];
1017
693
  const found = [];
1018
694
  for (const candidate of candidates) {
1019
- if (await fileExists(path4.join(workingDir, candidate))) {
695
+ if (await fileExists(path3.join(workingDir, candidate))) {
1020
696
  found.push(candidate);
1021
697
  }
1022
698
  }
@@ -1152,6 +828,11 @@ var INSTALL_HINTS = {
1152
828
  conda: "conda (miniconda): https://docs.conda.io/projects/miniconda/en/latest/",
1153
829
  venv: "python3 with the venv module: https://www.python.org/downloads/"
1154
830
  };
831
+ function installUvNotice(managers) {
832
+ if (managers.some((m) => m.available)) return null;
833
+ const command = process.platform === "win32" ? UV_INSTALL_COMMANDS.windows : UV_INSTALL_COMMANDS.unix;
834
+ return `No Python package manager (uv, poetry, conda or python3 with venv) was found on this machine. Ask the user to install uv first, the recommended option: \`${command}\` (see https://docs.astral.sh/uv/getting-started/installation/). Then call qcentriq_get_setup_instructions for the commands that create the test environment, and restart the MCP client from that environment.`;
835
+ }
1155
836
  function detectActiveEnvironment() {
1156
837
  if (process.env.VIRTUAL_ENV) {
1157
838
  return `virtualenv: ${process.env.VIRTUAL_ENV}`;
@@ -1162,7 +843,7 @@ function detectActiveEnvironment() {
1162
843
  return null;
1163
844
  }
1164
845
  async function buildEnvironmentSetupPlan(params = {}) {
1165
- const workingDir = params.workingDir ? path4.resolve(params.workingDir) : process.cwd();
846
+ const workingDir = params.workingDir ? path3.resolve(params.workingDir) : process.cwd();
1166
847
  const [packageManagers, projectFiles] = await Promise.all([detectPackageManagers(), detectProjectFiles(workingDir)]);
1167
848
  const availability = new Map(packageManagers.map((m) => [m.name, m.available]));
1168
849
  const preferred = params.preferredManager;
@@ -1223,7 +904,289 @@ async function buildEnvironmentSetupPlan(params = {}) {
1223
904
  };
1224
905
  }
1225
906
 
907
+ // src/tools/save-group-script.ts
908
+ var ALLURE_ID = /@allure\.id\(\s*["'][^"']*["']\s*\)/g;
909
+ function registerSaveGroupScriptTool(server, client, config, passingRuns) {
910
+ server.registerTool(
911
+ "qcentriq_save_group_script",
912
+ {
913
+ description: "Save a test script you wrote back to QCentriq so the cloud runner executes exactly what you ran locally. Only a script that passed qcentriq_run_local_test as a whole file, with this exact content, is uploaded; each fixture must match the file next to it when it ran. The script is validated before it is stored: valid Python, and every test case in the group present exactly once as @allure.id('<case_id>') \u2014 no duplicates, no ids from other groups. A rejection names the offending id or line so you can correct it. Pass expected_updated_at from the last download to turn a concurrent edit into a conflict rather than a lost update. conftest.py cannot be saved; QCentriq provides it. Requires the 'test:write' scope.",
914
+ inputSchema: z11.object({
915
+ group_id: z11.uuid().describe("UUID of the target test group."),
916
+ content: z11.string().describe("The Python test script source."),
917
+ project_id: z11.uuid().optional().describe("Optional project UUID (inferred from the API key if omitted)."),
918
+ filename: z11.string().optional().describe("Optional script filename; derived from the group title if omitted."),
919
+ fixtures: z11.array(z11.object({ file_name: z11.string(), content: z11.string() })).optional().describe("Companion files to store next to the script (page objects, test data). conftest.py is rejected."),
920
+ expected_updated_at: z11.string().optional().describe("ISO-8601 timestamp from the last download. Supply it to get a conflict instead of silently overwriting someone else's edit.")
921
+ }),
922
+ annotations: {
923
+ readOnlyHint: false,
924
+ destructiveHint: true,
925
+ // Replaces the group's existing script.
926
+ idempotentHint: true,
927
+ // Saving the same content twice leaves the same state.
928
+ openWorldHint: false
929
+ }
930
+ },
931
+ async (args, ctx) => {
932
+ const untested = await untestedReason(passingRuns, args);
933
+ if (untested) return errorResult(untested);
934
+ const gate = confirmUpload(server, ctx, config, "this test script", describeUpload(args));
935
+ if (!gate.proceed) return gate.result;
936
+ const { group_id, ...body } = args;
937
+ return backendCall(
938
+ "qcentriq_save_group_script",
939
+ () => client.send("PUT", `/groups/${group_id}/script`, { ...body, project_id: body.project_id || config.defaultProjectId })
940
+ );
941
+ }
942
+ );
943
+ }
944
+ async function untestedReason(passingRuns, args) {
945
+ const run = passingRuns.find(args.content);
946
+ if (!run) {
947
+ const reason = "Upload refused: this script has not passed a local run, so nothing was sent to QCentriq. Save it to disk, run it with qcentriq_run_local_test on the whole file until it passes, then call this tool again with exactly that content.";
948
+ const notice = installUvNotice(await detectPackageManagers());
949
+ return notice ? `${reason}
950
+
951
+ ${notice}` : reason;
952
+ }
953
+ const mismatch = await fixtureMismatch(run, args.fixtures ?? []);
954
+ if (mismatch) {
955
+ return `Upload refused: ${mismatch}, so nothing was sent to QCentriq. Re-run ${run.filePath} with qcentriq_run_local_test and upload the files exactly as they were when it passed.`;
956
+ }
957
+ return null;
958
+ }
959
+ function describeUpload(args) {
960
+ const cases = args.content.match(ALLURE_ID)?.length ?? 0;
961
+ const file = args.filename ? `"${args.filename}"` : "(named after the group)";
962
+ const fixtures = args.fixtures?.length ? ` plus ${plural(args.fixtures.length, "companion file")} (${args.fixtures.map((f) => f.file_name).join(", ")})` : "";
963
+ return `Upload test script ${file}${fixtures} to QCentriq test group ${args.group_id}? It contains ${plural(cases, "test case")} and replaces the group's current script.`;
964
+ }
965
+
966
+ // src/tools/local-run.ts
967
+ import { z as z12 } from "zod";
968
+ import * as fs4 from "fs/promises";
969
+ import * as path5 from "path";
970
+
971
+ // src/local/runner.ts
972
+ import { spawn as spawn2 } from "child_process";
973
+ import * as path4 from "path";
974
+ function buildTestEnv(params) {
975
+ const env = {
976
+ ...process.env,
977
+ ...params.envVars || {}
978
+ };
979
+ if (params.baseUrl) {
980
+ env.BASE_URL = params.baseUrl;
981
+ }
982
+ if (params.browser) {
983
+ env.BROWSER = params.browser;
984
+ }
985
+ if (params.headless !== void 0) {
986
+ env.HEADLESS = params.headless ? "true" : "false";
987
+ }
988
+ if (params.groupId) {
989
+ env.QCAQ_TEST_GROUP_ID = params.groupId;
990
+ }
991
+ return env;
992
+ }
993
+ function resolvePytestCommand() {
994
+ const venv = process.env.VIRTUAL_ENV;
995
+ if (!venv) return "pytest";
996
+ return process.platform === "win32" ? path4.join(venv, "Scripts", "pytest.exe") : path4.join(venv, "bin", "pytest");
997
+ }
998
+ function killProcessTree(child) {
999
+ if (child.pid && process.platform !== "win32") {
1000
+ try {
1001
+ process.kill(-child.pid, "SIGKILL");
1002
+ return;
1003
+ } catch {
1004
+ }
1005
+ }
1006
+ try {
1007
+ child.kill("SIGKILL");
1008
+ } catch {
1009
+ }
1010
+ }
1011
+ function attempt(cmd, args, cwd, env, timeoutMs) {
1012
+ return new Promise((resolve6) => {
1013
+ let stdout = "";
1014
+ let stderr = "";
1015
+ let settled = false;
1016
+ const settle = (result) => {
1017
+ if (settled) return;
1018
+ settled = true;
1019
+ clearTimeout(timer);
1020
+ resolve6(result);
1021
+ };
1022
+ const child = spawn2(cmd, args, {
1023
+ cwd,
1024
+ env,
1025
+ detached: process.platform !== "win32",
1026
+ stdio: ["ignore", "pipe", "pipe"]
1027
+ });
1028
+ const timer = setTimeout(() => {
1029
+ killProcessTree(child);
1030
+ settle({ launched: true, exitCode: -1, stdout, stderr, timedOut: true });
1031
+ }, timeoutMs);
1032
+ child.stdout?.on("data", (chunk) => stdout += chunk.toString());
1033
+ child.stderr?.on("data", (chunk) => stderr += chunk.toString());
1034
+ child.on("error", (error) => settle({ launched: false, error }));
1035
+ child.on("close", (code) => settle({ launched: true, exitCode: code ?? -1, stdout, stderr, timedOut: false }));
1036
+ });
1037
+ }
1038
+ async function runLocalPytest(params) {
1039
+ const startTime = Date.now();
1040
+ const cwd = params.workingDir ? path4.resolve(params.workingDir) : process.cwd();
1041
+ const timeoutSeconds = params.timeoutSeconds || 60;
1042
+ const args = [params.filePath];
1043
+ if (params.testName) {
1044
+ args.push("-k", params.testName);
1045
+ }
1046
+ if (params.extraArgs) {
1047
+ args.push(...params.extraArgs);
1048
+ }
1049
+ if (!args.includes("-v") && !args.includes("-vv")) {
1050
+ args.push("-v");
1051
+ }
1052
+ const env = buildTestEnv(params);
1053
+ const failure = (stderr, command, pytestMissing) => ({
1054
+ passed: false,
1055
+ exitCode: -1,
1056
+ stdout: "",
1057
+ stderr,
1058
+ durationMs: Date.now() - startTime,
1059
+ command,
1060
+ pytestMissing
1061
+ });
1062
+ let cmd = resolvePytestCommand();
1063
+ let cmdArgs = args;
1064
+ logger.info(`Running local test command: ${cmd} ${cmdArgs.join(" ")} in ${cwd}`);
1065
+ let outcome = await attempt(cmd, cmdArgs, cwd, env, timeoutSeconds * 1e3);
1066
+ if (!outcome.launched) {
1067
+ if (outcome.error.code !== "ENOENT") {
1068
+ return failure(`Failed to spawn process: ${outcome.error.message}. Ensure pytest is installed in your Python environment.`, `${cmd} ${cmdArgs.join(" ")}`, false);
1069
+ }
1070
+ logger.warn("pytest binary not found directly, falling back to python3 -m pytest...");
1071
+ const primary = `${cmd} ${cmdArgs.join(" ")}`;
1072
+ cmd = "python3";
1073
+ cmdArgs = ["-m", "pytest", ...args];
1074
+ outcome = await attempt(cmd, cmdArgs, cwd, env, timeoutSeconds * 1e3);
1075
+ if (!outcome.launched) {
1076
+ return failure(`Failed to execute pytest or python3 -m pytest: ${outcome.error.message}. Ensure pytest is installed in your Python environment.`, primary, true);
1077
+ }
1078
+ }
1079
+ return {
1080
+ passed: !outcome.timedOut && outcome.exitCode === 0,
1081
+ exitCode: outcome.exitCode,
1082
+ stdout: outcome.stdout,
1083
+ stderr: outcome.timedOut ? `${outcome.stderr}
1084
+ [TIMEOUT] Test execution timed out after ${timeoutSeconds} seconds.` : outcome.stderr,
1085
+ durationMs: Date.now() - startTime,
1086
+ command: `${cmd} ${cmdArgs.join(" ")}`,
1087
+ pytestMissing: /No module named pytest/.test(outcome.stderr)
1088
+ };
1089
+ }
1090
+
1091
+ // src/tools/local-run.ts
1092
+ function registerLocalRunTool(server, passingRuns) {
1093
+ server.registerTool(
1094
+ "qcentriq_run_local_test",
1095
+ {
1096
+ description: "Execute a downloaded Playwright/pytest test script locally in the developer's environment. Runs pytest as a local subprocess and returns stdout, stderr, exit code, and test diagnostics without using QCentriq cloud runners. A script must pass here, as a whole file (no test_name or other test filters), before qcentriq_save_group_script will upload it.",
1097
+ inputSchema: z12.object({
1098
+ file_path: z12.string().describe("Path to the local test file to run (e.g. 'tests/test_login.py')."),
1099
+ test_name: z12.string().optional().describe("Optional specific test function name or expression to run (passed to pytest -k)."),
1100
+ headless: z12.boolean().default(true).describe("Whether to run the browser in headless mode (default True). Set False to watch the browser execution live."),
1101
+ browser: z12.enum(["chromium", "firefox", "webkit"]).default("chromium").describe("Browser engine to execute against (default 'chromium')."),
1102
+ base_url: z12.url().optional().describe("Target application base URL (e.g. from qcentriq_get_environment). Injected as BASE_URL env var."),
1103
+ group_id: z12.string().optional().describe("Test group UUID this script belongs to. Injected as QCAQ_TEST_GROUP_ID so the Allure results stay mappable back to the QCentriq group."),
1104
+ env_vars: z12.record(z12.string(), z12.string()).optional().describe("Environment variables to inject into the local test process."),
1105
+ extra_args: z12.array(z12.string()).optional().describe("Additional CLI arguments to pass to pytest (e.g. ['-s', '--alluredir=allure-results'])."),
1106
+ timeout_seconds: z12.number().int().min(5).max(300).default(60).describe("Timeout in seconds for test execution (default 60)."),
1107
+ working_dir: z12.string().optional().describe("Working directory to run pytest in (defaults to current project directory).")
1108
+ })
1109
+ },
1110
+ async (args) => {
1111
+ try {
1112
+ const scriptPath = path5.resolve(args.working_dir ?? process.cwd(), args.file_path.split("::")[0]);
1113
+ const content = await fs4.readFile(scriptPath, "utf-8").catch(() => null);
1114
+ const startedAt = Date.now();
1115
+ const result = await runLocalPytest({
1116
+ filePath: args.file_path,
1117
+ testName: args.test_name,
1118
+ headless: args.headless,
1119
+ browser: args.browser,
1120
+ baseUrl: args.base_url,
1121
+ groupId: args.group_id,
1122
+ envVars: args.env_vars,
1123
+ extraArgs: args.extra_args,
1124
+ timeoutSeconds: args.timeout_seconds,
1125
+ workingDir: args.working_dir
1126
+ });
1127
+ const statusText = result.passed ? "PASSED" : "FAILED";
1128
+ const summary = [
1129
+ `Local Test Run Result: ${statusText} (exit code ${result.exitCode})`,
1130
+ `Duration: ${(result.durationMs / 1e3).toFixed(2)}s`,
1131
+ `Command: ${result.command}`,
1132
+ "",
1133
+ "--- STDOUT ---",
1134
+ result.stdout || "(no stdout)",
1135
+ "",
1136
+ "--- STDERR ---",
1137
+ result.stderr || "(no stderr)"
1138
+ ];
1139
+ const next = await nextStep(result, args, content !== null);
1140
+ if (next.uploadable && content !== null) {
1141
+ passingRuns.record(content, { filePath: scriptPath, dir: path5.dirname(scriptPath), startedAt });
1142
+ }
1143
+ if (next.text) summary.push("", next.text);
1144
+ return {
1145
+ content: [
1146
+ {
1147
+ type: "text",
1148
+ text: summary.join("\n")
1149
+ }
1150
+ ],
1151
+ isError: !result.passed
1152
+ };
1153
+ } catch (err) {
1154
+ return {
1155
+ isError: true,
1156
+ content: [
1157
+ {
1158
+ type: "text",
1159
+ text: `Error executing local test: ${err.message}`
1160
+ }
1161
+ ]
1162
+ };
1163
+ }
1164
+ }
1165
+ );
1166
+ }
1167
+ async function nextStep(result, args, scriptReadable) {
1168
+ if (result.pytestMissing) {
1169
+ const notice = installUvNotice(await detectPackageManagers());
1170
+ return {
1171
+ uploadable: false,
1172
+ text: notice ?? "pytest is not installed in the Python environment the MCP server runs with. Call qcentriq_get_setup_instructions for the commands that set one up."
1173
+ };
1174
+ }
1175
+ if (!result.passed) return { uploadable: false };
1176
+ if (!coversWholeFile(args.file_path, args.test_name, args.extra_args)) {
1177
+ return { uploadable: false, text: "Only part of the script ran. Run the whole file, without test_name or test filters, before uploading it with qcentriq_save_group_script." };
1178
+ }
1179
+ if (!scriptReadable) {
1180
+ return { uploadable: false, text: "file_path is not a readable script file, so this pass cannot qualify an upload. Run the single script file you intend to upload." };
1181
+ }
1182
+ if (!reportsPassedTests(result.stdout)) {
1183
+ return { uploadable: false, text: "No test actually passed (all skipped or none collected), so this script cannot be uploaded yet." };
1184
+ }
1185
+ return { uploadable: true, text: "This exact script passed locally and can now be uploaded with qcentriq_save_group_script." };
1186
+ }
1187
+
1226
1188
  // src/tools/setup-instructions.ts
1189
+ import { z as z13 } from "zod";
1227
1190
  async function fetchRuntimeRequirements(client) {
1228
1191
  if (!client) return {};
1229
1192
  try {
@@ -1242,13 +1205,13 @@ function registerSetupInstructionsTool(server, client) {
1242
1205
  "qcentriq_get_setup_instructions",
1243
1206
  {
1244
1207
  description: "Check which Python package managers (uv, poetry, conda, or the stdlib venv module) are installed on the developer's machine and return step-by-step commands for creating an environment that can run QCentriq Playwright/pytest tests locally. Prefers uv when it is available; if no package manager is installed, the steps start by installing uv. Returns instructions only \u2014 it does not create the environment.",
1245
- inputSchema: {
1246
- preferred_manager: z11.enum(["uv", "poetry", "conda", "venv"]).optional().describe("Force instructions for a specific package manager. Falls back to the best available one if it is not installed."),
1247
- working_dir: z11.string().optional().describe("Directory to inspect for pyproject.toml / lockfiles / requirements.txt (defaults to the current project directory)."),
1248
- env_name: z11.string().default("qcentriq-tests").describe("Name for the created environment (used by conda, default 'qcentriq-tests')."),
1249
- python_version: z11.string().default("3.12").describe("Python version to request when creating the environment (default '3.12', matching the QCentriq execution container)."),
1250
- playwright_version: z11.string().optional().describe("Playwright version to pin when installing test dependencies. Defaults to the version the project's active execution image is built against, as reported by the backend.")
1251
- },
1208
+ inputSchema: z13.object({
1209
+ preferred_manager: z13.enum(["uv", "poetry", "conda", "venv"]).optional().describe("Force instructions for a specific package manager. Falls back to the best available one if it is not installed."),
1210
+ working_dir: z13.string().optional().describe("Directory to inspect for pyproject.toml / lockfiles / requirements.txt (defaults to the current project directory)."),
1211
+ env_name: z13.string().default("qcentriq-tests").describe("Name for the created environment (used by conda, default 'qcentriq-tests')."),
1212
+ python_version: z13.string().default("3.12").describe("Python version to request when creating the environment (default '3.12', matching the QCentriq execution container)."),
1213
+ playwright_version: z13.string().optional().describe("Playwright version to pin when installing test dependencies. Defaults to the version the project's active execution image is built against, as reported by the backend.")
1214
+ }),
1252
1215
  annotations: {
1253
1216
  readOnlyHint: true,
1254
1217
  // Only probes local package managers and project files; never mutates local or remote state.
@@ -1298,6 +1261,7 @@ function registerSetupInstructionsTool(server, client) {
1298
1261
  // src/tools/index.ts
1299
1262
  function registerAllTools(server, client, config) {
1300
1263
  logger.debug("Registering QCentriq MCP tools...");
1264
+ const passingRuns = new PassingRunLedger();
1301
1265
  registerListTestsTool(server, client, config);
1302
1266
  registerGetTestTool(server, client, config);
1303
1267
  registerGetTestGroupsTool(server, client, config);
@@ -1306,11 +1270,11 @@ function registerAllTools(server, client, config) {
1306
1270
  registerRunLogsTool(server, client, config);
1307
1271
  registerAuthoringGuideTool(server, client);
1308
1272
  registerCreatePlanTool(server, client, config);
1309
- registerSaveGroupScriptTool(server, client, config);
1273
+ registerSaveGroupScriptTool(server, client, config, passingRuns);
1310
1274
  registerSaveScriptTool(server);
1311
- registerLocalRunTool(server);
1275
+ registerLocalRunTool(server, passingRuns);
1312
1276
  registerSetupInstructionsTool(server, client);
1313
- logger.info("Successfully registered 12 QCentriq MCP tools (7 remote discovery + 2 authoring + 3 local client execution).");
1277
+ logger.info("Registered QCentriq MCP tools.");
1314
1278
  }
1315
1279
 
1316
1280
  // src/version.ts
@@ -1318,26 +1282,23 @@ import { createRequire } from "module";
1318
1282
  var PACKAGE_VERSION = createRequire(import.meta.url)("../package.json").version;
1319
1283
 
1320
1284
  // src/index.ts
1321
- async function main() {
1285
+ function main() {
1322
1286
  try {
1323
1287
  const config = loadConfig(process.argv);
1324
1288
  logger.info(`Starting QCentriq MCP Server against: ${config.baseUrl}`);
1325
1289
  const apiClient = new QCentriqApiClient(config);
1326
- const server = new McpServer({
1327
- name: "@qcentriq/mcp",
1328
- version: PACKAGE_VERSION
1290
+ const handle = serveStdio(() => {
1291
+ const server = new McpServer2({ name: "@qcentriq/mcp", version: PACKAGE_VERSION });
1292
+ registerAllTools(server, apiClient, config);
1293
+ return server;
1329
1294
  });
1330
- registerAllTools(server, apiClient, config);
1331
- const transport = new StdioServerTransport();
1332
1295
  const cleanup = async () => {
1333
1296
  logger.info("Shutting down QCentriq MCP Server...");
1334
- await apiClient.close();
1335
- await server.close();
1297
+ await handle.close();
1336
1298
  process.exit(0);
1337
1299
  };
1338
1300
  process.on("SIGINT", cleanup);
1339
1301
  process.on("SIGTERM", cleanup);
1340
- await server.connect(transport);
1341
1302
  logger.info("QCentriq MCP Server is running on stdio.");
1342
1303
  } catch (err) {
1343
1304
  logger.error("Fatal error during QCentriq MCP Server startup:", err.message);