@qcentriq/mcp 0.3.1 → 0.4.1

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,7 @@
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";
6
5
 
7
6
  // src/config.ts
8
7
  import { Command } from "commander";
@@ -96,6 +95,7 @@ function sanitizePayload(value) {
96
95
  }
97
96
 
98
97
  // src/client/api.ts
98
+ var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
99
99
  async function readErrorDetail(res) {
100
100
  let text;
101
101
  try {
@@ -112,164 +112,90 @@ async function readErrorDetail(res) {
112
112
  }
113
113
  }
114
114
  var QCentriqApiClient = class {
115
- config;
116
115
  constructor(config) {
117
116
  this.config = config;
118
117
  }
119
118
  /**
120
- * Make an authenticated HTTP request to the QCentriq backend (/api/v1/mcp-client/...).
119
+ * Authenticated GET against the QCentriq backend (/api/v1/mcp-client/...).
120
+ * Undefined and null params are left out of the query string.
121
121
  */
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}`);
122
+ async request(path6, params = {}) {
123
+ const query = new URLSearchParams();
125
124
  for (const [key, value] of Object.entries(params)) {
126
125
  if (value !== void 0 && value !== null) {
127
- url.searchParams.set(key, String(value));
126
+ query.set(key, String(value));
128
127
  }
129
128
  }
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"
136
- }
137
- });
138
- if (!res.ok) {
139
- throw new Error(`API error (${res.status}): ${await readErrorDetail(res)}`);
140
- }
141
- const data = await res.json();
142
- return sanitizePayload(data);
129
+ return this.call("GET", path6, query);
143
130
  }
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}`;
131
+ /** Authenticated JSON write against the QCentriq backend. */
132
+ async send(method, path6, body) {
133
+ return this.call(method, path6, void 0, body);
134
+ }
135
+ async call(method, path6, query, body) {
136
+ const cleanPath = path6.startsWith("/") ? path6 : `/${path6}`;
137
+ const qs = query?.toString();
138
+ const url = `${this.config.baseUrl}/api/v1/mcp-client${cleanPath}${qs ? `?${qs}` : ""}`;
153
139
  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)
140
+ const headers = {
141
+ Authorization: `Bearer ${this.config.apiKey}`,
142
+ Accept: "application/json"
143
+ };
144
+ if (body) headers["Content-Type"] = "application/json";
145
+ const res = await this.fetchWithTimeout(method, cleanPath, url, {
146
+ headers,
147
+ body: body ? JSON.stringify(body) : void 0
162
148
  });
163
149
  if (!res.ok) {
164
150
  throw new Error(`API error (${res.status}): ${await readErrorDetail(res)}`);
165
151
  }
166
- const data = await res.json();
167
- return sanitizePayload(data);
152
+ return sanitizePayload(await res.json());
168
153
  }
169
154
  /**
170
- * Invoke remote tool via /api/v1/mcp-client REST endpoints and wrap
171
- * response in standard MCP CallToolResult format.
155
+ * Issue a request that is aborted after the configured timeout, reporting
156
+ * the timeout as such rather than as a bare AbortError.
172
157
  */
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;
158
+ async fetchWithTimeout(method, path6, url, init) {
159
+ const timeoutMs = this.config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
160
+ try {
161
+ return await fetch(url, { ...init, method, signal: AbortSignal.timeout(timeoutMs) });
162
+ } catch (err) {
163
+ if (err?.name === "TimeoutError") {
164
+ throw new Error(`${method} ${path6} timed out after ${timeoutMs}ms`);
245
165
  }
246
- default:
247
- throw new Error(`Unknown tool: ${toolName}`);
166
+ throw err;
248
167
  }
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
168
  }
263
169
  };
264
170
 
171
+ // src/server.ts
172
+ import { McpServer } from "@modelcontextprotocol/server";
173
+
265
174
  // src/tools/list-tests.ts
266
175
  import { z } from "zod";
176
+
177
+ // src/tools/results.ts
178
+ function jsonResult(data) {
179
+ return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };
180
+ }
181
+ function errorResult(text) {
182
+ return { isError: true, content: [{ type: "text", text }] };
183
+ }
184
+ async function backendCall(tool, run) {
185
+ try {
186
+ return jsonResult(await run());
187
+ } catch (err) {
188
+ return errorResult(`Error in ${tool}: ${err.message}`);
189
+ }
190
+ }
191
+
192
+ // src/tools/list-tests.ts
267
193
  function registerListTestsTool(server, client, config) {
268
194
  server.registerTool(
269
195
  "qcentriq_list_tests",
270
196
  {
271
197
  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: {
198
+ inputSchema: z.object({
273
199
  project_id: z.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
274
200
  group_id: z.uuid().optional().describe("Optional test group UUID filter."),
275
201
  priority: z.enum(["low", "medium", "high", "critical"]).optional().describe("Filter by priority."),
@@ -277,23 +203,12 @@ function registerListTestsTool(server, client, config) {
277
203
  status: z.enum(["failed", "passed", "error", "never_run", "blocked", "active", "flaky"]).optional().describe("Filter by test status (e.g. 'failed' or 'blocked')."),
278
204
  limit: z.number().int().min(1).max(100).default(50).describe("Max number of test cases to return (default 50)."),
279
205
  offset: z.number().int().min(0).default(0).describe("Pagination offset.")
280
- }
206
+ })
281
207
  },
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
- }
208
+ async (args) => backendCall(
209
+ "qcentriq_list_tests",
210
+ () => client.request("/tests", { ...args, project_id: args.project_id || config.defaultProjectId })
211
+ )
297
212
  );
298
213
  }
