@qcentriq/mcp 0.1.0 → 0.2.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
@@ -63,10 +63,6 @@ function loadConfig(argv = process.argv) {
63
63
  };
64
64
  }
65
65
 
66
- // src/client/api.ts
67
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
68
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
69
-
70
66
  // src/utils/sanitizer.ts
71
67
  var QCENTRIQ_KEY_REGEX = /qc_[0-9a-fA-F]{30,45}/g;
72
68
  var BEARER_TOKEN_REGEX = /Bearer\s+ey[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*/g;
@@ -102,121 +98,153 @@ function sanitizePayload(value) {
102
98
  // src/client/api.ts
103
99
  var QCentriqApiClient = class {
104
100
  config;
105
- mcpClient = null;
106
- mcpTransport = null;
107
- isConnecting = false;
108
- connectPromise = null;
109
101
  constructor(config) {
110
102
  this.config = config;
111
103
  }
112
104
  /**
113
- * Connect to QCentriq's remote FastMCP SSE endpoint (/api/v1/mcp/sse).
114
- * All QCentriq backend operations are handled via this single SSE connection.
105
+ * Make an authenticated HTTP request to the QCentriq backend (/api/v1/mcp-client/...).
115
106
  */
116
- async ensureMcpConnected() {
117
- if (this.mcpClient) {
118
- return this.mcpClient;
119
- }
120
- if (this.isConnecting && this.connectPromise) {
121
- await this.connectPromise;
122
- if (this.mcpClient) return this.mcpClient;
107
+ async request(path5, params = {}) {
108
+ const cleanPath = path5.startsWith("/") ? path5 : `/${path5}`;
109
+ const url = new URL(`${this.config.baseUrl}/api/v1/mcp-client${cleanPath}`);
110
+ for (const [key, value] of Object.entries(params)) {
111
+ if (value !== void 0 && value !== null) {
112
+ url.searchParams.set(key, String(value));
113
+ }
123
114
  }
124
- this.isConnecting = true;
125
- this.connectPromise = (async () => {
115
+ logger.debug(`[mcp-client] HTTP GET ${url.toString()}`);
116
+ const res = await fetch(url.toString(), {
117
+ method: "GET",
118
+ headers: {
119
+ Authorization: `Bearer ${this.config.apiKey}`,
120
+ Accept: "application/json"
121
+ }
122
+ });
123
+ if (!res.ok) {
124
+ let errorDetail = res.statusText;
126
125
  try {
127
- const sseUrl = new URL(`${this.config.baseUrl}/api/v1/mcp/sse`);
128
- sseUrl.searchParams.set("token", this.config.apiKey);
129
- logger.debug(`Connecting via SSEClientTransport to: ${sseUrl.toString()}`);
130
- this.mcpTransport = new SSEClientTransport(sseUrl, {
131
- requestInit: {
132
- headers: {
133
- Authorization: `Bearer ${this.config.apiKey}`
134
- }
135
- }
136
- });
137
- this.mcpClient = new Client(
138
- {
139
- name: "qcentriq-mcp-cli",
140
- version: "1.0.0"
141
- },
142
- {
143
- capabilities: {}
144
- }
145
- );
146
- await this.mcpClient.connect(this.mcpTransport);
147
- logger.info("Connected to QCentriq backend /api/v1/mcp/sse successfully.");
148
- } catch (err) {
149
- logger.error(`Failed to connect to QCentriq MCP SSE: ${err.message}`);
150
- this.mcpClient = null;
151
- this.mcpTransport = null;
152
- throw new Error(`Could not connect to QCentriq MCP endpoint: ${err.message}`);
153
- } finally {
154
- this.isConnecting = false;
155
- }
156
- })();
157
- await this.connectPromise;
158
- if (!this.mcpClient) {
159
- throw new Error("Failed to initialize MCP client.");
126
+ const errorJson = await res.json();
127
+ errorDetail = errorJson.detail || JSON.stringify(errorJson);
128
+ } catch {
129
+ const text = await res.text();
130
+ if (text) errorDetail = text;
131
+ }
132
+ throw new Error(`API error (${res.status}): ${errorDetail}`);
160
133
  }
161
- return this.mcpClient;
134
+ const data = await res.json();
135
+ return sanitizePayload(data);
162
136
  }
163
137
  /**
164
- * Retrieve list of tools exposed by QCentriq backend over /api/v1/mcp/sse.
165
- */
166
- async listRemoteTools() {
167
- const client = await this.ensureMcpConnected();
168
- const result = await client.listTools();
169
- return result.tools || [];
170
- }
171
- /**
172
- * Invoke a remote tool on the QCentriq backend via /api/v1/mcp/sse.
138
+ * Invoke remote tool via /api/v1/mcp-client REST endpoints and wrap
139
+ * response in standard MCP CallToolResult format.
173
140
  */
174
141
  async callRemoteTool(toolName, args) {
175
- const client = await this.ensureMcpConnected();
176
142
  logger.debug(`Invoking remote tool "${toolName}" with arguments:`, args);
177
- try {
178
- const response = await client.callTool({
179
- name: toolName,
180
- arguments: args
181
- });
182
- return sanitizePayload(response);
183
- } catch (err) {
184
- logger.error(`Error calling remote tool "${toolName}":`, err.message);
185
- if (err.message?.includes("closed") || err.message?.includes("disconnect")) {
186
- this.mcpClient = null;
187
- this.mcpTransport = null;
188
- }
189
- throw err;
143
+ let data;
144
+ switch (toolName) {
145
+ case "qcentriq_list_tests": {
146
+ const { project_id, group_id, priority, test_type, limit, offset } = args;
147
+ data = await this.request("/tests", {
148
+ project_id,
149
+ group_id,
150
+ priority,
151
+ test_type,
152
+ limit,
153
+ offset
154
+ });
155
+ break;
156
+ }
157
+ case "qcentriq_get_test": {
158
+ const { test_case_id, project_id } = args;
159
+ data = await this.request(`/tests/${test_case_id}`, { project_id });
160
+ break;
161
+ }
162
+ case "qcentriq_get_test_groups": {
163
+ const { project_id, group_id, limit, offset } = args;
164
+ data = await this.request("/groups", {
165
+ project_id,
166
+ group_id,
167
+ limit,
168
+ offset
169
+ });
170
+ break;
171
+ }
172
+ case "qcentriq_download_script": {
173
+ const { group_id, project_id, include_fixtures } = args;
174
+ data = await this.request(`/groups/${group_id}/script`, {
175
+ project_id,
176
+ include_fixtures
177
+ });
178
+ break;
179
+ }
180
+ case "qcentriq_get_environment": {
181
+ const { project_id, environment_id, environment_name, include_secrets } = args;
182
+ data = await this.request("/environment", {
183
+ project_id,
184
+ environment_id,
185
+ environment_name,
186
+ include_secrets
187
+ });
188
+ break;
189
+ }
190
+ case "qcentriq_get_test_run_logs": {
191
+ const {
192
+ test_case_id,
193
+ project_id,
194
+ run_id,
195
+ status,
196
+ latest_only,
197
+ from_date,
198
+ to_date,
199
+ limit,
200
+ offset
201
+ } = args;
202
+ data = await this.request(`/tests/${test_case_id}/run-logs`, {
203
+ project_id,
204
+ run_id,
205
+ status,
206
+ latest_only,
207
+ from_date,
208
+ to_date,
209
+ limit,
210
+ offset
211
+ });
212
+ break;
213
+ }
214
+ default:
215
+ throw new Error(`Unknown tool: ${toolName}`);
190
216
  }
217
+ return {
218
+ content: [
219
+ {
220
+ type: "text",
221
+ text: JSON.stringify(data, null, 2)
222
+ }
223
+ ]
224
+ };
191
225
  }
192
226
  /**
193
- * Close the SSE connection on shutdown.
227
+ * Close client session on shutdown (no-op for stateless HTTP client).
194
228
  */
195
229
  async close() {
196
- if (this.mcpClient) {
197
- try {
198
- await this.mcpClient.close();
199
- } catch {
200
- }
201
- this.mcpClient = null;
202
- this.mcpTransport = null;
203
- }
204
230
  }
205
231
  };
206
232
 
207
233
  // src/tools/list-tests.ts
208
234
  import { z } from "zod";
209
235
  function registerListTestsTool(server, client, config) {
210
- server.tool(
236
+ server.registerTool(
211
237
  "qcentriq_list_tests",
212
- "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.",
213
238
  {
214
- project_id: z.string().uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
215
- group_id: z.string().uuid().optional().describe("Optional test group UUID filter."),
216
- priority: z.enum(["low", "medium", "high", "critical"]).optional().describe("Filter by priority."),
217
- test_type: z.enum(["web", "api", "mobile"]).optional().describe("Filter by test type."),
218
- limit: z.number().int().min(1).max(100).default(50).describe("Max number of test cases to return (default 50)."),
219
- offset: z.number().int().min(0).default(0).describe("Pagination offset.")
239
+ 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.",
240
+ inputSchema: {
241
+ project_id: z.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
242
+ group_id: z.uuid().optional().describe("Optional test group UUID filter."),
243
+ priority: z.enum(["low", "medium", "high", "critical"]).optional().describe("Filter by priority."),
244
+ test_type: z.enum(["web", "api", "mobile"]).optional().describe("Filter by test type."),
245
+ limit: z.number().int().min(1).max(100).default(50).describe("Max number of test cases to return (default 50)."),
246
+ offset: z.number().int().min(0).default(0).describe("Pagination offset.")
247
+ }
220
248
  },
221
249
  async (args) => {
222
250
  try {
@@ -239,12 +267,14 @@ function registerListTestsTool(server, client, config) {
239
267
  // src/tools/get-test.ts
240
268
  import { z as z2 } from "zod";
241
269
  function registerGetTestTool(server, client, config) {
242
- server.tool(
270
+ server.registerTool(
243
271
  "qcentriq_get_test",
244
- "Retrieve detailed test case information including step definitions, preconditions, latest execution diagnostics, error stack traces, and parent test group script metadata.",
245
272
  {
246
- test_case_id: z2.string().uuid().describe("UUID of the target test case."),
247
- project_id: z2.string().uuid().optional().describe("Optional project UUID (inferred from API key if omitted).")
273
+ description: "Retrieve detailed test case information including step definitions, preconditions, latest execution diagnostics, error stack traces, and parent test group script metadata.",
274
+ inputSchema: {
275
+ test_case_id: z2.uuid().describe("UUID of the target test case."),
276
+ project_id: z2.uuid().optional().describe("Optional project UUID (inferred from API key if omitted).")
277
+ }
248
278
  },
249
279
  async (args) => {
250
280
  try {
@@ -267,14 +297,16 @@ function registerGetTestTool(server, client, config) {
267
297
  // src/tools/get-groups.ts
268
298
  import { z as z3 } from "zod";
269
299
  function registerGetTestGroupsTool(server, client, config) {
270
- server.tool(
300
+ server.registerTool(
271
301
  "qcentriq_get_test_groups",
272
- "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.",
273
302
  {
274
- project_id: z3.string().uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
275
- group_id: z3.string().uuid().optional().describe("Optional test group UUID filter to inspect a specific group."),
276
- limit: z3.number().int().min(1).max(100).default(50).describe("Max test groups to return (default 50)."),
277
- offset: z3.number().int().min(0).default(0).describe("Pagination offset.")
303
+ 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.",
304
+ inputSchema: {
305
+ project_id: z3.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
306
+ group_id: z3.uuid().optional().describe("Optional test group UUID filter to inspect a specific group."),
307
+ limit: z3.number().int().min(1).max(100).default(50).describe("Max test groups to return (default 50)."),
308
+ offset: z3.number().int().min(0).default(0).describe("Pagination offset.")
309
+ }
278
310
  },
279
311
  async (args) => {
280
312
  try {
@@ -299,15 +331,17 @@ import { z as z4 } from "zod";
299
331
  import * as fs from "fs/promises";
300
332
  import * as path from "path";
301
333
  function registerDownloadScriptTool(server, client, config) {
302
- server.tool(
334
+ server.registerTool(
303
335
  "qcentriq_download_script",
304
- "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.",
305
336
  {
306
- group_id: z4.string().uuid().describe("UUID of the target test group."),
307
- project_id: z4.string().uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
308
- include_fixtures: z4.boolean().default(true).describe("Whether to retrieve accompanying conftest.py / fixtures (default True)."),
309
- save_to_disk: z4.boolean().default(false).describe("If true, saves the downloaded test script and fixtures directly to the local filesystem."),
310
- destination_dir: z4.string().default("./tests").describe("Destination directory when save_to_disk is true (defaults to ./tests).")
337
+ 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.",
338
+ inputSchema: {
339
+ group_id: z4.uuid().describe("UUID of the target test group."),
340
+ project_id: z4.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
341
+ include_fixtures: z4.boolean().default(true).describe("Whether to retrieve accompanying conftest.py / fixtures (default True)."),
342
+ save_to_disk: z4.boolean().default(false).describe("If true, saves the downloaded test script and fixtures directly to the local filesystem."),
343
+ destination_dir: z4.string().default("./tests").describe("Destination directory when save_to_disk is true (defaults to ./tests).")
344
+ }
311
345
  },
312
346
  async (args) => {
313
347
  try {
@@ -367,14 +401,16 @@ function registerDownloadScriptTool(server, client, config) {
367
401
  // src/tools/environment.ts
368
402
  import { z as z5 } from "zod";
369
403
  function registerEnvironmentTool(server, client, config) {
370
- server.tool(
404
+ server.registerTool(
371
405
  "qcentriq_get_environment",
372
- "Retrieve target test environment configuration, base URL (BASE_URL), environment variables, and secrets for local test execution.",
373
406
  {
374
- project_id: z5.string().uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
375
- environment_id: z5.string().uuid().optional().describe("Optional specific environment UUID."),
376
- environment_name: z5.string().optional().describe("Optional environment name filter (e.g. 'staging', 'dev', 'production')."),
377
- include_secrets: z5.boolean().default(false).describe("Whether to include decrypted secret values for runtime injection (default False).")
407
+ description: "Retrieve target test environment configuration, base URL (BASE_URL), environment variables, and secrets for local test execution.",
408
+ inputSchema: {
409
+ project_id: z5.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
410
+ environment_id: z5.uuid().optional().describe("Optional specific environment UUID."),
411
+ environment_name: z5.string().optional().describe("Optional environment name filter (e.g. 'staging', 'dev', 'production')."),
412
+ include_secrets: z5.boolean().default(false).describe("Whether to include decrypted secret values for runtime injection (default False).")
413
+ }
378
414
  },
379
415
  async (args) => {
380
416
  try {
@@ -397,19 +433,21 @@ function registerEnvironmentTool(server, client, config) {
397
433
  // src/tools/run-logs.ts
398
434
  import { z as z6 } from "zod";
399
435
  function registerRunLogsTool(server, client, config) {
400
- server.tool(
436
+ server.registerTool(
401
437
  "qcentriq_get_test_run_logs",
402
- "Retrieve execution history and logs for a test case: per-run status, timing, error message, stack trace, and raw output logs across runs.",
403
438
  {
404
- test_case_id: z6.string().uuid().describe("UUID of the target test case."),
405
- project_id: z6.string().uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
406
- run_id: z6.string().uuid().optional().describe("Optional specific run UUID to fetch a single run's full log."),
407
- status: z6.enum(["failed", "passed", "error"]).optional().describe("Filter by result status."),
408
- latest_only: z6.boolean().default(false).describe("If True, returns only the most recent matching run."),
409
- from_date: z6.string().optional().describe("Optional ISO-8601 start date filter."),
410
- to_date: z6.string().optional().describe("Optional ISO-8601 end date filter."),
411
- limit: z6.number().int().min(1).max(100).default(20).describe("Max runs to return."),
412
- offset: z6.number().int().min(0).default(0).describe("Pagination offset.")
439
+ description: "Retrieve execution history and logs for a test case: per-run status, timing, error message, stack trace, and raw output logs across runs.",
440
+ inputSchema: {
441
+ test_case_id: z6.uuid().describe("UUID of the target test case."),
442
+ project_id: z6.uuid().optional().describe("Optional project UUID (inferred from API key if omitted)."),
443
+ run_id: z6.uuid().optional().describe("Optional specific run UUID to fetch a single run's full log."),
444
+ status: z6.enum(["failed", "passed", "error"]).optional().describe("Filter by result status."),
445
+ latest_only: z6.boolean().default(false).describe("If True, returns only the most recent matching run."),
446
+ from_date: z6.string().optional().describe("Optional ISO-8601 start date filter."),
447
+ to_date: z6.string().optional().describe("Optional ISO-8601 end date filter."),
448
+ limit: z6.number().int().min(1).max(100).default(20).describe("Max runs to return."),
449
+ offset: z6.number().int().min(0).default(0).describe("Pagination offset.")
450
+ }
413
451
  },
414
452
  async (args) => {
415
453
  try {
@@ -487,7 +525,7 @@ async function runLocalPytest(params) {
487
525
  }
488
526
  const fullCommand = `${cmd} ${args.join(" ")}`;
489
527
  logger.info(`Running local test command: ${fullCommand} in ${cwd}`);
490
- return new Promise((resolve4) => {
528
+ return new Promise((resolve5) => {
491
529
  let stdout = "";
492
530
  let stderr = "";
493
531
  let finished = false;
@@ -501,7 +539,7 @@ async function runLocalPytest(params) {
501
539
  if (!finished) {
502
540
  finished = true;
503
541
  killProcessTree(child);
504
- resolve4({
542
+ resolve5({
505
543
  passed: false,
506
544
  exitCode: -1,
507
545
  stdout,
@@ -537,7 +575,7 @@ async function runLocalPytest(params) {
537
575
  if (!fbFinished) {
538
576
  fbFinished = true;
539
577
  killProcessTree(fallbackChild);
540
- resolve4({
578
+ resolve5({
541
579
  passed: false,
542
580
  exitCode: -1,
543
581
  stdout: fbStdout,
@@ -554,7 +592,7 @@ async function runLocalPytest(params) {
554
592
  if (fbFinished) return;
555
593
  fbFinished = true;
556
594
  clearTimeout(fbTimer);
557
- resolve4({
595
+ resolve5({
558
596
  passed: code === 0,
559
597
  exitCode: code ?? -1,
560
598
  stdout: fbStdout,
@@ -567,7 +605,7 @@ async function runLocalPytest(params) {
567
605
  if (fbFinished) return;
568
606
  fbFinished = true;
569
607
  clearTimeout(fbTimer);
570
- resolve4({
608
+ resolve5({
571
609
  passed: false,
572
610
  exitCode: -1,
573
611
  stdout: "",
@@ -578,7 +616,7 @@ async function runLocalPytest(params) {
578
616
  });
579
617
  return;
580
618
  }
581
- resolve4({
619
+ resolve5({
582
620
  passed: false,
583
621
  exitCode: -1,
584
622
  stdout,
@@ -592,7 +630,7 @@ async function runLocalPytest(params) {
592
630
  finished = true;
593
631
  clearTimeout(timer);
594
632
  const durationMs = Date.now() - startTime;
595
- resolve4({
633
+ resolve5({
596
634
  passed: code === 0,
597
635
  exitCode: code ?? -1,
598
636
  stdout,
@@ -606,19 +644,21 @@ async function runLocalPytest(params) {
606
644
 
607
645
  // src/tools/local-run.ts
608
646
  function registerLocalRunTool(server) {
609
- server.tool(
647
+ server.registerTool(
610
648
  "qcentriq_run_local_test",
611
- "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.",
612
649
  {
613
- file_path: z7.string().describe("Path to the local test file to run (e.g. 'tests/test_login.py')."),
614
- test_name: z7.string().optional().describe("Optional specific test function name or expression to run (passed to pytest -k)."),
615
- headless: z7.boolean().default(true).describe("Whether to run the browser in headless mode (default True). Set False to watch the browser execution live."),
616
- browser: z7.enum(["chromium", "firefox", "webkit"]).default("chromium").describe("Browser engine to execute against (default 'chromium')."),
617
- base_url: z7.string().url().optional().describe("Target application base URL (e.g. from qcentriq_get_environment). Injected as BASE_URL env var."),
618
- env_vars: z7.record(z7.string(), z7.string()).optional().describe("Environment variables to inject into the local test process."),
619
- extra_args: z7.array(z7.string()).optional().describe("Additional CLI arguments to pass to pytest (e.g. ['-s', '--alluredir=allure-results'])."),
620
- timeout_seconds: z7.number().int().min(5).max(300).default(60).describe("Timeout in seconds for test execution (default 60)."),
621
- working_dir: z7.string().optional().describe("Working directory to run pytest in (defaults to current project directory).")
650
+ 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.",
651
+ inputSchema: {
652
+ file_path: z7.string().describe("Path to the local test file to run (e.g. 'tests/test_login.py')."),
653
+ test_name: z7.string().optional().describe("Optional specific test function name or expression to run (passed to pytest -k)."),
654
+ headless: z7.boolean().default(true).describe("Whether to run the browser in headless mode (default True). Set False to watch the browser execution live."),
655
+ browser: z7.enum(["chromium", "firefox", "webkit"]).default("chromium").describe("Browser engine to execute against (default 'chromium')."),
656
+ base_url: z7.url().optional().describe("Target application base URL (e.g. from qcentriq_get_environment). Injected as BASE_URL env var."),
657
+ env_vars: z7.record(z7.string(), z7.string()).optional().describe("Environment variables to inject into the local test process."),
658
+ extra_args: z7.array(z7.string()).optional().describe("Additional CLI arguments to pass to pytest (e.g. ['-s', '--alluredir=allure-results'])."),
659
+ timeout_seconds: z7.number().int().min(5).max(300).default(60).describe("Timeout in seconds for test execution (default 60)."),
660
+ working_dir: z7.string().optional().describe("Working directory to run pytest in (defaults to current project directory).")
661
+ }
622
662
  },
623
663
  async (args) => {
624
664
  try {
@@ -674,14 +714,16 @@ import { z as z8 } from "zod";
674
714
  import * as fs2 from "fs/promises";
675
715
  import * as path3 from "path";
676
716
  function registerSaveScriptTool(server) {
677
- server.tool(
717
+ server.registerTool(
678
718
  "qcentriq_save_script",
679
- "Save downloaded Playwright Python test script and fixtures directly to the local workspace disk so they can be run or edited locally.",
680
719
  {
681
- file_name: z8.string().describe("Target filename (e.g. 'test_login.py')."),
682
- content: z8.string().describe("Python test script source code."),
683
- conftest_content: z8.string().optional().describe("Accompanying conftest.py source code if present."),
684
- destination_dir: z8.string().default("./tests").describe("Destination directory in the local workspace (default './tests').")
720
+ description: "Save downloaded Playwright Python test script and fixtures directly to the local workspace disk so they can be run or edited locally.",
721
+ inputSchema: {
722
+ file_name: z8.string().describe("Target filename (e.g. 'test_login.py')."),
723
+ content: z8.string().describe("Python test script source code."),
724
+ conftest_content: z8.string().optional().describe("Accompanying conftest.py source code if present."),
725
+ destination_dir: z8.string().default("./tests").describe("Destination directory in the local workspace (default './tests').")
726
+ }
685
727
  },
686
728
  async (args) => {
687
729
  try {
@@ -736,6 +778,339 @@ function registerSaveScriptTool(server) {
736
778
  );
737
779
  }
738
780
 
781
+ // src/tools/setup-instructions.ts
782
+ import { z as z9 } from "zod";
783
+
784
+ // src/local/environment-setup.ts
785
+ import { spawn as spawn2 } from "child_process";
786
+ import * as fs3 from "fs/promises";
787
+ import * as path4 from "path";
788
+ var MANAGER_PRIORITY = ["uv", "poetry", "conda", "venv"];
789
+ var PROBE_TIMEOUT_MS = 5e3;
790
+ var DEFAULT_PYTHON_VERSION = "3.12";
791
+ var DEFAULT_PLAYWRIGHT_VERSION = "1.56.0";
792
+ function testDependencies(playwrightVersion) {
793
+ return [
794
+ "pytest",
795
+ "pytest-playwright",
796
+ `playwright==${playwrightVersion}`,
797
+ "allure-pytest",
798
+ "httpx",
799
+ "nest-asyncio",
800
+ "pytest-playwright-visual-snapshot",
801
+ "Pillow"
802
+ ].join(" ");
803
+ }
804
+ function probeCommand(cmd, args) {
805
+ return new Promise((resolve5) => {
806
+ let output = "";
807
+ let settled = false;
808
+ const finish = (value) => {
809
+ if (settled) return;
810
+ settled = true;
811
+ clearTimeout(timer);
812
+ resolve5(value);
813
+ };
814
+ let child;
815
+ try {
816
+ child = spawn2(cmd, args, {
817
+ stdio: ["ignore", "pipe", "pipe"],
818
+ shell: process.platform === "win32"
819
+ });
820
+ } catch {
821
+ resolve5(null);
822
+ return;
823
+ }
824
+ const timer = setTimeout(() => {
825
+ try {
826
+ child.kill("SIGKILL");
827
+ } catch {
828
+ }
829
+ finish(null);
830
+ }, PROBE_TIMEOUT_MS);
831
+ child.stdout?.on("data", (chunk) => output += chunk.toString());
832
+ child.stderr?.on("data", (chunk) => output += chunk.toString());
833
+ child.on("error", () => finish(null));
834
+ child.on("close", (code) => finish(code === 0 ? output.trim().split("\n")[0].trim() || "unknown" : null));
835
+ });
836
+ }
837
+ async function probePython() {
838
+ for (const bin of ["python3", "python"]) {
839
+ const version = await probeCommand(bin, ["-c", "import venv, sys; print(sys.version.split()[0])"]);
840
+ if (version) {
841
+ return { bin, version };
842
+ }
843
+ }
844
+ return null;
845
+ }
846
+ async function fileExists(filePath) {
847
+ try {
848
+ await fs3.access(filePath);
849
+ return true;
850
+ } catch {
851
+ return false;
852
+ }
853
+ }
854
+ async function detectProjectFiles(workingDir) {
855
+ const candidates = [
856
+ "pyproject.toml",
857
+ "uv.lock",
858
+ "poetry.lock",
859
+ "requirements.txt",
860
+ "environment.yml",
861
+ "environment.yaml"
862
+ ];
863
+ const found = [];
864
+ for (const candidate of candidates) {
865
+ if (await fileExists(path4.join(workingDir, candidate))) {
866
+ found.push(candidate);
867
+ }
868
+ }
869
+ return found;
870
+ }
871
+ async function detectPackageManagers() {
872
+ const [uv, poetry, conda, python] = await Promise.all([
873
+ probeCommand("uv", ["--version"]),
874
+ probeCommand("poetry", ["--version"]),
875
+ probeCommand("conda", ["--version"]),
876
+ probePython()
877
+ ]);
878
+ return [
879
+ { name: "uv", available: Boolean(uv), version: uv ?? void 0, probe_command: "uv --version" },
880
+ { name: "poetry", available: Boolean(poetry), version: poetry ?? void 0, probe_command: "poetry --version" },
881
+ { name: "conda", available: Boolean(conda), version: conda ?? void 0, probe_command: "conda --version" },
882
+ {
883
+ name: "venv",
884
+ available: Boolean(python),
885
+ version: python ? `${python.bin} ${python.version}` : void 0,
886
+ probe_command: "python3 -m venv"
887
+ }
888
+ ];
889
+ }
890
+ function activateCommand(ctx) {
891
+ return ctx.isWindows ? ".venv\\Scripts\\activate" : "source .venv/bin/activate";
892
+ }
893
+ function buildUvSteps(ctx) {
894
+ const deps = testDependencies(ctx.playwrightVersion);
895
+ if (ctx.projectFiles.includes("uv.lock")) {
896
+ return [
897
+ { description: "Install the project's locked dependencies into a uv-managed virtualenv.", command: "uv sync" },
898
+ { description: "Add the QCentriq test dependencies if they are not already in pyproject.toml.", command: `uv add --dev ${deps}` },
899
+ { description: "Download the Playwright browser binaries.", command: "uv run playwright install chromium" }
900
+ ];
901
+ }
902
+ const steps = [
903
+ { description: "Create a virtual environment in .venv.", command: `uv venv .venv --python ${ctx.pythonVersion}` },
904
+ { description: "Activate the virtual environment.", command: activateCommand(ctx) }
905
+ ];
906
+ if (ctx.projectFiles.includes("requirements.txt")) {
907
+ steps.push({ description: "Install the project's existing dependencies.", command: "uv pip install -r requirements.txt" });
908
+ }
909
+ steps.push(
910
+ { description: "Install the QCentriq test dependencies (pytest, Playwright, Allure, and fixtures).", command: `uv pip install ${deps}` },
911
+ { description: "Download the Playwright browser binaries.", command: "playwright install chromium" }
912
+ );
913
+ return steps;
914
+ }
915
+ function buildPoetrySteps(ctx) {
916
+ const deps = testDependencies(ctx.playwrightVersion);
917
+ const steps = [
918
+ {
919
+ description: "Keep the virtualenv inside the project so qcentriq_run_local_test can find it.",
920
+ command: "poetry config virtualenvs.in-project true"
921
+ }
922
+ ];
923
+ if (!ctx.projectFiles.includes("pyproject.toml")) {
924
+ steps.push({
925
+ description: "Initialize a pyproject.toml for this test project.",
926
+ command: `poetry init --no-interaction --python ">=${ctx.pythonVersion}"`
927
+ });
928
+ }
929
+ steps.push(
930
+ { description: "Add the QCentriq test dependencies (pytest, Playwright, Allure, and fixtures) as dev dependencies.", command: `poetry add --group dev ${deps}` },
931
+ { description: "Install the environment.", command: "poetry install" },
932
+ { description: "Download the Playwright browser binaries.", command: "poetry run playwright install chromium" },
933
+ { description: "Activate the environment for your shell session.", command: activateCommand(ctx) }
934
+ );
935
+ return steps;
936
+ }
937
+ function buildCondaSteps(ctx) {
938
+ const deps = testDependencies(ctx.playwrightVersion);
939
+ const envFile = ctx.projectFiles.find((f) => f === "environment.yml" || f === "environment.yaml");
940
+ const steps = envFile ? [{ description: "Create the conda environment from the project's environment file.", command: `conda env create -f ${envFile}` }] : [
941
+ {
942
+ description: "Create a dedicated conda environment for QCentriq tests.",
943
+ command: `conda create -n ${ctx.envName} python=${ctx.pythonVersion} -y`
944
+ }
945
+ ];
946
+ steps.push(
947
+ { description: "Activate the conda environment.", command: `conda activate ${ctx.envName}` },
948
+ { description: "Install the QCentriq test dependencies (pytest, Playwright, Allure, and fixtures).", command: `pip install ${deps}` },
949
+ { description: "Download the Playwright browser binaries.", command: "playwright install chromium" }
950
+ );
951
+ return steps;
952
+ }
953
+ function buildVenvSteps(ctx) {
954
+ const deps = testDependencies(ctx.playwrightVersion);
955
+ const steps = [
956
+ { description: "Create a virtual environment in .venv.", command: "python3 -m venv .venv" },
957
+ { description: "Activate the virtual environment.", command: activateCommand(ctx) },
958
+ { description: "Upgrade pip inside the environment.", command: "python -m pip install --upgrade pip" }
959
+ ];
960
+ if (ctx.projectFiles.includes("requirements.txt")) {
961
+ steps.push({ description: "Install the project's existing dependencies.", command: "pip install -r requirements.txt" });
962
+ }
963
+ steps.push(
964
+ { description: "Install the QCentriq test dependencies (pytest, Playwright, Allure, and fixtures).", command: `pip install ${deps}` },
965
+ { description: "Download the Playwright browser binaries.", command: "playwright install chromium" }
966
+ );
967
+ return steps;
968
+ }
969
+ var STEP_BUILDERS = {
970
+ uv: buildUvSteps,
971
+ poetry: buildPoetrySteps,
972
+ conda: buildCondaSteps,
973
+ venv: buildVenvSteps
974
+ };
975
+ var VERIFY_COMMANDS = {
976
+ uv: "pytest --version",
977
+ poetry: "poetry run pytest --version",
978
+ conda: "pytest --version",
979
+ venv: "pytest --version"
980
+ };
981
+ var INSTALL_HINTS = {
982
+ uv: "uv: https://docs.astral.sh/uv/getting-started/installation/",
983
+ poetry: "poetry: https://python-poetry.org/docs/#installation",
984
+ conda: "conda (miniconda): https://docs.conda.io/projects/miniconda/en/latest/",
985
+ venv: "python3 with the venv module: https://www.python.org/downloads/"
986
+ };
987
+ function detectActiveEnvironment() {
988
+ if (process.env.VIRTUAL_ENV) {
989
+ return `virtualenv: ${process.env.VIRTUAL_ENV}`;
990
+ }
991
+ if (process.env.CONDA_DEFAULT_ENV) {
992
+ return `conda: ${process.env.CONDA_DEFAULT_ENV}`;
993
+ }
994
+ return null;
995
+ }
996
+ async function buildEnvironmentSetupPlan(params = {}) {
997
+ const workingDir = params.workingDir ? path4.resolve(params.workingDir) : process.cwd();
998
+ const [packageManagers, projectFiles] = await Promise.all([detectPackageManagers(), detectProjectFiles(workingDir)]);
999
+ const availability = new Map(packageManagers.map((m) => [m.name, m.available]));
1000
+ const preferred = params.preferredManager;
1001
+ const notes = [];
1002
+ let recommended = null;
1003
+ if (preferred && availability.get(preferred)) {
1004
+ recommended = preferred;
1005
+ } else {
1006
+ if (preferred) {
1007
+ notes.push(`Requested package manager "${preferred}" was not found on PATH; falling back to the best available option.`);
1008
+ }
1009
+ recommended = MANAGER_PRIORITY.find((name) => availability.get(name)) ?? null;
1010
+ }
1011
+ const ctx = {
1012
+ workingDir,
1013
+ isWindows: process.platform === "win32",
1014
+ envName: params.envName || "qcentriq-tests",
1015
+ pythonVersion: params.pythonVersion || DEFAULT_PYTHON_VERSION,
1016
+ playwrightVersion: params.playwrightVersion || DEFAULT_PLAYWRIGHT_VERSION,
1017
+ projectFiles
1018
+ };
1019
+ const activeEnvironment = detectActiveEnvironment();
1020
+ if (activeEnvironment) {
1021
+ notes.push(`An environment is already active (${activeEnvironment}). Reuse it instead of creating a new one if it already has pytest and playwright installed.`);
1022
+ }
1023
+ let steps = [];
1024
+ let verifyCommand = null;
1025
+ if (recommended) {
1026
+ steps = STEP_BUILDERS[recommended](ctx);
1027
+ verifyCommand = VERIFY_COMMANDS[recommended];
1028
+ if (recommended !== "uv" && availability.get("uv")) {
1029
+ notes.push("uv is also available on this machine and is recommended over other package managers for faster, more reliable installs. Pass preferred_manager to override this choice.");
1030
+ }
1031
+ const alternatives = MANAGER_PRIORITY.filter((name) => name !== recommended && availability.get(name));
1032
+ if (alternatives.length > 0) {
1033
+ notes.push(`Also available on this machine: ${alternatives.join(", ")}. Re-run this tool with preferred_manager to get instructions for one of them.`);
1034
+ }
1035
+ } else {
1036
+ notes.push("No supported Python package manager was found on PATH. Install one of the following, then run this tool again:");
1037
+ for (const name of MANAGER_PRIORITY) {
1038
+ notes.push(` - ${INSTALL_HINTS[name]}`);
1039
+ }
1040
+ }
1041
+ notes.push(
1042
+ "Run these commands in a terminal from the working directory below \u2014 this tool returns instructions only and does not create the environment for you.",
1043
+ "qcentriq_run_local_test resolves pytest from the VIRTUAL_ENV the MCP server was launched with, then falls back to pytest on PATH. After creating a new environment, restart your MCP client (Claude Desktop, Cursor, ...) from an activated shell so local runs pick it up."
1044
+ );
1045
+ logger.debug(`Environment setup plan: recommended=${recommended ?? "none"}, project files=[${projectFiles.join(", ")}]`);
1046
+ return {
1047
+ working_dir: workingDir,
1048
+ package_managers: packageManagers,
1049
+ recommended_manager: recommended,
1050
+ active_environment: activeEnvironment,
1051
+ detected_project_files: projectFiles,
1052
+ steps,
1053
+ verify_command: verifyCommand,
1054
+ notes
1055
+ };
1056
+ }
1057
+
1058
+ // src/tools/setup-instructions.ts
1059
+ function registerSetupInstructionsTool(server) {
1060
+ server.registerTool(
1061
+ "qcentriq_get_setup_instructions",
1062
+ {
1063
+ 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. Returns instructions only \u2014 it does not create the environment.",
1064
+ inputSchema: {
1065
+ preferred_manager: z9.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."),
1066
+ working_dir: z9.string().optional().describe("Directory to inspect for pyproject.toml / lockfiles / requirements.txt (defaults to the current project directory)."),
1067
+ env_name: z9.string().default("qcentriq-tests").describe("Name for the created environment (used by conda, default 'qcentriq-tests')."),
1068
+ python_version: z9.string().default("3.12").describe("Python version to request when creating the environment (default '3.12', matching the QCentriq execution container)."),
1069
+ playwright_version: z9.string().default("1.56.0").describe("Playwright version to pin when installing test dependencies (default '1.56.0', matching the QCentriq execution container).")
1070
+ },
1071
+ annotations: {
1072
+ readOnlyHint: true,
1073
+ // Only probes local package managers and project files; never mutates local or remote state.
1074
+ destructiveHint: false,
1075
+ idempotentHint: false,
1076
+ // Machine state (installed tooling) can change between calls.
1077
+ openWorldHint: false
1078
+ // Fixed set of local package managers, not open-ended.
1079
+ }
1080
+ },
1081
+ async (args) => {
1082
+ try {
1083
+ const plan = await buildEnvironmentSetupPlan({
1084
+ preferredManager: args.preferred_manager,
1085
+ workingDir: args.working_dir,
1086
+ envName: args.env_name,
1087
+ pythonVersion: args.python_version,
1088
+ playwrightVersion: args.playwright_version
1089
+ });
1090
+ return {
1091
+ content: [
1092
+ {
1093
+ type: "text",
1094
+ text: JSON.stringify(plan, null, 2)
1095
+ }
1096
+ ],
1097
+ isError: plan.recommended_manager === null
1098
+ };
1099
+ } catch (err) {
1100
+ return {
1101
+ isError: true,
1102
+ content: [
1103
+ {
1104
+ type: "text",
1105
+ text: `Error in qcentriq_get_setup_instructions: ${err.message}`
1106
+ }
1107
+ ]
1108
+ };
1109
+ }
1110
+ }
1111
+ );
1112
+ }
1113
+
739
1114
  // src/tools/index.ts
740
1115
  function registerAllTools(server, client, config) {
741
1116
  logger.debug("Registering QCentriq MCP tools...");
@@ -747,7 +1122,8 @@ function registerAllTools(server, client, config) {
747
1122
  registerRunLogsTool(server, client, config);
748
1123
  registerSaveScriptTool(server);
749
1124
  registerLocalRunTool(server);
750
- logger.info("Successfully registered 8 QCentriq MCP tools (6 remote discovery + 2 local client execution).");
1125
+ registerSetupInstructionsTool(server);
1126
+ logger.info("Successfully registered 9 QCentriq MCP tools (6 remote discovery + 3 local client execution).");
751
1127
  }
752
1128
 
753
1129
  // src/index.ts