299
214
 
@@ -304,26 +219,15 @@ function registerGetTestTool(server, client, config) {
304
219
  "qcentriq_get_test",
305
220
  {
306
221
  description: "Retrieve detailed test case information including step definitions, preconditions, latest execution diagnostics, error stack traces, and parent test group script metadata.",
307
- inputSchema: {
222
+ inputSchema: z2.object({
308
223
  test_case_id: z2.uuid().describe("UUID of the target test case."),
309
224
  project_id: z2.uuid().optional().describe("Optional project UUID (inferred from API key if omitted).")
310
- }
225
+ })
311
226
  },
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
- }
227
+ async ({ test_case_id, ...query }) => backendCall(
228
+ "qcentriq_get_test",
229
+ () => client.request(`/tests/${test_case_id}`, { ...query, project_id: query.project_id || config.defaultProjectId })
230
+ )
327
231
  );
328
232
  }
329
233
 
@@ -334,35 +238,22 @@ function registerGetTestGroupsTool(server, client, config) {
334
238
  "qcentriq_get_test_groups",
335
239
  {
336
240
  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: {
241
+ inputSchema: z3.object({
338
242
  project_id: z3.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
339
243
  group_id: z3.uuid().optional().describe("Optional test group UUID filter to inspect a specific group."),
340
244
  limit: z3.number().int().min(1).max(100).default(50).describe("Max test groups to return (default 50)."),
341
245
  offset: z3.number().int().min(0).default(0).describe("Pagination offset.")
342
- }
246
+ })
343
247
  },
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
- }
248
+ async (args) => backendCall(
249
+ "qcentriq_get_test_groups",
250
+ () => client.request("/groups", { ...args, project_id: args.project_id || config.defaultProjectId })
251
+ )
359
252
  );
360
253
  }
361
254
 
362
255
  // src/tools/download-script.ts
363
256
  import { z as z5 } from "zod";
364
- import * as fs2 from "fs/promises";
365
- import * as path2 from "path";
366
257
 
367
258
  // src/tools/save-script.ts
368
259
  import { z as z4 } from "zod";
@@ -374,129 +265,86 @@ function registerSaveScriptTool(server) {
374
265
  "qcentriq_save_script",
375
266
  {
376
267
  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: {
268
+ inputSchema: z4.object({
378
269
  file_name: z4.string().describe("Target filename (e.g. 'test_login.py')."),
379
270
  content: z4.string().describe("Python test script source code."),
380
271
  conftest_content: z4.string().optional().describe("Accompanying conftest.py source code if present."),
381
272
  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
- }
273
+ })
383
274
  },
384
275
  async (args) => {
385
276
  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
- };
277
+ const savedFiles = await saveScriptFiles(args.destination_dir ?? DEFAULT_SCRIPT_DIR, args.file_name, args.content, args.conftest_content);
278
+ return jsonResult({
279
+ status: "success",
280
+ message: `Successfully saved ${savedFiles.length} file(s) to ${path.dirname(savedFiles[0])}`,
281
+ saved_files: savedFiles
282
+ });
422
283
  } 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
- };
284
+ return errorResult(`Failed to save test script to disk: ${err.message}`);
432
285
  }
433
286
  }
434
287
  );
435
288
  }
289
+ async function saveScriptFiles(destinationDir, fileName, content, conftest) {
290
+ const safeFileName = path.basename(fileName);
291
+ if (!safeFileName || safeFileName === "." || safeFileName === "..") {
292
+ throw new Error(`Invalid file name: "${fileName}"`);
293
+ }
294
+ const targetDir = path.resolve(process.cwd(), destinationDir);
295
+ await fs.mkdir(targetDir, { recursive: true });
296
+ const scriptPath = path.join(targetDir, safeFileName);
297
+ await fs.writeFile(scriptPath, content, "utf-8");
298
+ logger.info(`Saved test script to: ${scriptPath}`);
299
+ const saved = [scriptPath];
300
+ if (conftest) {
301
+ const conftestPath = path.join(targetDir, "conftest.py");
302
+ await fs.writeFile(conftestPath, conftest, "utf-8");
303
+ logger.info(`Saved conftest.py to: ${conftestPath}`);
304
+ saved.push(conftestPath);
305
+ }
306
+ return saved;
307
+ }
436
308
 
437
309
  // src/tools/download-script.ts
438
310
  function registerDownloadScriptTool(server, client, config) {
439
311
  server.registerTool(
440
312
  "qcentriq_download_script",
441
313
  {
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: {
314
+ 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.`,
315
+ inputSchema: z5.object({
444
316
  group_id: z5.uuid().describe("UUID of the target test group."),
445
317
  project_id: z5.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
446
318
  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."),
319
+ 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
320
  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
- }
321
+ })
450
322
  },
451
323
  async (args) => {
324
+ let data;
452
325
  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,
326
+ data = await client.request(`/groups/${args.group_id}/script`, {
327
+ project_id: args.project_id || config.defaultProjectId,
457
328
  include_fixtures: args.include_fixtures
458
329
  });
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
330
  } catch (err) {
331
+ return errorResult(`Error in qcentriq_download_script: ${err.message}`);
332
+ }
333
+ if (!args.save_to_disk || !data?.file_name || !data?.content) return jsonResult(data);
334
+ try {
335
+ data.saved_files = await saveScriptFiles(args.destination_dir, data.file_name, data.content, data.conftest_content);
336
+ return jsonResult(data);
337
+ } catch (writeErr) {
338
+ logger.warn(`Failed to write downloaded script to disk: ${writeErr.message}`);
497
339
  return {
498
340
  isError: true,
499
- content: [{ type: "text", text: `Error in qcentriq_download_script: ${err.message}` }]
341
+ content: [
342
+ {
343
+ type: "text",
344
+ 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.`
345
+ },
346
+ ...jsonResult(data).content
347
+ ]
500
348
  };
501
349
  }
502
350
  }
@@ -510,27 +358,16 @@ function registerEnvironmentTool(server, client, config) {
510
358
  "qcentriq_get_environment",
511
359
  {
512
360
  description: "Retrieve target test environment configuration, base URL (BASE_URL), environment variables, and required secret variable names for local test execution.",
513
- inputSchema: {
361
+ inputSchema: z6.object({
514
362
  project_id: z6.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
515
363
  environment_id: z6.uuid().optional().describe("Optional specific environment UUID."),
516
364
  environment_name: z6.string().optional().describe("Optional environment name filter (e.g. 'staging', 'dev', 'production').")
517
- }
365
+ })
518
366
  },
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
- }
367
+ async (args) => backendCall(
368
+ "qcentriq_get_environment",
369
+ () => client.request("/environment", { ...args, project_id: args.project_id || config.defaultProjectId })
370
+ )
534
371
  );
535
372
  }
536
373
 
@@ -541,7 +378,7 @@ function registerRunLogsTool(server, client, config) {
541
378
  "qcentriq_get_test_run_logs",
542
379
  {
543
380
  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: {
381
+ inputSchema: z7.object({
545
382
  test_case_id: z7.uuid().describe("UUID of the target test case."),
546
383
  project_id: z7.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
547
384
  run_id: z7.uuid().optional().describe("Optional specific run UUID to fetch a single run's full log."),
@@ -551,33 +388,23 @@ function registerRunLogsTool(server, client, config) {
551
388
  to_date: z7.string().optional().describe("Optional ISO-8601 end date filter."),
552
389
  limit: z7.number().int().min(1).max(100).default(20).describe("Max runs to return."),
553
390
  offset: z7.number().int().min(0).default(0).describe("Pagination offset.")
554
- }
391
+ })
555
392
  },
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
- }
393
+ async ({ test_case_id, ...query }) => backendCall(
394
+ "qcentriq_get_test_run_logs",
395
+ () => client.request(`/tests/${test_case_id}/run-logs`, { ...query, project_id: query.project_id || config.defaultProjectId })
396
+ )
571
397
  );
572
398
  }
573
399
 
574
400
  // src/tools/authoring-guide.ts
401
+ import { z as z8 } from "zod";
575
402
  function registerAuthoringGuideTool(server, client) {
576
403
  server.registerTool(
577
404
  "qcentriq_get_authoring_guide",
578
405
  {
579
- 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: {},
406
+ 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. Then explore the app under test with the Playwright MCP server (browser_navigate, browser_snapshot) before writing, so the plan and locators match what the app really shows.",
407
+ inputSchema: z8.object({}),
581
408
  annotations: {
582
409
  readOnlyHint: true,
583
410
  destructiveHint: false,
@@ -602,16 +429,16 @@ function registerAuthoringGuideTool(server, client) {
602
429
  }
603
430
 
604
431
  // src/tools/create-plan.ts
605
- import { z as z8 } from "zod";
432
+ import { z as z9 } from "zod";
606
433
  function registerCreatePlanTool(server, client, config) {
607
434
  server.registerTool(
608
435
  "qcentriq_create_plan",
609
436
  {
610
- 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
- },
437
+ description: "Create test groups and test cases in QCentriq from a plan you authored. Call qcentriq_get_authoring_guide first, and walk through every flow in the plan with the Playwright MCP server (browser_navigate, browser_snapshot) when it is connected, so each test case describes behaviour you saw rather than guessed. 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.",
438
+ inputSchema: z9.object({
439
+ plan: z9.record(z9.string(), z9.any()).describe("The plan object, matching the TaskPlan schema from qcentriq_get_authoring_guide."),
440
+ project_id: z9.uuid().optional().describe("Optional project UUID (inferred from the API key if omitted).")
441
+ }),
615
442
  annotations: {
616
443
  readOnlyHint: false,
617
444
  destructiveHint: false,
@@ -621,323 +448,69 @@ function registerCreatePlanTool(server, client, config) {
621
448
  openWorldHint: false
622
449
  }
623
450
  },
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
- }
637
- }
451
+ async (args) => backendCall(
452
+ "qcentriq_create_plan",
453
+ () => client.send("POST", "/plans", { plan: args.plan, project_id: args.project_id || config.defaultProjectId })
454
+ )
638
455
  );
639
456
  }
640
457
 
641
458
  // 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
- );
681
- }
682
-
683
- // src/tools/local-run.ts
684
459
  import { z as z10 } from "zod";
685
460
 
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";
461
+ // src/local/passing-runs.ts
462
+ import { createHash } from "crypto";
463
+ import * as fs2 from "fs/promises";
464
+ import * as path2 from "path";
465
+ var PassingRunLedger = class {
466
+ runs = /* @__PURE__ */ new Map();
467
+ record(content, run) {
468
+ this.runs.set(contentHash(content), run);
702
469
  }
703
- if (params.groupId) {
704
- env.QCAQ_TEST_GROUP_ID = params.groupId;
470
+ find(content) {
471
+ return this.runs.get(contentHash(content));
705
472
  }
706
- return env;
473
+ };
474
+ function contentHash(content) {
475
+ return createHash("sha256").update(content).digest("hex");
707
476
  }
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: [] };
477
+ var NARROWING_FLAGS = ["-k", "-m", "--deselect", "--lf", "--last-failed", "--sw", "--stepwise", "--co", "--collect-only", "--setup-only", "--setup-plan", "--fixtures"];
478
+ function coversWholeFile(filePath, testName, extraArgs = []) {
479
+ if (testName || filePath.includes("::")) return false;
480
+ return !extraArgs.some(
481
+ (arg) => NARROWING_FLAGS.some((flag) => arg === flag || arg.startsWith(`${flag}=`) || /^-[a-z]$/.test(flag) && arg.startsWith(flag))
482
+ );
714
483
  }
715
- function killProcessTree(child) {
716
- if (child.pid) {
484
+ function reportsPassedTests(stdout) {
485
+ return /\b[1-9]\d* passed\b/.test(stdout);
486
+ }
487
+ async function fixtureMismatch(run, fixtures) {
488
+ for (const fixture of fixtures) {
489
+ const localPath = path2.resolve(run.dir, fixture.file_name);
490
+ if (path2.dirname(localPath) !== run.dir) {
491
+ return `companion file "${fixture.file_name}" is not a plain file name next to the script`;
492
+ }
493
+ let local;
494
+ let modifiedAt;
717
495
  try {
718
- if (process.platform !== "win32") {
719
- process.kill(-child.pid, "SIGKILL");
720
- return;
721
- }
496
+ [local, modifiedAt] = await Promise.all([fs2.readFile(localPath, "utf-8"), fs2.stat(localPath).then((s) => s.mtimeMs)]);
722
497
  } catch {
498
+ return `companion file "${fixture.file_name}" was not next to the script (${run.dir}) when it passed`;
723
499
  }
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
- }
500
+ if (local !== fixture.content) {
501
+ return `companion file "${fixture.file_name}" differs from ${localPath}, which the passing run used`;
930
502
  }
931
- );
503
+ if (modifiedAt > run.startedAt) {
504
+ return `companion file "${fixture.file_name}" changed after the passing run`;
505
+ }
506
+ }
507
+ return null;
932
508
  }
933
509
 
934
- // src/tools/setup-instructions.ts
935
- import { z as z11 } from "zod";
936
-
937
510
  // src/local/environment-setup.ts
938
- import { spawn as spawn2 } from "child_process";
511
+ import { spawn } from "child_process";
939
512
  import * as fs3 from "fs/promises";
940
- import * as path4 from "path";
513
+ import * as path3 from "path";
941
514
  var MANAGER_PRIORITY = ["uv", "poetry", "conda", "venv"];
942
515
  var PROBE_TIMEOUT_MS = 5e3;
943
516
  var DEFAULT_PYTHON_VERSION = "3.12";
@@ -956,23 +529,23 @@ function testDependencies(playwrightVersion, packages) {
956
529
  return [...base, `playwright==${playwrightVersion}`].join(" ");
957
530
  }
958
531
  function probeCommand(cmd, args) {
959
- return new Promise((resolve5) => {
532
+ return new Promise((resolve6) => {
960
533
  let output = "";
961
534
  let settled = false;
962
535
  const finish = (value) => {
963
536
  if (settled) return;
964
537
  settled = true;
965
538
  clearTimeout(timer);
966
- resolve5(value);
539
+ resolve6(value);
967
540
  };
968
541
  let child;
969
542
  try {
970
- child = spawn2(cmd, args, {
543
+ child = spawn(cmd, args, {
971
544
  stdio: ["ignore", "pipe", "pipe"],
972
545
  shell: process.platform === "win32"
973
546
  });
974
547
  } catch {
975
- resolve5(null);
548
+ resolve6(null);
976
549
  return;
977
550
  }
978
551
  const timer = setTimeout(() => {
@@ -1016,7 +589,7 @@ async function detectProjectFiles(workingDir) {
1016
589
  ];
1017
590
  const found = [];
1018
591
  for (const candidate of candidates) {
1019
- if (await fileExists(path4.join(workingDir, candidate))) {
592
+ if (await fileExists(path3.join(workingDir, candidate))) {
1020
593
  found.push(candidate);
1021
594
  }
1022
595
  }
@@ -1152,6 +725,11 @@ var INSTALL_HINTS = {
1152
725
  conda: "conda (miniconda): https://docs.conda.io/projects/miniconda/en/latest/",
1153
726
  venv: "python3 with the venv module: https://www.python.org/downloads/"
1154
727
  };
728
+ function installUvNotice(managers) {
729
+ if (managers.some((m) => m.available)) return null;
730
+ const command = process.platform === "win32" ? UV_INSTALL_COMMANDS.windows : UV_INSTALL_COMMANDS.unix;
731
+ 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.`;
732
+ }
1155
733
  function detectActiveEnvironment() {
1156
734
  if (process.env.VIRTUAL_ENV) {
1157
735
  return `virtualenv: ${process.env.VIRTUAL_ENV}`;
@@ -1162,7 +740,7 @@ function detectActiveEnvironment() {
1162
740
  return null;
1163
741
  }
1164
742
  async function buildEnvironmentSetupPlan(params = {}) {
1165
- const workingDir = params.workingDir ? path4.resolve(params.workingDir) : process.cwd();
743
+ const workingDir = params.workingDir ? path3.resolve(params.workingDir) : process.cwd();
1166
744
  const [packageManagers, projectFiles] = await Promise.all([detectPackageManagers(), detectProjectFiles(workingDir)]);
1167
745
  const availability = new Map(packageManagers.map((m) => [m.name, m.available]));
1168
746
  const preferred = params.preferredManager;
@@ -1223,7 +801,280 @@ async function buildEnvironmentSetupPlan(params = {}) {
1223
801
  };
1224
802
  }
1225
803
 
804
+ // src/tools/save-group-script.ts
805
+ function registerSaveGroupScriptTool(server, client, config, passingRuns) {
806
+ server.registerTool(
807
+ "qcentriq_save_group_script",
808
+ {
809
+ 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.",
810
+ inputSchema: z10.object({
811
+ group_id: z10.uuid().describe("UUID of the target test group."),
812
+ content: z10.string().describe("The Python test script source."),
813
+ project_id: z10.uuid().optional().describe("Optional project UUID (inferred from the API key if omitted)."),
814
+ filename: z10.string().optional().describe("Optional script filename; derived from the group title if omitted."),
815
+ fixtures: z10.array(z10.object({ file_name: z10.string(), content: z10.string() })).optional().describe("Companion files to store next to the script (page objects, test data). conftest.py is rejected."),
816
+ expected_updated_at: z10.string().optional().describe("ISO-8601 timestamp from the last download. Supply it to get a conflict instead of silently overwriting someone else's edit.")
817
+ }),
818
+ annotations: {
819
+ readOnlyHint: false,
820
+ destructiveHint: true,
821
+ // Replaces the group's existing script.
822
+ idempotentHint: true,
823
+ // Saving the same content twice leaves the same state.
824
+ openWorldHint: false
825
+ }
826
+ },
827
+ async (args) => {
828
+ const untested = await untestedReason(passingRuns, args);
829
+ if (untested) return errorResult(untested);
830
+ const { group_id, ...body } = args;
831
+ return backendCall(
832
+ "qcentriq_save_group_script",
833
+ () => client.send("PUT", `/groups/${group_id}/script`, { ...body, project_id: body.project_id || config.defaultProjectId })
834
+ );
835
+ }
836
+ );
837
+ }
838
+ async function untestedReason(passingRuns, args) {
839
+ const run = passingRuns.find(args.content);
840
+ if (!run) {
841
+ 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.";
842
+ const notice = installUvNotice(await detectPackageManagers());
843
+ return notice ? `${reason}
844
+
845
+ ${notice}` : reason;
846
+ }
847
+ const mismatch = await fixtureMismatch(run, args.fixtures ?? []);
848
+ if (mismatch) {
849
+ 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.`;
850
+ }
851
+ return null;
852
+ }
853
+
854
+ // src/tools/local-run.ts
855
+ import { z as z11 } from "zod";
856
+ import * as fs4 from "fs/promises";
857
+ import * as path5 from "path";
858
+
859
+ // src/local/runner.ts
860
+ import { spawn as spawn2 } from "child_process";
861
+ import * as path4 from "path";
862
+ function buildTestEnv(params) {
863
+ const env = {
864
+ ...process.env,
865
+ ...params.envVars || {}
866
+ };
867
+ if (params.baseUrl) {
868
+ env.BASE_URL = params.baseUrl;
869
+ }
870
+ if (params.browser) {
871
+ env.BROWSER = params.browser;
872
+ }
873
+ if (params.headless !== void 0) {
874
+ env.HEADLESS = params.headless ? "true" : "false";
875
+ }
876
+ if (params.groupId) {
877
+ env.QCAQ_TEST_GROUP_ID = params.groupId;
878
+ }
879
+ return env;
880
+ }
881
+ function resolvePytestCommand() {
882
+ const venv = process.env.VIRTUAL_ENV;
883
+ if (!venv) return "pytest";
884
+ return process.platform === "win32" ? path4.join(venv, "Scripts", "pytest.exe") : path4.join(venv, "bin", "pytest");
885
+ }
886
+ function killProcessTree(child) {
887
+ if (child.pid && process.platform !== "win32") {
888
+ try {
889
+ process.kill(-child.pid, "SIGKILL");
890
+ return;
891
+ } catch {
892
+ }
893
+ }
894
+ try {
895
+ child.kill("SIGKILL");
896
+ } catch {
897
+ }
898
+ }
899
+ function attempt(cmd, args, cwd, env, timeoutMs) {
900
+ return new Promise((resolve6) => {
901
+ let stdout = "";
902
+ let stderr = "";
903
+ let settled = false;
904
+ const settle = (result) => {
905
+ if (settled) return;
906
+ settled = true;
907
+ clearTimeout(timer);
908
+ resolve6(result);
909
+ };
910
+ const child = spawn2(cmd, args, {
911
+ cwd,
912
+ env,
913
+ detached: process.platform !== "win32",
914
+ stdio: ["ignore", "pipe", "pipe"]
915
+ });
916
+ const timer = setTimeout(() => {
917
+ killProcessTree(child);
918
+ settle({ launched: true, exitCode: -1, stdout, stderr, timedOut: true });
919
+ }, timeoutMs);
920
+ child.stdout?.on("data", (chunk) => stdout += chunk.toString());
921
+ child.stderr?.on("data", (chunk) => stderr += chunk.toString());
922
+ child.on("error", (error) => settle({ launched: false, error }));
923
+ child.on("close", (code) => settle({ launched: true, exitCode: code ?? -1, stdout, stderr, timedOut: false }));
924
+ });
925
+ }
926
+ async function runLocalPytest(params) {
927
+ const startTime = Date.now();
928
+ const cwd = params.workingDir ? path4.resolve(params.workingDir) : process.cwd();
929
+ const timeoutSeconds = params.timeoutSeconds || 60;
930
+ const args = [params.filePath];
931
+ if (params.testName) {
932
+ args.push("-k", params.testName);
933
+ }
934
+ if (params.extraArgs) {
935
+ args.push(...params.extraArgs);
936
+ }
937
+ if (!args.includes("-v") && !args.includes("-vv")) {
938
+ args.push("-v");
939
+ }
940
+ const env = buildTestEnv(params);
941
+ const failure = (stderr, command, pytestMissing) => ({
942
+ passed: false,
943
+ exitCode: -1,
944
+ stdout: "",
945
+ stderr,
946
+ durationMs: Date.now() - startTime,
947
+ command,
948
+ pytestMissing
949
+ });
950
+ let cmd = resolvePytestCommand();
951
+ let cmdArgs = args;
952
+ logger.info(`Running local test command: ${cmd} ${cmdArgs.join(" ")} in ${cwd}`);
953
+ let outcome = await attempt(cmd, cmdArgs, cwd, env, timeoutSeconds * 1e3);
954
+ if (!outcome.launched) {
955
+ if (outcome.error.code !== "ENOENT") {
956
+ return failure(`Failed to spawn process: ${outcome.error.message}. Ensure pytest is installed in your Python environment.`, `${cmd} ${cmdArgs.join(" ")}`, false);
957
+ }
958
+ logger.warn("pytest binary not found directly, falling back to python3 -m pytest...");
959
+ const primary = `${cmd} ${cmdArgs.join(" ")}`;
960
+ cmd = "python3";
961
+ cmdArgs = ["-m", "pytest", ...args];
962
+ outcome = await attempt(cmd, cmdArgs, cwd, env, timeoutSeconds * 1e3);
963
+ if (!outcome.launched) {
964
+ return failure(`Failed to execute pytest or python3 -m pytest: ${outcome.error.message}. Ensure pytest is installed in your Python environment.`, primary, true);
965
+ }
966
+ }
967
+ return {
968
+ passed: !outcome.timedOut && outcome.exitCode === 0,
969
+ exitCode: outcome.exitCode,
970
+ stdout: outcome.stdout,
971
+ stderr: outcome.timedOut ? `${outcome.stderr}
972
+ [TIMEOUT] Test execution timed out after ${timeoutSeconds} seconds.` : outcome.stderr,
973
+ durationMs: Date.now() - startTime,
974
+ command: `${cmd} ${cmdArgs.join(" ")}`,
975
+ pytestMissing: /No module named pytest/.test(outcome.stderr)
976
+ };
977
+ }
978
+
979
+ // src/tools/local-run.ts
980
+ function registerLocalRunTool(server, passingRuns) {
981
+ server.registerTool(
982
+ "qcentriq_run_local_test",
983
+ {
984
+ 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.",
985
+ inputSchema: z11.object({
986
+ file_path: z11.string().describe("Path to the local test file to run (e.g. 'tests/test_login.py')."),
987
+ test_name: z11.string().optional().describe("Optional specific test function name or expression to run (passed to pytest -k)."),
988
+ headless: z11.boolean().default(true).describe("Whether to run the browser in headless mode (default True). Set False to watch the browser execution live."),
989
+ browser: z11.enum(["chromium", "firefox", "webkit"]).default("chromium").describe("Browser engine to execute against (default 'chromium')."),
990
+ base_url: z11.url().optional().describe("Target application base URL (e.g. from qcentriq_get_environment). Injected as BASE_URL env var."),
991
+ group_id: z11.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."),
992
+ env_vars: z11.record(z11.string(), z11.string()).optional().describe("Environment variables to inject into the local test process."),
993
+ extra_args: z11.array(z11.string()).optional().describe("Additional CLI arguments to pass to pytest (e.g. ['-s', '--alluredir=allure-results'])."),
994
+ timeout_seconds: z11.number().int().min(5).max(300).default(60).describe("Timeout in seconds for test execution (default 60)."),
995
+ working_dir: z11.string().optional().describe("Working directory to run pytest in (defaults to current project directory).")
996
+ })
997
+ },
998
+ async (args) => {
999
+ try {
1000
+ const scriptPath = path5.resolve(args.working_dir ?? process.cwd(), args.file_path.split("::")[0]);
1001
+ const content = await fs4.readFile(scriptPath, "utf-8").catch(() => null);
1002
+ const startedAt = Date.now();
1003
+ const result = await runLocalPytest({
1004
+ filePath: args.file_path,
1005
+ testName: args.test_name,
1006
+ headless: args.headless,
1007
+ browser: args.browser,
1008
+ baseUrl: args.base_url,
1009
+ groupId: args.group_id,
1010
+ envVars: args.env_vars,
1011
+ extraArgs: args.extra_args,
1012
+ timeoutSeconds: args.timeout_seconds,
1013
+ workingDir: args.working_dir
1014
+ });
1015
+ const statusText = result.passed ? "PASSED" : "FAILED";
1016
+ const summary = [
1017
+ `Local Test Run Result: ${statusText} (exit code ${result.exitCode})`,
1018
+ `Duration: ${(result.durationMs / 1e3).toFixed(2)}s`,
1019
+ `Command: ${result.command}`,
1020
+ "",
1021
+ "--- STDOUT ---",
1022
+ result.stdout || "(no stdout)",
1023
+ "",
1024
+ "--- STDERR ---",
1025
+ result.stderr || "(no stderr)"
1026
+ ];
1027
+ const next = await nextStep(result, args, content !== null);
1028
+ if (next.uploadable && content !== null) {
1029
+ passingRuns.record(content, { filePath: scriptPath, dir: path5.dirname(scriptPath), startedAt });
1030
+ }
1031
+ if (next.text) summary.push("", next.text);
1032
+ return {
1033
+ content: [
1034
+ {
1035
+ type: "text",
1036
+ text: summary.join("\n")
1037
+ }
1038
+ ],
1039
+ isError: !result.passed
1040
+ };
1041
+ } catch (err) {
1042
+ return {
1043
+ isError: true,
1044
+ content: [
1045
+ {
1046
+ type: "text",
1047
+ text: `Error executing local test: ${err.message}`
1048
+ }
1049
+ ]
1050
+ };
1051
+ }
1052
+ }
1053
+ );
1054
+ }
1055
+ async function nextStep(result, args, scriptReadable) {
1056
+ if (result.pytestMissing) {
1057
+ const notice = installUvNotice(await detectPackageManagers());
1058
+ return {
1059
+ uploadable: false,
1060
+ 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."
1061
+ };
1062
+ }
1063
+ if (!result.passed) return { uploadable: false };
1064
+ if (!coversWholeFile(args.file_path, args.test_name, args.extra_args)) {
1065
+ 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." };
1066
+ }
1067
+ if (!scriptReadable) {
1068
+ 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." };
1069
+ }
1070
+ if (!reportsPassedTests(result.stdout)) {
1071
+ return { uploadable: false, text: "No test actually passed (all skipped or none collected), so this script cannot be uploaded yet." };
1072
+ }
1073
+ return { uploadable: true, text: "This exact script passed locally and can now be uploaded with qcentriq_save_group_script." };
1074
+ }
1075
+
1226
1076
  // src/tools/setup-instructions.ts
1077
+ import { z as z12 } from "zod";
1227
1078
  async function fetchRuntimeRequirements(client) {
1228
1079
  if (!client) return {};
1229
1080
  try {
@@ -1242,13 +1093,13 @@ function registerSetupInstructionsTool(server, client) {
1242
1093
  "qcentriq_get_setup_instructions",
1243
1094
  {
1244
1095
  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
- },
1096
+ inputSchema: z12.object({
1097
+ preferred_manager: z12.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."),
1098
+ working_dir: z12.string().optional().describe("Directory to inspect for pyproject.toml / lockfiles / requirements.txt (defaults to the current project directory)."),
1099
+ env_name: z12.string().default("qcentriq-tests").describe("Name for the created environment (used by conda, default 'qcentriq-tests')."),
1100
+ python_version: z12.string().default("3.12").describe("Python version to request when creating the environment (default '3.12', matching the QCentriq execution container)."),
1101
+ playwright_version: z12.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.")
1102
+ }),
1252
1103
  annotations: {
1253
1104
  readOnlyHint: true,
1254
1105
  // Only probes local package managers and project files; never mutates local or remote state.
@@ -1298,6 +1149,7 @@ function registerSetupInstructionsTool(server, client) {
1298
1149
  // src/tools/index.ts
1299
1150
  function registerAllTools(server, client, config) {
1300
1151
  logger.debug("Registering QCentriq MCP tools...");
1152
+ const passingRuns = new PassingRunLedger();
1301
1153
  registerListTestsTool(server, client, config);
1302
1154
  registerGetTestTool(server, client, config);
1303
1155
  registerGetTestGroupsTool(server, client, config);
@@ -1306,38 +1158,52 @@ function registerAllTools(server, client, config) {
1306
1158
  registerRunLogsTool(server, client, config);
1307
1159
  registerAuthoringGuideTool(server, client);
1308
1160
  registerCreatePlanTool(server, client, config);
1309
- registerSaveGroupScriptTool(server, client, config);
1161
+ registerSaveGroupScriptTool(server, client, config, passingRuns);
1310
1162
  registerSaveScriptTool(server);
1311
- registerLocalRunTool(server);
1163
+ registerLocalRunTool(server, passingRuns);
1312
1164
  registerSetupInstructionsTool(server, client);
1313
- logger.info("Successfully registered 12 QCentriq MCP tools (7 remote discovery + 2 authoring + 3 local client execution).");
1165
+ logger.info("Registered QCentriq MCP tools.");
1314
1166
  }
1315
1167
 
1316
1168
  // src/version.ts
1317
1169
  import { createRequire } from "module";
1318
1170
  var PACKAGE_VERSION = createRequire(import.meta.url)("../package.json").version;
1319
1171
 
1172
+ // src/server.ts
1173
+ var SERVER_INSTRUCTIONS = `QCentriq MCP finds, runs, diagnoses and writes QCentriq Playwright tests.
1174
+
1175
+ To write a new test plan or script:
1176
+ 1. Call qcentriq_get_authoring_guide for the plan schema and script rules, and qcentriq_get_environment for the BASE_URL of the app under test.
1177
+ 2. Explore the app with the Playwright MCP server before writing anything. Start by navigating to the actual BASE_URL, then open each page under test (for example with browser_navigate), read it with browser_snapshot, and click through every flow the plan will cover. Take URLs, labels, roles and selectors from what the browser shows; do not guess them. If the Playwright MCP server is not connected, tell the user that the plan and script will be based on guesses about the app and recommend connecting it (npx @playwright/mcp@latest) before going on.
1178
+ 3. Create the plan with qcentriq_create_plan, describing only flows you saw.
1179
+ 4. Write the script using the locators you found, run it with qcentriq_run_local_test until the whole file passes, then upload it with qcentriq_save_group_script.
1180
+
1181
+ HTTP basic auth: a site behind basic auth answers 401 before any app content loads, so the page comes back blank (browser_snapshot shows nothing; browser_network_requests shows the 401). This is not the app's own login form. Do not stop there, and do not plan from the blank page:
1182
+ - Find the credentials the user defined: in their request, or in the variables from qcentriq_get_environment, either BASIC_AUTH_USERNAME and BASIC_AUTH_PASSWORD or the keys named by QCENTRIQ_BASIC_AUTH_USERNAME_KEY and QCENTRIQ_BASIC_AUTH_PASSWORD_KEY.
1183
+ - Navigate again with them in the URL, https://<username>:<password>@host/path, percent-encoding reserved characters (@ as %40, : as %3A). Playwright MCP's default Chromium browser then remembers them for that origin, so later navigations and clicks need no credentials. Then explore as usual.
1184
+ - Ask the user only if the credentials are not there, for example when they are listed only in secret_keys: QCentriq never returns secret values.
1185
+ - In the plan, note the basic-auth precondition using the environment's variable names, never the values.
1186
+ - In the script, do not put credentials in URLs or call any auth API yourself: the conftest QCentriq ships applies basic auth to every browser context from BASIC_AUTH_USERNAME and BASIC_AUTH_PASSWORD (or the keys named by QCENTRIQ_BASIC_AUTH_USERNAME_KEY and QCENTRIQ_BASIC_AUTH_PASSWORD_KEY, as in the cloud). For qcentriq_run_local_test, pass BASIC_AUTH_USERNAME and BASIC_AUTH_PASSWORD in env_vars with the values you found.`;
1187
+ function createServer(client, config) {
1188
+ const server = new McpServer({ name: "@qcentriq/mcp", version: PACKAGE_VERSION }, { instructions: SERVER_INSTRUCTIONS });
1189
+ registerAllTools(server, client, config);
1190
+ return server;
1191
+ }
1192
+
1320
1193
  // src/index.ts
1321
- async function main() {
1194
+ function main() {
1322
1195
  try {
1323
1196
  const config = loadConfig(process.argv);
1324
1197
  logger.info(`Starting QCentriq MCP Server against: ${config.baseUrl}`);
1325
1198
  const apiClient = new QCentriqApiClient(config);
1326
- const server = new McpServer({
1327
- name: "@qcentriq/mcp",
1328
- version: PACKAGE_VERSION
1329
- });
1330
- registerAllTools(server, apiClient, config);
1331
- const transport = new StdioServerTransport();
1199
+ const handle = serveStdio(() => createServer(apiClient, config));
1332
1200
  const cleanup = async () => {
1333
1201
  logger.info("Shutting down QCentriq MCP Server...");
1334
- await apiClient.close();
1335
- await server.close();
1202
+ await handle.close();
1336
1203
  process.exit(0);
1337
1204
  };
1338
1205
  process.on("SIGINT", cleanup);
1339
1206
  process.on("SIGTERM", cleanup);
1340
- await server.connect(transport);
1341
1207
  logger.info("QCentriq MCP Server is running on stdio.");
1342
1208
  } catch (err) {
1343
1209
  logger.error("Fatal error during QCentriq MCP Server startup:", err.message);