@validate.qa/mcp 1.0.0 → 1.1.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/init.ts","../src/index.ts","../src/config.ts","../src/api-client.ts","../src/tools/index.ts"],"sourcesContent":["/**\n * `npx @validate.qa/mcp init` — one-command MCP setup for all supported IDEs.\n *\n * Creates/updates MCP config files so the user never has to manually edit JSON.\n * Detects which IDEs are present and writes the appropriate config for each.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { resolve, join } from 'path';\n\ninterface InitArgs {\n apiUrl: string;\n token: string;\n projectId: string;\n}\n\nfunction parseInitArgs(argv: string[]): InitArgs {\n const args: Record<string, string> = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg.startsWith('--') && i + 1 < argv.length) {\n args[arg.slice(2)] = argv[++i];\n }\n }\n\n const apiUrl = args['api-url'] ?? process.env.VALIDATEQA_API_URL ?? 'https://shared-server.up.railway.app';\n const token = args['token'] ?? process.env.VALIDATEQA_TOKEN;\n const projectId = args['project-id'] ?? process.env.VALIDATEQA_PROJECT_ID;\n\n if (!token) {\n console.error('❌ Missing --token. Copy the full command from your Validate.QA dashboard.');\n process.exit(1);\n }\n if (!projectId) {\n console.error('❌ Missing --project-id. Copy the full command from your Validate.QA dashboard.');\n process.exit(1);\n }\n\n return { apiUrl: apiUrl.replace(/\\/$/, ''), token, projectId };\n}\n\n/** Build the MCP server entry for config files */\nfunction buildMcpEntry(config: InitArgs) {\n return {\n command: 'npx',\n args: [\n '-y', '@validate.qa/mcp@latest',\n '--api-url', config.apiUrl,\n '--token', config.token,\n '--project-id', config.projectId,\n ],\n };\n}\n\ninterface IDETarget {\n name: string;\n configDir: string; // relative to cwd\n configFile: string; // filename inside configDir\n /** Key in the JSON where MCP servers live */\n serversKey: string;\n}\n\nconst IDE_TARGETS: IDETarget[] = [\n { name: 'Claude Code', configDir: '.', configFile: '.mcp.json', serversKey: 'mcpServers' },\n { name: 'Cursor', configDir: '.cursor', configFile: 'mcp.json', serversKey: 'mcpServers' },\n { name: 'Windsurf', configDir: '.windsurf', configFile: 'mcp.json', serversKey: 'mcpServers' },\n { name: 'VS Code', configDir: '.vscode', configFile: 'mcp.json', serversKey: 'servers' },\n];\n\nfunction writeConfigForIDE(cwd: string, target: IDETarget, entry: object): 'created' | 'updated' | 'skipped' {\n const dir = resolve(cwd, target.configDir);\n const filePath = resolve(dir, target.configFile);\n\n // For .cursor and .windsurf, only write if the directory already exists (IDE is in use)\n // For Claude Code (.mcp.json in root), always write\n if (target.configDir !== '.' && !existsSync(dir)) {\n return 'skipped';\n }\n\n let existing: Record<string, unknown> = {};\n if (existsSync(filePath)) {\n try {\n existing = JSON.parse(readFileSync(filePath, 'utf-8'));\n } catch {\n // Corrupted file — overwrite\n }\n }\n\n const servers = (existing[target.serversKey] ?? {}) as Record<string, unknown>;\n const hadEntry = 'validate.qa' in servers;\n servers['validate.qa'] = entry;\n existing[target.serversKey] = servers;\n\n // Ensure directory exists (for .cursor/mcp.json on first setup)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n writeFileSync(filePath, JSON.stringify(existing, null, 2) + '\\n', 'utf-8');\n return hadEntry ? 'updated' : 'created';\n}\n\nexport function runInit() {\n const config = parseInitArgs(process.argv.slice(3)); // skip: node, script, 'init'\n const entry = buildMcpEntry(config);\n const cwd = process.cwd();\n\n console.log('');\n console.log(' Validate.QA — MCP Setup');\n console.log(' ─────────────────────────');\n console.log('');\n\n let anyWritten = false;\n\n for (const target of IDE_TARGETS) {\n const result = writeConfigForIDE(cwd, target, entry);\n if (result === 'skipped') {\n continue;\n }\n const file = join(target.configDir, target.configFile);\n if (result === 'created') {\n console.log(` ✓ ${target.name} — created ${file}`);\n } else {\n console.log(` ✓ ${target.name} — updated ${file}`);\n }\n anyWritten = true;\n }\n\n if (!anyWritten) {\n // No IDE dirs found — create Claude Code config as default\n const target = IDE_TARGETS[0]; // Claude Code\n writeConfigForIDE(cwd, target, entry);\n console.log(` ✓ Created ${target.configFile} (works with Claude Code)`);\n console.log('');\n console.log(' Tip: Create a .cursor/ or .windsurf/ directory and re-run to set up those IDEs too.');\n }\n\n console.log('');\n console.log(' Next: restart your IDE or reload MCP servers.');\n console.log(' Then ask your AI: \"list my tests\" to verify it works.');\n console.log('');\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { resolveConfig } from './config.js';\nimport { ValidateQAClient } from './api-client.js';\nimport { registerAllTools } from './tools/index.js';\n\n// `npx @validate.qa/mcp init ...` — auto-create IDE config files\nif (process.argv[2] === 'init') {\n const { runInit } = await import('./init.js');\n runInit();\n process.exit(0);\n}\n\nconst config = resolveConfig();\nconst client = new ValidateQAClient(config.apiUrl, config.token, config.projectId);\n\nconst server = new McpServer(\n { name: 'validate.qa', version: '1.0.0' },\n { instructions: `Validate.QA — AI-powered QA platform: generates, runs, and heals Playwright E2E tests.\n\n## Capabilities\n- Setup projects via setup_project (read source code first)\n- Write tests via create_test (read routes, components, API handlers first)\n- Manage tests: list, view, edit, run, delete (DRAFT/ACTIVE/DISABLED/QUARANTINED)\n- Heal failing tests: AI replays in browser, fixes code or flags app bugs\n- Schedule recurring runs (hourly-weekly) with auto-heal\n\n## Workflows\n1. New project: READ source, setup_project (features, baseUrl, testCredentials, appBrief). Per feature: READ code, create_test, add_api_endpoints.\n2. Check health: list_features (failingTests > 0), get_test_failures per feature, edit_test_code or heal_test.\n3. Add coverage: READ code, create_feature, create_test x N (suite = feature name), add_api_endpoints.\n4. Nightly automation: create_schedule (daily, autoHeal: true).\n5. After code change: batch_run_tests, then list_features + get_test_failures.\n\n## Automatic lifecycle\nDo NOT call run_test after create_test (auto-queued) or heal_test after failures (auto-heals).\nDo NOT check run status in a loop — call get_test_failures after a reasonable wait to see what failed.\nLifecycle: create > auto-run > pass=ACTIVE, fail=auto-heal > heal fail=@needs-review.\nDO call add_api_endpoints per feature (not automatic).\nDO call run_security_audit after UI tests to analyze captured API traffic. If it errors about missing data, tell the developer to click \"Security Audit\" in the Dashboard to run a live browser capture first. Use list_security_findings to review results.\n\n## Rate limits\n50 calls/60s. Reads parallel OK, writes sequential. On 429, wait 30-60s.\n\n## Triaging failures\n- App broken: flag_as_bug(testId, description). Selector/timing: heal_test. Bad test logic: edit_test_code.\n- Unsure: heal_test first — it detects app bugs automatically.\n\n## Using the codebase\nYou have full source code access. Always READ before writing: routes for URLs, components for selectors, API handlers for endpoints.\n\n## Before writing any test — preflight check\n\nRead project://test-conventions first. Check the variables section:\n- BASE_URL must be set (the runner needs it). If missing, call setup_project or set_variable.\n- TEST_USER_EMAIL and TEST_USER_PASSWORD must be set if tests require login. If missing, ask the developer for credentials and call set_variable.\n- If starting fresh (no features, no variables), use workflow #1 (setup_project) before anything else.\n\n## Critical rules — see project://test-conventions for full details and code templates\n- URLs: relative only, never hardcoded domains — runner sets baseURL\n- Credentials: process.env.TEST_USER_EMAIL! (non-null assertion) — never ?? or || fallbacks\n- Registration: testuser-\\${Date.now()}@example.com\n- Suite name must match feature name exactly (case-sensitive)\n- @auth must NOT combine with @smoke/@regression/@needs-auth/@critical\n- Each test = own browser process; @needs-auth tests MUST login inline\n- API tests: test.describe.serial() with __QA_HTTP__ log after every request\n- UI tests: console.log() milestones after key actions\n- create_test/edit_test_code validate code — fix warnings before moving on\n\n## Setting up coverage\n1. SCAN: Read router, nav, pages, API handlers — map ALL routes and features.\n2. SETUP: setup_project with features, pages, baseUrl, testCredentials, appBrief.\n3. WRITE: One feature at a time. For EACH test, read the SPECIFIC source code first (see codeReadingRequirements in test-conventions). For login blocks: read the login component. For UI tests: read the page component. For API tests: read the route handler. Templates are structure guides — selectors MUST come from the real code. Use create_test for BOTH UI and API tests. Then call add_api_endpoints.\n4. VERIFY: get_coverage_summary + list_features for failures + get_test_failures.\n\nTest real user flows (forms, validation, errors). \"Page loads\" tests are worthless.` },\n);\n\n// Register all QA platform tools\nregisterAllTools(server, client);\n\n// ── MCP Resources (live project context for AI assistants) ────────────\n\nserver.resource(\n 'Project Overview',\n 'project://overview',\n { description: 'Live project state: test counts, pass rates, runner status, features, coverage gaps, and configuration. Read this first to understand the current project.' },\n async () => {\n try {\n const [overview, coverage, stats] = await Promise.all([\n client.executeTool('get_project_overview'),\n client.executeTool('get_coverage_summary').catch(() => null),\n client.executeTool('get_regression_stats').catch(() => null),\n ]);\n const snapshot = {\n overview,\n coverage,\n regressionStats: stats,\n retrievedAt: new Date().toISOString(),\n };\n return { contents: [{ uri: 'project://overview', mimeType: 'application/json', text: JSON.stringify(snapshot, null, 2) }] };\n } catch (err) {\n return { contents: [{ uri: 'project://overview', mimeType: 'text/plain', text: `Failed to load project overview: ${err instanceof Error ? err.message : String(err)}` }] };\n }\n },\n);\n\nserver.resource(\n 'Test Conventions',\n 'project://test-conventions',\n { description: 'Project-specific test conventions: environment variables, credential patterns, tag meanings, and registration email rules. Read this before writing or editing any test.' },\n async () => {\n try {\n const vars = await client.executeTool('get_variables') as { variables: Record<string, { value: string; secret: boolean }> };\n const varNames = Object.keys(vars.variables || {});\n const hasAuth = varNames.includes('TEST_USER_EMAIL') && varNames.includes('TEST_USER_PASSWORD');\n\n const conventions = {\n codeReadingRequirements: {\n CRITICAL: 'Templates below are STRUCTURE GUIDES — every selector, route, and endpoint MUST come from reading the actual source code. Never copy a template verbatim.',\n forLogin: 'BEFORE writing any @needs-auth login block: READ the login/auth page component. Find: (1) the login route (/login, /auth/login, /signin?), (2) the flow type (single-step or multi-step with Continue/Next button?), (3) exact input selectors (labels, placeholders, input types — is it getByLabel, getByPlaceholder, or input[type=password]?), (4) exact submit button text, (5) post-login redirect URL. Every app is different — single-step, multi-step, OAuth buttons, magic links.',\n forUITests: 'BEFORE writing a UI test for a page: READ the page component. Find: headings (text + level), form fields (labels, placeholders, types), buttons (text, role), navigation elements, validation error messages, success/error states. Use the exact text from the component — do not guess.',\n forAPITests: 'BEFORE writing an API test: READ the route handler. Find: the endpoint path, HTTP method, request body schema (what fields, what types), response body shape (is it flat or wrapped in { data: {...} }?), auth requirements (Bearer token? Cookie? API key?), error response shapes.',\n forAPIMapping: 'BEFORE calling add_api_endpoints: READ ALL route handlers for the feature. Register every endpoint with accurate method, path, requestShape, responseShapes, requiresAuth.',\n },\n credentials: {\n rule: 'Never hardcode credentials in test code',\n loginFields: hasAuth\n ? 'Use process.env.TEST_USER_EMAIL! and process.env.TEST_USER_PASSWORD!'\n : 'No credentials configured — set TEST_USER_EMAIL and TEST_USER_PASSWORD via set_variable',\n registrationFields: 'MUST use unique email per run: `testuser-${Date.now()}@example.com` — reusing emails causes \"already registered\" failures',\n registrationPassword: \"Use 'TestPass123!' for new account passwords (meets typical strength rules)\",\n },\n variables: {\n configured: varNames,\n baseUrl: (vars.variables as any)?.BASE_URL?.value || 'Not set',\n },\n tags: {\n '@auth': 'Tests the login/auth flow itself. MUST NOT combine with @smoke, @regression, @needs-auth, @critical. CAN include @discovered.',\n '@needs-auth': 'Tests for authenticated pages — MUST include inline login block. CAN combine with @smoke, @regression, @critical.',\n '@smoke': 'Quick sanity checks — run on every deploy',\n '@regression': 'Full regression suite tests',\n '@critical': 'Business-critical paths (informational label — no special suite filtering)',\n '@api': 'API-level tests. Runs in its own project, excluded from suite/smoke/regression runs',\n '@discovered': 'Auto-added to tests generated by AI discovery',\n '@generated': 'Auto-added by AI discovery and API test generation',\n '@manual': 'Default tag for tests created via create_test when no tags specified',\n '@flaky': 'Auto-added after repeated failures. Excluded from suite/smoke/regression runs',\n '@bug-found': 'Added when healer detects an app bug. Test is auto-quarantined',\n '@needs-review': 'Added when DRAFT test fails healing. Requires human attention',\n '@heal-skip': 'Added by healer when test is permanently unfixable. Prevents future auto-heal',\n },\n executionModel: {\n isolation: 'Each test runs as its own separate Playwright process in a fresh browser. No shared state, no storageState, no global setup.',\n authRequired: 'Every @needs-auth test MUST include its own login block. Do NOT suggest storageState or performLogin() — those only work in the regression suite.',\n concurrency: 'Tests run in parallel — runner claims up to 10 per poll, launched 3s apart (~30s per batch). Multiple batches can overlap. Use test.setTimeout(120_000) if the target app is slow under concurrent login load.',\n },\n lifecycle: {\n DRAFT: 'New or unverified test — not included in scheduled runs',\n ACTIVE: 'Verified and running — included in batch/suite executions',\n DISABLED: 'Manually paused — excluded from all runs',\n QUARANTINED: 'Auto-quarantined after repeated failures',\n },\n logging: {\n CRITICAL: 'EVERY request.get/post/put/patch/delete call MUST be followed by a __QA_HTTP__ log line. This is how the platform surfaces request/response data in the Network panel. Missing this = invisible API calls.',\n apiPattern: \"const body = await res.json();\\nconsole.log('__QA_HTTP__:' + JSON.stringify({ method: 'POST', url: '/api/path', status: res.status(), requestBody: { field: value, password: '[REDACTED]' }, responseBody: body }));\",\n rules: [\n 'Call res.json() ONCE, store in body variable — reuse for log and assertions (calling twice throws)',\n 'Log AFTER the request, BEFORE assertions',\n 'Redact sensitive fields: password: \"[REDACTED]\", token: \"[REDACTED]\"',\n 'Use the literal URL string (same as the request call), not a variable',\n 'UI tests using page fixture do NOT need __QA_HTTP__ — only request fixture tests',\n ],\n uiMilestones: \"UI tests (page fixture): add plain console.log() at key milestones — e.g. console.log('Navigated to login page') after page.goto(). These appear in the Console Output panel.\",\n uiLoggingRules: [\n 'Log AFTER the action, not before — confirms the action succeeded',\n 'Include dynamic values where useful: console.log(\"Current URL:\", page.url())',\n 'Keep messages short and human-readable — they show verbatim in the UI',\n 'Do NOT log sensitive values (passwords, tokens)',\n ],\n apiTestStructure: 'Use test.describe.serial() for API tests sharing auth. Independent validation tests (401, 404 checks) go in a SEPARATE non-serial describe block — do not mix them with the auth-dependent serial flow.',\n },\n bestPractices: [\n 'Every @needs-auth test must start with a login block (goto login, fill creds, click submit, waitForURL)',\n 'Use { timeout: 30000 } on waitForURL after login — target apps can be slow under concurrent test load',\n 'Keep login blocks minimal — no assertions on the login page (that is what @auth tests are for)',\n 'After login, page.goto() directly to the page being tested — do not navigate via UI clicks',\n 'Use role-based selectors (getByRole, getByLabel) over CSS selectors',\n 'Registration tests must generate unique email with Date.now()',\n 'Group tests into suites matching feature names exactly (case-sensitive)',\n 'Do NOT suggest storageState or performLogin() for create_test — those only work in the regression suite',\n 'EVERY API test (request fixture) MUST include __QA_HTTP__ log after each request call — see logging section above',\n 'Avoid waitForLoadState(\"networkidle\") — apps with SSE, WebSocket, or analytics connections may never reach idle, causing 60s timeouts. Wait for specific elements instead.',\n 'For headings, use exact: true or level: 1 — getByRole(\"heading\", { name: \"X\" }) matches ALL h1-h6 containing \"X\", causing strict mode violations',\n ],\n pitfalls: {\n CRITICAL: 'These are the top causes of test failures. Read before writing ANY test.',\n strictModeViolations: \"Playwright throws when a locator resolves to 2+ elements. Common causes: getByLabel('Password') matches input AND 'Show password' toggle; getByRole('button', { name: 'Continue' }) matches 'Continue' AND 'Continue with GitHub'. Prevention: use input[type=\\\"password\\\"] for password fields, use { exact: true } for ambiguous button text, scope to a parent container (page.locator('form#login').getByLabel('Email')).\",\n networkIdle: \"NEVER use waitForLoadState('networkidle') — waits for 500ms of zero network activity, which is fragile and causes 30s+ timeouts in apps with polling, analytics, or WebSockets. Use waitForURL() or wait for a specific element instead.\",\n headingStrictMode: \"getByRole('heading', { name: 'Dashboard' }) can match multiple headings (h1 + h2 + breadcrumb). Add { level: 1 } or { exact: true } to disambiguate. Same for getByLabel('Password') matching input AND 'Show password' toggle.\",\n postLoginRedirect: \"NEVER assert exact URL after login (e.g. expect(page).toHaveURL('/dashboard')) — apps redirect to different routes per user/role. Use: await page.waitForURL(url => !url.pathname.startsWith('/login'), { timeout: 30000 })\",\n resJsonOnce: \"res.json() consumes the response body stream — calling it twice throws. Store result: const body = await res.json(); then reuse body for logging and assertions.\",\n hiddenInputs: \"Many UI frameworks use visually hidden <input> with custom overlays. page.check() fails because the overlay intercepts clicks. Click the <label> or visible wrapper: page.getByText('Remember me').click()\",\n apiResponseShapes: \"API endpoints often wrap data in a property ({ user: {...} }, { data: [...] }). Read the route handler's res.json() call to see the actual shape. If the handler does res.json({ ticket }), then body is { ticket: { id, ... } } — NOT { id, ... }.\",\n invalidIds: \"Not all routes validate ID format before querying the database. If a route passes the raw ID to an ORM query and gets null back, it returns 404 'not found' — not 400 'bad request'. If unsure, expect either: expect([400, 404]).toContain(res.status())\",\n hardcodedUrls: \"NEVER hardcode full URLs in test code. For UI tests: always use relative paths — page.goto('/login'). The runner sets baseURL from the project's BASE_URL variable. For API tests: use relative paths if the API is on the same domain as the frontend (request.post('/api/auth/login')). If the API is on a SEPARATE domain, use process.env.BASE_API_URL! as a test variable (set via set_variable) and construct URLs: request.post(process.env.BASE_API_URL! + '/auth/login'). NEVER hardcode 'https://example.com/...' in test code — use env vars or relative paths.\",\n credentialFallbacks: \"NEVER use process.env.TEST_USER_EMAIL ?? 'fallback' or || 'fallback'. Use ! (non-null assertion). Missing variable = test should fail immediately, not silently use hardcoded value.\",\n },\n templates: {\n needsAuth: \"test('Feature Name — Test Name', {\\n tag: ['@needs-auth', '@smoke'],\\n}, async ({ page }) => {\\n // Login block — ADAPTED from reading the app's login page component\\n // YOU MUST READ the login page component BEFORE writing this block\\n await page.goto('/login'); // read the router for actual login route\\n await page.getByRole('textbox', { name: /email/i }).fill(process.env.TEST_USER_EMAIL!);\\n await page.locator('input[type=\\\"password\\\"]').waitFor({ state: 'visible', timeout: 10000 });\\n await page.locator('input[type=\\\"password\\\"]').fill(process.env.TEST_USER_PASSWORD!);\\n await page.getByRole('button', { name: /sign in|log in|submit/i }).click();\\n await page.waitForURL(url => !url.pathname.startsWith('/login'), { timeout: 30000 });\\n console.log('Logged in, current URL:', page.url());\\n\\n // Actual test\\n await page.goto('/feature-path');\\n console.log('On feature page');\\n await expect(page.getByRole('heading', { name: /feature name/i })).toBeVisible();\\n});\",\n authTest: \"test('Login — Happy Path', {\\n tag: ['@auth'],\\n}, async ({ page }) => {\\n await page.goto('/auth/login');\\n // test the login form itself — selectors from reading the actual component\\n});\",\n apiSerial: \"test.describe.serial('Feature Name', () => {\\n let token: string;\\n test('authenticate', async ({ request }) => {\\n const res = await request.post('/api/auth/login', {\\n data: { email: process.env.TEST_USER_EMAIL!, password: process.env.TEST_USER_PASSWORD! }\\n });\\n const body = await res.json();\\n console.log('__QA_HTTP__:' + JSON.stringify({\\n method: 'POST', url: '/api/auth/login', status: res.status(),\\n requestBody: { email: process.env.TEST_USER_EMAIL!, password: '[REDACTED]' },\\n responseBody: body,\\n }));\\n expect(res.status()).toBe(200);\\n token = body.access_token; // ← adapt to your API (e.g. body.token, body.jwt)\\n });\\n test('get profile', async ({ request }) => {\\n const res = await request.get('/api/users/profile', {\\n headers: { Authorization: `Bearer ${token}` }\\n });\\n const body = await res.json();\\n console.log('__QA_HTTP__:' + JSON.stringify({\\n method: 'GET', url: '/api/users/profile', status: res.status(),\\n responseBody: body,\\n }));\\n expect(res.status()).toBe(200);\\n });\\n});\",\n apiEndpointMapping: '// After reading an Express route handler like:\\n// router.post(\\'/api/auth/login\\', async (req, res) => { ... })\\n// Call add_api_endpoints with:\\n{\\n featureName: \"Authentication\",\\n endpoints: [{\\n method: \"POST\",\\n path: \"/api/auth/login\",\\n requiresAuth: false,\\n requestShape: { \"email\": \"string\", \"password\": \"string\" },\\n responseShapes: { \"200\": { \"token\": \"string\", \"user\": \"object\" }, \"401\": { \"error\": \"string\" } }\\n }]\\n}',\n uiWithMilestones: \"test('Feature — Happy Path', async ({ page }) => {\\n await page.goto('/login');\\n console.log('Navigated to login page');\\n\\n await page.getByRole('textbox', { name: /email/i }).fill(process.env.TEST_USER_EMAIL!);\\n await page.locator('input[type=\\\"password\\\"]').fill(process.env.TEST_USER_PASSWORD!);\\n await page.getByRole('button', { name: /sign in/i }).click();\\n console.log('Credentials submitted');\\n\\n await page.waitForURL(url => !url.pathname.startsWith('/login'), { timeout: 15000 });\\n console.log('Logged in, current URL:', page.url());\\n\\n await page.goto('/feature-path');\\n console.log('On feature page');\\n});\",\n },\n testQuality: [\n 'Test actual user flows, not just \"page loads\" — a test that only checks goto + heading visible is nearly worthless',\n 'Test form submission: fill fields, submit, verify success/redirect',\n 'Test validation: leave required fields empty, enter invalid data, verify error messages',\n 'Test error states: wrong password, expired session, invalid IDs',\n 'Test the happy path end-to-end: login → navigate → perform action → verify result',\n 'Each test should assert something meaningful about the application behavior',\n ],\n securityAudit: {\n workflow: 'After creating UI tests for a feature, call run_security_audit to analyze captured API traffic for auth issues, data exposure, and vulnerabilities.',\n prerequisite: 'Requires prior browser-based test execution (the auto-verification run from create_test counts). If run_security_audit errors about missing data, tell the developer to click \"Security Audit\" in the Tests dropdown on the Dashboard — this launches a live browser to capture real network traffic (HAR) and runs analysis automatically.',\n reviewing: 'Use list_security_findings to review results. Filter by severity (critical/high/medium/low/info) or status (open/acknowledged/resolved/false-positive). Critical and high findings should be flagged to the developer immediately.',\n },\n keyConcepts: {\n features: 'Group related pages and tests (e.g., \"Authentication\" covers /auth/login, /auth/register). MUST include page routes.',\n pages: 'Route URLs on a feature — used for coverage tracking and site map (e.g., [\"/login\", \"/register\"])',\n suites: 'Group tests for batch execution — suite name MUST match feature name exactly (case-sensitive)',\n runner: 'Executes tests — can be local (developer machine) or cloud',\n testData: 'Key-value variables injected into tests (e.g., credentials, URLs)',\n },\n retrievedAt: new Date().toISOString(),\n };\n return { contents: [{ uri: 'project://test-conventions', mimeType: 'application/json', text: JSON.stringify(conventions, null, 2) }] };\n } catch (err) {\n return { contents: [{ uri: 'project://test-conventions', mimeType: 'text/plain', text: `Failed to load conventions: ${err instanceof Error ? err.message : String(err)}` }] };\n }\n },\n);\n\n// Connect via stdio transport\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n","import { readFileSync } from 'fs';\nimport { resolve } from 'path';\n\nexport interface ValidateQAConfig {\n apiUrl: string;\n token: string;\n projectId: string;\n}\n\nfunction parseArgs(argv: string[]): Record<string, string> {\n const args: Record<string, string> = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg.startsWith('--') && i + 1 < argv.length) {\n const key = arg.slice(2);\n args[key] = argv[++i];\n }\n }\n return args;\n}\n\nfunction loadDotFile(): Partial<ValidateQAConfig> {\n try {\n const content = readFileSync(resolve(process.cwd(), '.validateqa.json'), 'utf-8');\n const json = JSON.parse(content);\n return {\n apiUrl: typeof json.apiUrl === 'string' ? json.apiUrl : undefined,\n projectId: typeof json.projectId === 'string' ? json.projectId : undefined,\n };\n } catch {\n return {};\n }\n}\n\nexport function resolveConfig(): ValidateQAConfig {\n const cliArgs = parseArgs(process.argv.slice(2));\n const dotFile = loadDotFile();\n\n const apiUrl =\n cliArgs['api-url'] ??\n process.env.VALIDATEQA_API_URL ??\n dotFile.apiUrl;\n\n const token =\n cliArgs['token'] ??\n process.env.VALIDATEQA_TOKEN;\n\n const projectId =\n cliArgs['project-id'] ??\n process.env.VALIDATEQA_PROJECT_ID ??\n dotFile.projectId;\n\n if (!apiUrl) {\n console.error('Missing required config: api-url (--api-url, VALIDATEQA_API_URL, or .validateqa.json)');\n process.exit(1);\n }\n if (!token) {\n console.error('Missing required config: token (--token or VALIDATEQA_TOKEN)');\n process.exit(1);\n }\n if (!projectId) {\n console.error('Missing required config: project-id (--project-id, VALIDATEQA_PROJECT_ID, or .validateqa.json)');\n process.exit(1);\n }\n\n return { apiUrl: apiUrl.replace(/\\/$/, ''), token, projectId };\n}\n","export class ValidateQAClient {\n constructor(\n private baseUrl: string,\n private token: string,\n private projectId: string,\n ) {}\n\n async executeTool(tool: string, args: Record<string, unknown> = {}): Promise<unknown> {\n let res: Response;\n try {\n res = await fetch(`${this.baseUrl}/api/mcp/execute`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.token}`,\n 'X-Project-Id': this.projectId,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ tool, args }),\n signal: AbortSignal.timeout(120_000),\n });\n } catch (err) {\n // Network errors, DNS failures, timeouts\n const cause = err instanceof Error && err.cause instanceof Error ? err.cause.message : '';\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Connection failed: ${msg}${cause ? ` (${cause})` : ''}`);\n }\n\n if (!res.ok) {\n const body = await res.json().catch(() => ({ error: res.statusText }));\n throw new Error((body as any).error || `API error ${res.status}`);\n }\n\n return res.json();\n }\n\n async healthCheck(): Promise<boolean> {\n try {\n const res = await fetch(`${this.baseUrl}/health`, {\n signal: AbortSignal.timeout(5000),\n });\n return res.ok;\n } catch {\n return false;\n }\n }\n}\n","import { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { ValidateQAClient } from '../api-client.js';\n\ntype ToolAnnotations = {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n};\n\nfunction tool(\n server: McpServer,\n client: ValidateQAClient,\n name: string,\n description: string,\n schema: Record<string, z.ZodTypeAny>,\n annotations?: ToolAnnotations,\n) {\n const handler = async (args: Record<string, unknown>) => {\n try {\n const result = await client.executeTool(name, args);\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: `Error: ${err instanceof Error ? err.message : String(err)}` }],\n isError: true,\n };\n }\n };\n\n if (annotations) {\n server.tool(name, description, schema, annotations, handler);\n } else {\n server.tool(name, description, schema, handler);\n }\n}\n\nexport function registerAllTools(server: McpServer, client: ValidateQAClient) {\n // ── Test Management ──────────────────────────────────────────────────\n\n tool(server, client, 'list_tests',\n 'List tests in the current project. Returns test name, status, suite, tags, confidence, and the last run result. Paginated — use limit/offset to page through all tests.',\n {\n status: z.enum(['DRAFT', 'ACTIVE', 'DISABLED', 'QUARANTINED']).optional().describe('Filter by test lifecycle status'),\n suite: z.string().optional().describe('Filter by suite name'),\n search: z.string().optional().describe('Search test names (case-insensitive substring match)'),\n tag: z.string().optional().describe('Filter by tag (e.g. @regression, @smoke, @auth)'),\n limit: z.number().optional().describe('Max results to return (default: 50, max: 200)'),\n offset: z.number().optional().describe('Number of results to skip for pagination (default: 0)'),\n },\n { readOnlyHint: true },\n );\n\n tool(server, client, 'get_test',\n 'Get details of a specific test: name, status, tags, steps, session, and the 5 most recent run results. Code is truncated to 200 lines — use get_test_code for the full Playwright code.',\n { testId: z.string().describe('The test case ID') },\n { readOnlyHint: true },\n );\n\n tool(server, client, 'run_test',\n 'Queue a test for execution. Creates a PENDING test run that will be picked up by an online runner. Returns the run ID.',\n { testId: z.string().describe('The test case ID to run') },\n );\n\n tool(server, client, 'delete_test',\n 'Permanently delete a test case and all its run history. Cannot be undone.',\n { testId: z.string().describe('The test case ID to delete') },\n { destructiveHint: true },\n );\n\n tool(server, client, 'heal_test',\n 'Queue an AI healing run for a failing test. The AI agent replays the test in a real browser, analyzes the failure, and either fixes the Playwright code OR detects an application bug (quarantines the test with @bug-found if the app itself is broken, not the test).',\n { testId: z.string().describe('The failing test case ID') },\n );\n\n tool(server, client, 'edit_test_code',\n 'Update the Playwright code, name, or tags of an existing test case. Read project://test-conventions for patterns and pitfalls. Code is validated — fix any warnings returned.',\n {\n testId: z.string().describe('The test case ID to edit'),\n playwrightCode: z.string().optional().describe('New Playwright test code (full file replacement)'),\n name: z.string().optional().describe('New test name'),\n tags: z.array(z.string()).optional().describe('New tags array (e.g. [\"@regression\", \"@smoke\"])'),\n },\n );\n\n tool(server, client, 'update_test_status',\n 'Change the lifecycle status of one or more tests (e.g. promote DRAFT→ACTIVE, disable a flaky test).',\n {\n testIds: z.array(z.string()).describe('Test IDs to update'),\n status: z.enum(['DRAFT', 'ACTIVE', 'DISABLED', 'QUARANTINED']).describe('New status to set'),\n },\n );\n\n // ── Test Runs ────────────────────────────────────────────────────────\n\n tool(server, client, 'get_test_run',\n 'Get the status and result of a specific test run, including error details if it failed. Can look up by runId or get the latest run for a testId.',\n {\n runId: z.string().optional().describe('The test run ID'),\n testId: z.string().optional().describe('Get the most recent run for this test case ID'),\n },\n { readOnlyHint: true },\n );\n\n // Custom handler — returns MCP image content blocks so the AI can see screenshots\n server.tool(\n 'get_test_screenshots',\n 'Get screenshots from a specific test run as images the AI can actually see. Use this to visually inspect what happened during a failed or passing run.',\n {\n runId: z.string().describe('The test run ID to fetch screenshots from'),\n limit: z.number().optional().describe('Max screenshots to return (default: 5, max: 10)'),\n },\n { readOnlyHint: true },\n async (args) => {\n try {\n const result = await client.executeTool('get_test_screenshots', args) as {\n runId: string;\n status: string;\n total: number;\n returned: number;\n screenshots: Array<{ index: number; data: string; mimeType: string }>;\n };\n\n if (!result.screenshots || result.screenshots.length === 0) {\n return {\n content: [{\n type: 'text' as const,\n text: `No screenshots available for run ${result.runId} (status: ${result.status})`,\n }],\n };\n }\n\n const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [\n {\n type: 'text' as const,\n text: `Run ${result.runId} — status: ${result.status} — showing ${result.returned} of ${result.total} screenshot(s)`,\n },\n ];\n\n for (const shot of result.screenshots) {\n content.push({ type: 'image' as const, data: shot.data, mimeType: shot.mimeType });\n }\n\n return { content };\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: `Error: ${err instanceof Error ? err.message : String(err)}` }],\n isError: true,\n };\n }\n },\n );\n\n tool(server, client, 'cancel_test_run',\n 'Cancel a pending or running test run. Can cancel by run ID or cancel the latest running batch.',\n {\n runId: z.string().optional().describe('The specific test run ID to cancel'),\n cancelBatch: z.boolean().optional().describe('If true, cancel the latest batch run instead'),\n },\n );\n\n tool(server, client, 'batch_run_tests',\n 'Run multiple tests from the database individually. Filter by test IDs or suite name; omit both to run all ACTIVE tests. Each test executes in its own browser.',\n {\n testIds: z.array(z.string()).optional().describe('Specific test IDs to run'),\n suite: z.string().optional().describe('Run all active tests in this suite'),\n },\n );\n\n // ── Features & API Endpoints ──────────────────────────────────────────\n\n tool(server, client, 'list_features',\n 'List all features with test counts and failure counts (last 24h). Use failingTests > 0 to identify which features need attention, then call get_test_failures({ suite: featureName }) to drill into the full error details for that feature.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'list_api_endpoints',\n 'List captured API endpoints for the current project. Optionally scope to a specific feature name.',\n {\n featureName: z.string().optional().describe('Optional feature name to scope the endpoint list'),\n },\n { readOnlyHint: true },\n );\n\n // ── Infrastructure ───────────────────────────────────────────────────\n\n tool(server, client, 'get_runner_health',\n 'Check whether the project\\'s configured runners are online, including available device capabilities.',\n {},\n { readOnlyHint: true },\n );\n\n // ── Reports & Observability ──────────────────────────────────────────\n\n tool(server, client, 'get_project_overview',\n 'Get a workspace-level QA overview: test counts, pass rates, runner readiness, features, coverage gaps, variables, schedules, and notifications.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'get_reports_summary',\n 'Get a high-level report: total tests (active, never-run), 7-day pass rate, today\\'s run count, and the 10 most recent test run results.',\n {},\n { readOnlyHint: true },\n );\n\n // ── Schedules (Admin) ────────────────────────────────────────────────\n\n tool(server, client, 'list_schedules',\n 'List all scheduled test runs in the project.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'create_schedule',\n 'Create a new recurring test schedule. Runs all matching tests from the database on the configured interval.',\n {\n name: z.string().describe('Name for the schedule (e.g. \"Nightly smoke tests\")'),\n mode: z.enum(['batch']).describe('Run mode: batch (runs project tests from the database)'),\n intervalMinutes: z.union([z.literal(60), z.literal(360), z.literal(720), z.literal(1440), z.literal(2880), z.literal(10080)]).describe('Interval in minutes: 60 (hourly), 360 (6h), 720 (12h), 1440 (daily), 2880 (2 days), 10080 (weekly)'),\n tags: z.array(z.string()).optional().describe('Tags to filter which tests run (e.g. [\"@smoke\"]). Omit to run all ACTIVE tests.'),\n autoHeal: z.boolean().optional().describe('Automatically heal failing tests after each run'),\n enabled: z.boolean().optional().describe('Whether the schedule is active (default: true)'),\n runImmediately: z.boolean().optional().describe('Whether to trigger the first run immediately (default: true)'),\n },\n );\n\n tool(server, client, 'update_schedule',\n 'Update an existing test schedule.',\n {\n scheduleId: z.string().describe('The schedule ID to update'),\n name: z.string().optional().describe('New name for the schedule'),\n intervalMinutes: z.union([z.literal(60), z.literal(360), z.literal(720), z.literal(1440), z.literal(2880), z.literal(10080)]).optional().describe('New interval in minutes'),\n suite: z.string().optional().describe('New suite name to filter tests'),\n tags: z.array(z.string()).optional().describe('New tag filter'),\n autoHeal: z.boolean().optional().describe('Toggle auto-heal'),\n enabled: z.boolean().optional().describe('Enable or disable the schedule'),\n },\n );\n\n tool(server, client, 'delete_schedule',\n 'Delete (remove) a test schedule permanently.',\n { scheduleId: z.string().describe('The schedule ID to delete') },\n { destructiveHint: true },\n );\n\n tool(server, client, 'run_schedule_now',\n 'Trigger a scheduled run immediately instead of waiting for the next scheduled time.',\n { scheduleId: z.string().describe('The schedule ID to trigger') },\n );\n\n // ── Configuration ────────────────────────────────────────────────────\n\n tool(server, client, 'get_variables',\n 'Get all test variables (environment variables) for the current project. Secrets are redacted.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'set_variable',\n 'Set or update a test variable (environment variable) for the project. Used to configure base URLs, credentials, etc.',\n {\n key: z.string().describe('Variable name (e.g. BASE_URL, TEST_USER_EMAIL, API_KEY)'),\n value: z.string().describe('Variable value. Set value to empty string to remove a variable.'),\n secret: z.boolean().optional().describe('Whether this variable is a secret (will be redacted in UI)'),\n },\n );\n\n tool(server, client, 'create_test',\n 'Create a new test case with Playwright code. Read project://test-conventions for templates and pitfalls BEFORE writing code. The test starts as DRAFT — auto-runs and auto-promotes to ACTIVE on pass. IMPORTANT: (1) Set suite to the EXACT feature name. (2) After creating all tests for a feature, you MUST call add_api_endpoints.',\n {\n name: z.string().describe('Test name (e.g. \"Login — Happy Path\")'),\n playwrightCode: z.string().describe('Full Playwright test code'),\n suite: z.string().optional().describe('MUST match an existing feature name exactly to link the test to that feature (e.g. \"Authentication\", not \"Auth Tests\")'),\n tags: z.array(z.string()).optional().describe('Tags (e.g. [\"@smoke\", \"@auth\"])'),\n },\n );\n\n // ── Features ─────────────────────────────────────────────────────────\n\n tool(server, client, 'get_feature',\n 'Get detailed info about a feature including its pages, test plans, existing tests with lastRunStatus, and AI insights.',\n { featureName: z.string().describe('The feature name (case-insensitive match)') },\n { readOnlyHint: true },\n );\n\n tool(server, client, 'create_feature',\n 'Create a new feature with page routes. Read the developer\\'s route files to provide accurate page URLs. Pages are used for coverage tracking and site map.',\n {\n name: z.string().describe('Feature name (e.g. \"Checkout Flow\")'),\n description: z.string().optional().describe('What the feature does and what to test'),\n pages: z.array(z.string()).describe('Page routes this feature covers (e.g. [\"/checkout\", \"/checkout/payment\"]). Required for test generation.'),\n criticality: z.enum(['critical', 'high', 'medium', 'low']).optional().describe('Feature criticality level (default: medium)'),\n },\n );\n\n // ── Full Test Code ───────────────────────────────────────────────────\n\n tool(server, client, 'get_test_code',\n 'Get the full (untruncated) Playwright test code for a test case. Use this when you need to read, analyze, or prepare edits for the complete test code.',\n { testId: z.string().describe('The test case ID') },\n { readOnlyHint: true },\n );\n\n // ── Project Settings ─────────────────────────────────────────────────\n\n tool(server, client, 'set_runner_preference',\n 'Switch between cloud and local runner for test execution.',\n { preference: z.enum(['cloud', 'local']).describe('Runner type: cloud (shared infrastructure) or local (runs on your machine)') },\n );\n\n tool(server, client, 'toggle_auto_heal',\n 'Enable or disable automatic AI healing when tests fail in batch or suite runs.',\n { enabled: z.boolean().describe('true to enable auto-heal, false to disable') },\n );\n\n // ── Test Data ────────────────────────────────────────────────────────\n\n tool(server, client, 'list_test_data',\n 'List all test data sets in the project. Each set contains key-value pairs injected into AI prompts and test runs.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'create_test_data',\n 'Create a new test data set with key-value pairs. Max 200 entries per set.',\n {\n name: z.string().describe('Name of the test data set (max 100 chars)'),\n description: z.string().optional().describe('Optional description (max 1000 chars)'),\n data: z.record(z.string()).describe('Key-value pairs (e.g. {\"email\": \"test@example.com\", \"password\": \"secret\"})'),\n },\n );\n\n tool(server, client, 'delete_test_data',\n 'Delete a test data set by ID.',\n { dataSetId: z.string().describe('The test data set ID to delete') },\n { destructiveHint: true },\n );\n\n // ── Feature Management ───────────────────────────────────────────────\n\n tool(server, client, 'update_feature',\n 'Update a feature\\'s name, description, pages, or criticality.',\n {\n featureId: z.string().describe('The feature ID to update'),\n name: z.string().optional().describe('New feature name'),\n description: z.string().optional().describe('New description'),\n pages: z.array(z.string()).optional().describe('Updated page routes'),\n criticality: z.enum(['critical', 'high', 'medium', 'low']).optional().describe('Feature criticality level'),\n },\n );\n\n tool(server, client, 'archive_feature',\n 'Archive a feature (soft delete). Archived features are hidden from the dashboard but can be restored.',\n { featureId: z.string().describe('The feature ID to archive') },\n { destructiveHint: true },\n );\n\n // ── Site Map ─────────────────────────────────────────────────────────\n\n tool(server, client, 'get_site_map_coverage',\n 'Get site map coverage statistics: total pages, pages with tests, elements covered, coverage percentage, and per-page breakdown.',\n {},\n { readOnlyHint: true },\n );\n\n // ── Issue Triage ─────────────────────────────────────────────────────\n\n tool(server, client, 'list_bugs',\n 'Get all detected bugs: app bugs (quarantined tests with @bug-found), security findings, and flaky tests.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'flag_as_bug',\n 'Mark a failing test as a confirmed application bug — quarantines it with @bug-found and records the bug description. Use when the failure is caused by broken app behaviour, NOT a test script issue. Do NOT use for selector changes or timeout failures — use heal_test or edit_test_code for those.',\n {\n testId: z.string().describe('The failing test case ID'),\n description: z.string().describe('What is broken in the application (e.g. \"POST /api/checkout returns 500 when payment method is valid\")'),\n },\n );\n\n // ── Security Audit ───────────────────────────────────────────────────\n\n tool(server, client, 'run_security_audit',\n 'Run an AI security audit on captured API traffic. Requires prior browser-based test execution (discovery or capture) — analyzes real network traffic, not just registered endpoints. If no traffic exists, the developer can trigger \"Security Audit\" from the Dashboard which launches a live browser to capture it.',\n {},\n );\n\n tool(server, client, 'list_security_findings',\n 'List security audit findings with optional filters. Returns severity, category, status, and affected endpoints.',\n {\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']).optional().describe('Filter by severity'),\n status: z.enum(['open', 'acknowledged', 'resolved', 'false-positive']).optional().describe('Filter by status'),\n },\n { readOnlyHint: true },\n );\n\n // ── Project Settings ─────────────────────────────────────────────────\n\n tool(server, client, 'set_app_brief',\n 'Set or update the project\\'s application brief — a description of the app used by AI for better test generation.',\n { appBrief: z.string().describe('Application description. Set empty to clear.') },\n );\n\n // ── Coverage & Draft Verification ────────────────────────────────────\n\n tool(server, client, 'get_coverage_summary',\n 'Get feature-level test coverage: planned vs existing vs passing tests, plus API endpoint coverage. Shows uncoveredEndpoints per feature — use this to find which API endpoints still need tests.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'run_draft_tests',\n 'Run all DRAFT tests to verify them. Tests that pass auto-promote to ACTIVE. Optionally scope to a feature.',\n {\n featureName: z.string().optional().describe('Only run drafts for this feature (optional)'),\n },\n );\n\n // ── Project Setup ────────────────────────────────────────────────────\n\n tool(server, client, 'setup_project',\n 'One-shot project setup from codebase knowledge. Sets app brief, base URL, test credentials, and creates features with pages — all in one call. Use this when a developer says \"set up test coverage for my app.\"',\n {\n appBrief: z.string().optional().describe('Description of the application (what it does, key features, tech stack)'),\n baseUrl: z.string().describe('Application base URL (e.g. \"https://myapp.com\" or \"http://localhost:3000\")'),\n testCredentials: z.object({\n email: z.string().optional().describe('Test user email'),\n password: z.string().optional().describe('Test user password'),\n }).optional().describe('Login credentials for test execution'),\n features: z.array(z.object({\n name: z.string().describe('Feature name'),\n description: z.string().optional().describe('What the feature does'),\n pages: z.array(z.string()).describe('Page routes (e.g. [\"/login\", \"/register\"])'),\n criticality: z.enum(['critical', 'high', 'medium', 'low']).optional().describe('Feature criticality'),\n })).describe('Features to create with their page routes'),\n },\n );\n\n // ── API Endpoints ───────────────────────────────────────────────────\n\n tool(server, client, 'add_api_endpoints',\n 'Register API endpoints for a feature from codebase knowledge. Read the developer\\'s route handlers to extract methods, paths, request/response shapes. Populates the API intelligence dashboard.',\n {\n featureName: z.string().describe('Feature name to link these endpoints to'),\n endpoints: z.array(z.object({\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),\n path: z.string().describe('API path (e.g. \"/api/auth/login\")'),\n requestShape: z.record(z.string()).optional().describe('Request body fields with types (e.g. { \"email\": \"string\" })'),\n responseShapes: z.record(z.record(z.string())).optional().describe('Response shapes by status code (e.g. { \"200\": { \"token\": \"string\" } })'),\n requiresAuth: z.boolean().optional().describe('Whether endpoint requires authentication'),\n })).describe('API endpoints to register'),\n },\n );\n\n // ── Failure Diagnostics ──────────────────────────────────────────────\n\n tool(server, client, 'get_test_failures',\n 'Get recent test failures with full error messages, Playwright code, step-level failures, and heal context. Use this to understand why tests are failing.',\n {\n limit: z.number().optional().describe('Max failures to return (default: 50, max: 100)'),\n suite: z.string().optional().describe('Filter by feature/suite name'),\n mode: z.enum(['run', 'heal', 'all']).optional().describe('run = regular failures, heal = heal attempt failures, all = both (default)'),\n sinceHours: z.number().optional().describe('Only failures from the last N hours (default: 24)'),\n },\n { readOnlyHint: true },\n );\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAMA,SAAS,YAAY,WAAW,gBAAAA,eAAc,qBAAqB;AACnE,SAAS,WAAAC,UAAS,YAAY;AAQ9B,SAAS,cAAc,MAA0B;AAC/C,QAAM,OAA+B,CAAC;AACtC,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,MAAM,KAAK,CAAC;AAClB,QAAI,IAAI,WAAW,IAAI,KAAK,IAAI,IAAI,KAAK,QAAQ;AAC/C,WAAK,IAAI,MAAM,CAAC,CAAC,IAAI,KAAK,EAAE,CAAC;AAAA,IAC/B;AAAA,EACF;AAEA,QAAM,SAAS,KAAK,SAAS,KAAK,QAAQ,IAAI,sBAAsB;AACpE,QAAM,QAAQ,KAAK,OAAO,KAAK,QAAQ,IAAI;AAC3C,QAAM,YAAY,KAAK,YAAY,KAAK,QAAQ,IAAI;AAEpD,MAAI,CAAC,OAAO;AACV,YAAQ,MAAM,gFAA2E;AACzF,YA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AAA,UACA;AAAA,QACF;AAAA,QACA,eAAe;AAAA,UACb,UAAU;AAAA,UACV,cAAc;AAAA,UACd,WAAW;AAAA,QACb;AAAA,QACA,aAAa;AAAA,UACX,UAAU;AAAA,UACV,OAAO;AAAA,UACP,QAAQ;AAAA,UACR,QAAQ;AAAA,UACR,UAAU;AAAA,QACZ;AAAA,QACA,cAAa,oBAAI,KAAK,GAAE,YAAY;AAAA,MACtC;AACA,aAAO,EAAE,UAAU,CAAC,EAAE,KAAK,8BAA8B,UAAU,oBAAoB,MAAM,KAAK,UAAU,aAAa,MAAM,CAAC,EAAE,CAAC,EAAE;AAAA,IACvI,SAAS,KAAK;AACZ,aAAO,EAAE,UAAU,CAAC,EAAE,KAAK,8BAA8B,UAAU,cAAc,MAAM,+BAA+B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,GAAG,CAAC,EAAE;AAAA,IAC9K;AAAA,EACF;AACF;AAGA,IAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS;","names":["readFileSync","resolve","config","tool","server","client","runInit"]}
1
+ {"version":3,"sources":["../src/init.ts","../src/index.ts","../src/config.ts","../src/api-client.ts","../src/tools/index.ts"],"sourcesContent":["/**\n * `npx @validate.qa/mcp init` - one-command MCP setup for all supported IDEs.\n *\n * Creates/updates MCP config files so the user never has to manually edit JSON.\n * Detects which IDEs are present and writes the appropriate config for each.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { resolve, join } from 'path';\n\ninterface InitArgs {\n apiUrl: string;\n token: string;\n projectId: string;\n}\n\nfunction parseInitArgs(argv: string[]): InitArgs {\n const args: Record<string, string> = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg.startsWith('--') && i + 1 < argv.length) {\n args[arg.slice(2)] = argv[++i];\n }\n }\n\n const apiUrl = args['api-url'] ?? process.env.VALIDATEQA_API_URL ?? 'https://shared.validate.qa';\n const token = args['token'] ?? process.env.VALIDATEQA_TOKEN;\n const projectId = args['project-id'] ?? process.env.VALIDATEQA_PROJECT_ID;\n\n if (!token) {\n console.error('❌ Missing --token. Copy the full command from your Validate.QA dashboard.');\n process.exit(1);\n }\n if (!projectId) {\n console.error('❌ Missing --project-id. Copy the full command from your Validate.QA dashboard.');\n process.exit(1);\n }\n\n return { apiUrl: apiUrl.replace(/\\/$/, ''), token, projectId };\n}\n\n/** Build the MCP server entry for config files */\nfunction buildMcpEntry(config: InitArgs) {\n return {\n command: 'npx',\n args: [\n '-y', '@validate.qa/mcp@latest',\n '--api-url', config.apiUrl,\n '--token', config.token,\n '--project-id', config.projectId,\n ],\n };\n}\n\ninterface IDETarget {\n name: string;\n configDir: string; // relative to cwd\n configFile: string; // filename inside configDir\n /** Key in the JSON where MCP servers live */\n serversKey: string;\n}\n\nconst IDE_TARGETS: IDETarget[] = [\n { name: 'Claude Code', configDir: '.', configFile: '.mcp.json', serversKey: 'mcpServers' },\n { name: 'Cursor', configDir: '.cursor', configFile: 'mcp.json', serversKey: 'mcpServers' },\n { name: 'Windsurf', configDir: '.windsurf', configFile: 'mcp.json', serversKey: 'mcpServers' },\n { name: 'VS Code', configDir: '.vscode', configFile: 'mcp.json', serversKey: 'servers' },\n];\n\nfunction writeConfigForIDE(cwd: string, target: IDETarget, entry: object): 'created' | 'updated' | 'skipped' {\n const dir = resolve(cwd, target.configDir);\n const filePath = resolve(dir, target.configFile);\n\n // For .cursor and .windsurf, only write if the directory already exists (IDE is in use)\n // For Claude Code (.mcp.json in root), always write\n if (target.configDir !== '.' && !existsSync(dir)) {\n return 'skipped';\n }\n\n let existing: Record<string, unknown> = {};\n if (existsSync(filePath)) {\n try {\n existing = JSON.parse(readFileSync(filePath, 'utf-8'));\n } catch {\n // Corrupted file - overwrite\n }\n }\n\n const servers = (existing[target.serversKey] ?? {}) as Record<string, unknown>;\n const hadEntry = 'validate.qa' in servers;\n servers['validate.qa'] = entry;\n existing[target.serversKey] = servers;\n\n // Ensure directory exists (for .cursor/mcp.json on first setup)\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n writeFileSync(filePath, JSON.stringify(existing, null, 2) + '\\n', 'utf-8');\n return hadEntry ? 'updated' : 'created';\n}\n\nexport function runInit() {\n const config = parseInitArgs(process.argv.slice(3)); // skip: node, script, 'init'\n const entry = buildMcpEntry(config);\n const cwd = process.cwd();\n\n console.log('');\n console.log(' Validate.QA - MCP Setup');\n console.log(' ─────────────────────────');\n console.log('');\n\n let anyWritten = false;\n\n for (const target of IDE_TARGETS) {\n const result = writeConfigForIDE(cwd, target, entry);\n if (result === 'skipped') {\n continue;\n }\n const file = join(target.configDir, target.configFile);\n if (result === 'created') {\n console.log(` ✓ ${target.name} - created ${file}`);\n } else {\n console.log(` ✓ ${target.name} - updated ${file}`);\n }\n anyWritten = true;\n }\n\n if (!anyWritten) {\n // No IDE dirs found - create Claude Code config as default\n const target = IDE_TARGETS[0]; // Claude Code\n writeConfigForIDE(cwd, target, entry);\n console.log(` ✓ Created ${target.configFile} (works with Claude Code)`);\n console.log('');\n console.log(' Tip: Create a .cursor/ or .windsurf/ directory and re-run to set up those IDEs too.');\n }\n\n console.log('');\n console.log(' Next: restart your IDE or reload MCP servers.');\n console.log(' Then ask your AI: \"list my tests\" to verify it works.');\n console.log('');\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { resolveConfig } from './config.js';\nimport { ValidateQAClient } from './api-client.js';\nimport { registerAllTools } from './tools/index.js';\n\n// `npx @validate.qa/mcp init ...` - auto-create IDE config files\nif (process.argv[2] === 'init') {\n const { runInit } = await import('./init.js');\n runInit();\n process.exit(0);\n}\n\nconst config = resolveConfig();\nconst client = new ValidateQAClient(config.apiUrl, config.token, config.projectId);\n\nconst server = new McpServer(\n { name: 'validate.qa', version: '1.0.0' },\n { instructions: `Validate.QA - AI-powered QA platform: generates, runs, and heals Playwright E2E tests.\n\n## Capabilities\n- Setup projects via setup_project (read source code first)\n- Write tests via create_test (read routes, components, API handlers first)\n- Manage tests: list, view, edit, run, delete (DRAFT/ACTIVE/DISABLED/QUARANTINED)\n- Heal failing tests: AI replays in browser, fixes code or flags app bugs\n- Schedule recurring runs (hourly-weekly) with auto-heal\n\n## Workflows\n1. New project: READ source, setup_project (features, baseUrl, testCredentials, appBrief). Per feature: READ code, create_test, add_api_endpoints.\n2. Check health: list_features (failingTests > 0), get_test_failures per feature, edit_test_code or heal_test.\n3. Add coverage: READ code, create_feature, create_test x N (suite = feature name), add_api_endpoints.\n4. Nightly automation: create_schedule (daily, autoHeal: true).\n5. After code change: batch_run_tests (waitSeconds: 120, or then wait_for_batch), then list_features + get_test_failures.\n\n## Automatic lifecycle\nDo NOT call run_test after create_test (auto-queued) or heal_test after failures (auto-heals, unless toggle_auto_heal turned it off).\nDo NOT poll get_test_run in a loop. To wait for a run, call wait_for_run(runId) (or wait_for_batch(batchId)); it blocks until the run finishes or timeoutSeconds passes (max 120) and returns timedOut: true if it is still going - then call it again. run_test and batch_run_tests also take waitSeconds to queue and wait in one call. A FAILED run comes back with its error, consoleLog and failedSteps.\nLifecycle: create > auto-run > pass=ACTIVE, fail=auto-heal > heal fail=@needs-review. With toggle_auto_heal(false), no failure is auto-healed; call heal_test yourself when you want one.\nDO call add_api_endpoints per feature (not automatic).\nDO call run_security_audit after UI tests to analyze captured API traffic. If it errors about missing data, tell the developer to click \"Security Audit\" in the Dashboard to run a live browser capture first. Use list_security_findings to review results.\n\n## Rate limits\n50 calls/60s. Reads parallel OK, writes sequential. On 429, wait 30-60s.\n\n## Triaging failures\n- App broken: flag_as_bug(testId, description). Selector/timing: heal_test. Bad test logic: edit_test_code.\n- Unsure: heal_test first - it detects app bugs automatically.\n\n## Using the codebase\nYou have full source code access. Always READ before writing: routes for URLs, components for selectors, API handlers for endpoints.\n\n## Before writing any test - preflight check\n\nRead project://test-conventions first. Check the variables section:\n- BASE_URL must be set (the runner needs it). If missing, call setup_project or set_variable.\n- TEST_USER_EMAIL and TEST_USER_PASSWORD must be set if tests require login. If missing, ask the developer for credentials and call set_variable.\n- If starting fresh (no features, no variables), use workflow #1 (setup_project) before anything else.\n\n## Critical rules - see project://test-conventions for full details and code templates\n- URLs: relative only, never hardcoded domains - runner sets baseURL\n- Credentials: process.env.TEST_USER_EMAIL! (non-null assertion) - never ?? or || fallbacks\n- Registration: testuser-\\${Date.now()}@example.com\n- Suite name must match feature name exactly (case-sensitive)\n- @auth must NOT combine with @smoke/@regression/@needs-auth/@critical\n- Each test = own browser process; @needs-auth tests MUST login inline\n- API tests: test.describe.serial() with __QA_HTTP__ log after every request\n- UI tests: console.log() milestones after key actions\n- Selectors: getByRole(role, { name, exact: true }), getByLabel(label, { exact: true }), getByText(text, { exact: true }); CSS ids only for nodes with no accessible name\n- URL assertions: path only - await expect(page).toHaveURL(/\\\\/dashboard$/) - never a host\n- Production BASE_URL: read-only tests get the read-only guard (page.route aborts auth/mutation requests and fails the test) - template in project://test-conventions\n- Every assertion must be able to fail: no toHaveCount(0) on transient text, no toBeHidden on an element never shown, full message text instead of a toContainText fragment\n- create_test/edit_test_code validate code - fix warnings before moving on\n\n## Setting up coverage\n1. SCAN: Read router, nav, pages, API handlers - map ALL routes and features.\n2. SETUP: setup_project with features, pages, baseUrl, testCredentials, appBrief.\n3. WRITE: One feature at a time. For EACH test, read the SPECIFIC source code first (see codeReadingRequirements in test-conventions). For login blocks: read the login component. For UI tests: read the page component. For API tests: read the route handler. Templates are structure guides - selectors MUST come from the real code. Use create_test for BOTH UI and API tests. Then call add_api_endpoints.\n4. VERIFY: get_spec_coverage(featureName, specItems) - write tests for every uncovered item - then get_coverage_summary + list_features for failures + get_test_failures.\n\nTest real user flows (forms, validation, errors). \"Page loads\" tests are worthless.` },\n);\n\n// Register all QA platform tools\nregisterAllTools(server, client);\n\n// ── MCP Resources (live project context for AI assistants) ────────────\n\nserver.resource(\n 'Project Overview',\n 'project://overview',\n { description: 'Live project state: test counts, pass rates, runner status, features, coverage gaps, and configuration. Read this first to understand the current project.' },\n async () => {\n try {\n const [overview, coverage, stats] = await Promise.all([\n client.executeTool('get_project_overview'),\n client.executeTool('get_coverage_summary').catch(() => null),\n client.executeTool('get_regression_stats').catch(() => null),\n ]);\n const snapshot = {\n overview,\n coverage,\n regressionStats: stats,\n retrievedAt: new Date().toISOString(),\n };\n return { contents: [{ uri: 'project://overview', mimeType: 'application/json', text: JSON.stringify(snapshot, null, 2) }] };\n } catch (err) {\n return { contents: [{ uri: 'project://overview', mimeType: 'text/plain', text: `Failed to load project overview: ${err instanceof Error ? err.message : String(err)}` }] };\n }\n },\n);\n\nserver.resource(\n 'Test Conventions',\n 'project://test-conventions',\n { description: 'Project-specific test conventions: environment variables, credential patterns, tag meanings, and registration email rules. Read this before writing or editing any test.' },\n async () => {\n // The server builds the conventions (one copy for every transport, updated without an npm\n // release). The copy below is only a fallback for servers that predate that route.\n const served = await client.getTestConventions();\n if (served && typeof served === 'object') {\n return { contents: [{ uri: 'project://test-conventions', mimeType: 'application/json', text: JSON.stringify(served, null, 2) }] };\n }\n try {\n const vars = await client.executeTool('get_variables') as { variables: Record<string, { value: string; secret: boolean }> };\n const varNames = Object.keys(vars.variables || {});\n const hasAuth = varNames.includes('TEST_USER_EMAIL') && varNames.includes('TEST_USER_PASSWORD');\n\n const conventions = {\n codeReadingRequirements: {\n CRITICAL: 'Templates below are STRUCTURE GUIDES - every selector, route, and endpoint MUST come from reading the actual source code. Never copy a template verbatim.',\n forLogin: 'BEFORE writing any @needs-auth login block: READ the login/auth page component. Find: (1) the login route (/login, /auth/login, /signin?), (2) the flow type (single-step or multi-step with Continue/Next button?), (3) each field\\'s label text for getByLabel(label, { exact: true }) - fall back to the placeholder or input[type=password] only when the field has no label, (4) the submit button\\'s accessible name for getByRole(\\'button\\', { name, exact: true }), (5) post-login redirect URL. Every app is different - single-step, multi-step, OAuth buttons, magic links.',\n forUITests: 'BEFORE writing a UI test for a page: READ the page component. Find: headings (text + level), form fields (labels, placeholders, types), buttons (text, role), navigation elements, validation error messages, success/error states. Use the exact text from the component - do not guess.',\n forAPITests: 'BEFORE writing an API test: READ the route handler. Find: the endpoint path, HTTP method, request body schema (what fields, what types), response body shape (is it flat or wrapped in { data: {...} }?), auth requirements (Bearer token? Cookie? API key?), error response shapes.',\n forAPIMapping: 'BEFORE calling add_api_endpoints: READ ALL route handlers for the feature. Register every endpoint with accurate method, path, requestShape, responseShapes, requiresAuth.',\n },\n credentials: {\n rule: 'Never hardcode credentials in test code',\n loginFields: hasAuth\n ? 'Use process.env.TEST_USER_EMAIL! and process.env.TEST_USER_PASSWORD!'\n : 'No credentials configured - set TEST_USER_EMAIL and TEST_USER_PASSWORD via set_variable',\n registrationFields: 'MUST use unique email per run: `testuser-${Date.now()}@example.com` - reusing emails causes \"already registered\" failures',\n registrationPassword: \"Use 'TestPass123!' for new account passwords (meets typical strength rules)\",\n },\n variables: {\n configured: varNames,\n baseUrl: (vars.variables as any)?.BASE_URL?.value || 'Not set',\n },\n tags: {\n '@auth': 'Tests the login/auth flow itself. MUST NOT combine with @smoke, @regression, @needs-auth, @critical. CAN include @discovered.',\n '@needs-auth': 'Tests for authenticated pages - MUST include inline login block. CAN combine with @smoke, @regression, @critical.',\n '@smoke': 'Quick sanity checks - run on every deploy',\n '@regression': 'Full regression suite tests',\n '@critical': 'Business-critical paths (informational label - no special suite filtering)',\n '@api': 'API-level tests. Runs in its own project, excluded from suite/smoke/regression runs',\n '@discovered': 'Auto-added to tests generated by AI discovery',\n '@generated': 'Auto-added by AI discovery and API test generation',\n '@manual': 'Default tag for tests created via create_test when no tags specified',\n '@flaky': 'Auto-added after repeated failures. Excluded from suite/smoke/regression runs',\n '@bug-found': 'Added when healer detects an app bug. Test is auto-quarantined',\n '@needs-review': 'Added when DRAFT test fails healing. Requires human attention',\n '@heal-skip': 'Added by healer when test is permanently unfixable. Prevents future auto-heal',\n '@rate-limit-blocked': 'Auto-added by pre-heal classifier when test failure was a rate-limit (HTTP 429). Test skips heal until next pass clears the tag. NOT for use by test authors.',\n '@quota-exceeded': 'Auto-added when failure is a quota/daily-limit response. Skips heal; clears on next pass.',\n '@auth-lost': 'Auto-added when a signed-in test (@needs-auth, authed @api, or a stored-login body) fails on a 401/403 or falls back to the login page. Never on @auth / login-form tests. Skips heal; clears after re-auth + pass.',\n '@rate-limit-expected': 'OPT-OUT tag for tests that intentionally exercise rate-limit behavior (e.g., \"POST /api/login 6 times to trigger lockout\"). Add this tag to ANY @api test that asserts rate-limit responses, otherwise the rate-limit detector will silently downgrade your failure to ERROR. Distinct from auto-pushed @rate-limit-blocked.',\n },\n executionModel: {\n isolation: 'Each test runs as its own separate Playwright process in a fresh browser. No shared state, no storageState, no global setup.',\n authRequired: 'Every @needs-auth test MUST include its own login block. Do NOT suggest storageState or performLogin() - those only work in the regression suite.',\n concurrency: 'Tests run in parallel - runner claims up to 10 per poll, launched 3s apart (~30s per batch). Multiple batches can overlap. Use test.setTimeout(120_000) if the target app is slow under concurrent login load.',\n },\n lifecycle: {\n DRAFT: 'New or unverified test - not included in scheduled runs',\n ACTIVE: 'Verified and running - included in batch/suite executions',\n DISABLED: 'Manually paused - excluded from all runs',\n QUARANTINED: 'Auto-quarantined after repeated failures',\n },\n logging: {\n CRITICAL: 'EVERY request.get/post/put/patch/delete call MUST be followed by a __QA_HTTP__ log line. This is how the platform surfaces request/response data in the Network panel. Missing this = invisible API calls.',\n apiPattern: \"const body = await res.json();\\nconsole.log('__QA_HTTP__:' + JSON.stringify({ method: 'POST', url: '/api/path', status: res.status(), requestBody: { field: value, password: '[REDACTED]' }, responseBody: body }));\",\n rules: [\n 'Call res.json() ONCE, store in body variable - reuse for log and assertions (calling twice throws)',\n 'Log AFTER the request, BEFORE assertions',\n 'Redact sensitive fields: password: \"[REDACTED]\", token: \"[REDACTED]\"',\n 'Use the literal URL string (same as the request call), not a variable',\n 'UI tests using page fixture do NOT need __QA_HTTP__ - only request fixture tests',\n ],\n uiMilestones: \"UI tests (page fixture): add plain console.log() at key milestones - e.g. console.log('Navigated to login page') after page.goto(). These appear in the Console Output panel.\",\n uiLoggingRules: [\n 'Log AFTER the action, not before - confirms the action succeeded',\n 'Include dynamic values where useful: console.log(\"Current URL:\", page.url())',\n 'Keep messages short and human-readable - they show verbatim in the UI',\n 'Do NOT log sensitive values (passwords, tokens)',\n ],\n apiTestStructure: 'Use test.describe.serial() for API tests sharing auth. Independent validation tests (401, 404 checks) go in a SEPARATE non-serial describe block - do not mix them with the auth-dependent serial flow.',\n },\n bestPractices: [\n 'Every @needs-auth test must start with a login block (goto login, fill creds, click submit, waitForURL)',\n 'Use { timeout: 30000 } on waitForURL after login - target apps can be slow under concurrent test load',\n 'Keep login blocks minimal - no assertions on the login page (that is what @auth tests are for)',\n 'After login, page.goto() directly to the page being tested - do not navigate via UI clicks',\n 'Selectors: getByRole(role, { name, exact: true }) for buttons/links/headings, getByLabel(label, { exact: true }) for form fields, getByText(text, { exact: true }) for static copy. CSS ids/classes only for nodes with no accessible name',\n 'URL assertions: path only - await expect(page).toHaveURL(/\\\\/dashboard$/) - never a host',\n 'Registration tests must generate unique email with Date.now()',\n 'Group tests into suites matching feature names exactly (case-sensitive)',\n 'Do NOT suggest storageState or performLogin() for create_test - those only work in the regression suite',\n 'EVERY API test (request fixture) MUST include __QA_HTTP__ log after each request call - see logging section above',\n 'Avoid waitForLoadState(\"networkidle\") - apps with SSE, WebSocket, or analytics connections may never reach idle, causing 60s timeouts. Wait for specific elements instead.',\n 'For headings, use exact: true or level: 1 - getByRole(\"heading\", { name: \"X\" }) matches ALL h1-h6 containing \"X\", causing strict mode violations',\n ],\n pitfalls: {\n CRITICAL: 'These are the top causes of test failures. Read before writing ANY test.',\n strictModeViolations: \"Playwright throws when a locator resolves to 2+ elements. Common causes: getByLabel('Password') matches input AND 'Show password' toggle; getByRole('button', { name: 'Continue' }) matches 'Continue' AND 'Continue with GitHub'. Prevention: getByLabel('Password', { exact: true }) (exact keeps it from matching 'Show password'), { exact: true } for ambiguous button text, scope to a parent container (page.locator('form#login').getByLabel('Email', { exact: true })). Use input[type=\\\"password\\\"] only when the field has no label.\",\n networkIdle: \"NEVER use waitForLoadState('networkidle') - waits for 500ms of zero network activity, which is fragile and causes 30s+ timeouts in apps with polling, analytics, or WebSockets. Use waitForURL() or wait for a specific element instead.\",\n headingStrictMode: \"getByRole('heading', { name: 'Dashboard' }) can match multiple headings (h1 + h2 + breadcrumb). Add { level: 1 } or { exact: true } to disambiguate. Same fix for getByLabel('Password') matching the input AND a 'Show password' toggle: getByLabel('Password', { exact: true }).\",\n postLoginRedirect: \"NEVER assert exact URL after login (e.g. expect(page).toHaveURL('/dashboard')) - apps redirect to different routes per user/role. Use: await page.waitForURL(url => !url.pathname.startsWith('/login'), { timeout: 30000 })\",\n resJsonOnce: \"res.json() consumes the response body stream - calling it twice throws. Store result: const body = await res.json(); then reuse body for logging and assertions.\",\n hiddenInputs: \"Many UI frameworks use visually hidden <input> with custom overlays. page.check() fails because the overlay intercepts clicks. Click the <label> or visible wrapper: page.getByText('Remember me').click()\",\n apiResponseShapes: \"API endpoints often wrap data in a property ({ user: {...} }, { data: [...] }). Read the route handler's res.json() call to see the actual shape. If the handler does res.json({ ticket }), then body is { ticket: { id, ... } } - NOT { id, ... }.\",\n invalidIds: \"Not all routes validate ID format before querying the database. If a route passes the raw ID to an ORM query and gets null back, it returns 404 'not found' - not 400 'bad request'. If unsure, expect either: expect([400, 404]).toContain(res.status())\",\n hardcodedUrls: \"NEVER hardcode full URLs in test code. For UI tests: always use relative paths - page.goto('/login'). The runner sets baseURL from the project's BASE_URL variable. For API tests: use relative paths if the API is on the same domain as the frontend (request.post('/api/auth/login')). If the API is on a SEPARATE domain, use process.env.BASE_API_URL! as a test variable (set via set_variable) and construct URLs: request.post(process.env.BASE_API_URL! + '/auth/login'). NEVER hardcode 'https://example.com/...' in test code - use env vars or relative paths.\",\n credentialFallbacks: \"NEVER use process.env.TEST_USER_EMAIL ?? 'fallback' or || 'fallback'. Use ! (non-null assertion). Missing variable = test should fail immediately, not silently use hardcoded value.\",\n },\n templates: {\n needsAuth: \"test('Feature Name - Test Name', {\\n tag: ['@needs-auth', '@smoke'],\\n}, async ({ page }) => {\\n // Login block - ADAPTED from reading the app's login page component\\n // YOU MUST READ the login page component BEFORE writing this block\\n await page.goto('/login'); // read the router for actual login route\\n await page.getByLabel('Email', { exact: true }).fill(process.env.TEST_USER_EMAIL!); // label text from the component\\n await page.getByLabel('Password', { exact: true }).waitFor({ state: 'visible', timeout: 10000 });\\n await page.getByLabel('Password', { exact: true }).fill(process.env.TEST_USER_PASSWORD!); // input[type=\\\"password\\\"] only if the field has no label\\n await page.getByRole('button', { name: 'Sign in', exact: true }).click(); // the button's accessible name\\n await page.waitForURL(url => !url.pathname.startsWith('/login'), { timeout: 30000 });\\n console.log('Logged in, current URL:', page.url());\\n\\n // Actual test\\n await page.goto('/feature-path');\\n console.log('On feature page');\\n await expect(page.getByRole('heading', { name: /feature name/i })).toBeVisible();\\n});\",\n authTest: \"test('Login - Happy Path', {\\n tag: ['@auth'],\\n}, async ({ page }) => {\\n await page.goto('/auth/login');\\n // test the login form itself - selectors from reading the actual component\\n});\",\n apiSerial: \"test.describe.serial('Feature Name', () => {\\n let token: string;\\n test('authenticate', async ({ request }) => {\\n const res = await request.post('/api/auth/login', {\\n data: { email: process.env.TEST_USER_EMAIL!, password: process.env.TEST_USER_PASSWORD! }\\n });\\n const body = await res.json();\\n console.log('__QA_HTTP__:' + JSON.stringify({\\n method: 'POST', url: '/api/auth/login', status: res.status(),\\n requestBody: { email: process.env.TEST_USER_EMAIL!, password: '[REDACTED]' },\\n responseBody: body,\\n }));\\n expect(res.status()).toBe(200);\\n token = body.access_token; // ← adapt to your API (e.g. body.token, body.jwt)\\n });\\n test('get profile', async ({ request }) => {\\n const res = await request.get('/api/users/profile', {\\n headers: { Authorization: `Bearer ${token}` }\\n });\\n const body = await res.json();\\n console.log('__QA_HTTP__:' + JSON.stringify({\\n method: 'GET', url: '/api/users/profile', status: res.status(),\\n responseBody: body,\\n }));\\n expect(res.status()).toBe(200);\\n });\\n});\",\n apiEndpointMapping: '// After reading an Express route handler like:\\n// router.post(\\'/api/auth/login\\', async (req, res) => { ... })\\n// Call add_api_endpoints with:\\n{\\n featureName: \"Authentication\",\\n endpoints: [{\\n method: \"POST\",\\n path: \"/api/auth/login\",\\n requiresAuth: false,\\n requestShape: { \"email\": \"string\", \"password\": \"string\" },\\n responseShapes: { \"200\": { \"token\": \"string\", \"user\": \"object\" }, \"401\": { \"error\": \"string\" } }\\n }]\\n}',\n uiWithMilestones: \"test('Feature - Happy Path', async ({ page }) => {\\n await page.goto('/login');\\n console.log('Navigated to login page');\\n\\n await page.getByLabel('Email', { exact: true }).fill(process.env.TEST_USER_EMAIL!);\\n await page.getByLabel('Password', { exact: true }).fill(process.env.TEST_USER_PASSWORD!);\\n await page.getByRole('button', { name: 'Sign in', exact: true }).click();\\n console.log('Credentials submitted');\\n\\n await page.waitForURL(url => !url.pathname.startsWith('/login'), { timeout: 15000 });\\n console.log('Logged in, current URL:', page.url());\\n\\n await page.goto('/feature-path');\\n console.log('On feature page');\\n});\",\n },\n testQuality: [\n 'Test actual user flows, not just \"page loads\" - a test that only checks goto + heading visible is nearly worthless',\n 'Test form submission: fill fields, submit, verify success/redirect',\n 'Test validation: leave required fields empty, enter invalid data, verify error messages',\n 'Test error states: wrong password, expired session, invalid IDs',\n 'Test the happy path end-to-end: login → navigate → perform action → verify result',\n 'Each test should assert something meaningful about the application behavior',\n ],\n securityAudit: {\n workflow: 'After creating UI tests for a feature, call run_security_audit to analyze captured API traffic for auth issues, data exposure, and vulnerabilities.',\n prerequisite: 'Requires prior browser-based test execution (the auto-verification run from create_test counts). If run_security_audit errors about missing data, tell the developer to click \"Security Audit\" in the Tests dropdown on the Dashboard - this launches a live browser to capture real network traffic (HAR) and runs analysis automatically.',\n reviewing: 'Use list_security_findings to review results. Filter by severity (critical/high/medium/low/info) or status (open/acknowledged/resolved/false-positive). Critical and high findings should be flagged to the developer immediately.',\n },\n keyConcepts: {\n features: 'Group related pages and tests (e.g., \"Authentication\" covers /auth/login, /auth/register). MUST include page routes.',\n pages: 'Route URLs on a feature - used for coverage tracking and site map (e.g., [\"/login\", \"/register\"])',\n suites: 'Group tests for batch execution - suite name MUST match feature name exactly (case-sensitive)',\n runner: 'Executes tests - can be local (developer machine) or cloud',\n testData: 'Key-value variables injected into tests (e.g., credentials, URLs)',\n },\n retrievedAt: new Date().toISOString(),\n };\n return { contents: [{ uri: 'project://test-conventions', mimeType: 'application/json', text: JSON.stringify(conventions, null, 2) }] };\n } catch (err) {\n return { contents: [{ uri: 'project://test-conventions', mimeType: 'text/plain', text: `Failed to load conventions: ${err instanceof Error ? err.message : String(err)}` }] };\n }\n },\n);\n\n// Connect via stdio transport\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n","import { readFileSync } from 'fs';\nimport { resolve } from 'path';\n\nexport interface ValidateQAConfig {\n apiUrl: string;\n token: string;\n projectId: string;\n}\n\nfunction parseArgs(argv: string[]): Record<string, string> {\n const args: Record<string, string> = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg.startsWith('--') && i + 1 < argv.length) {\n const key = arg.slice(2);\n args[key] = argv[++i];\n }\n }\n return args;\n}\n\nfunction loadDotFile(): Partial<ValidateQAConfig> {\n try {\n const content = readFileSync(resolve(process.cwd(), '.validateqa.json'), 'utf-8');\n const json = JSON.parse(content);\n return {\n apiUrl: typeof json.apiUrl === 'string' ? json.apiUrl : undefined,\n projectId: typeof json.projectId === 'string' ? json.projectId : undefined,\n };\n } catch {\n return {};\n }\n}\n\nexport function resolveConfig(): ValidateQAConfig {\n const cliArgs = parseArgs(process.argv.slice(2));\n const dotFile = loadDotFile();\n\n const apiUrl =\n cliArgs['api-url'] ??\n process.env.VALIDATEQA_API_URL ??\n dotFile.apiUrl;\n\n const token =\n cliArgs['token'] ??\n process.env.VALIDATEQA_TOKEN;\n\n const projectId =\n cliArgs['project-id'] ??\n process.env.VALIDATEQA_PROJECT_ID ??\n dotFile.projectId;\n\n if (!apiUrl) {\n console.error('Missing required config: api-url (--api-url, VALIDATEQA_API_URL, or .validateqa.json)');\n process.exit(1);\n }\n if (!token) {\n console.error('Missing required config: token (--token or VALIDATEQA_TOKEN)');\n process.exit(1);\n }\n if (!projectId) {\n console.error('Missing required config: project-id (--project-id, VALIDATEQA_PROJECT_ID, or .validateqa.json)');\n process.exit(1);\n }\n\n return { apiUrl: apiUrl.replace(/\\/$/, ''), token, projectId };\n}\n","/**\n * Same string as `PLAN_FEATURE_LOCKED_CODE` in `@validateqa/shared`.\n * This package does not depend on shared.\n */\nexport const PLAN_FEATURE_LOCKED_CODE = 'PLAN_FEATURE_LOCKED';\n\nexport class ApiResponseError extends Error {\n readonly status: number;\n readonly body: Record<string, unknown>;\n\n constructor(status: number, body: Record<string, unknown>) {\n const message = typeof body.error === 'string' && body.error.length > 0\n ? body.error\n : `API error ${status}`;\n super(message);\n this.name = 'ApiResponseError';\n this.status = status;\n this.body = body;\n }\n}\n\n/** Tool text for a thrown client error. A plan lock keeps the structured body. */\nexport function toolErrorText(err: unknown): string {\n if (err instanceof ApiResponseError && err.body.code === PLAN_FEATURE_LOCKED_CODE) {\n return JSON.stringify(err.body);\n }\n return `Error: ${err instanceof Error ? err.message : String(err)}`;\n}\n\nexport class ValidateQAClient {\n constructor(\n private baseUrl: string,\n private token: string,\n private projectId: string,\n ) {}\n\n async executeTool(tool: string, args: Record<string, unknown> = {}): Promise<unknown> {\n let res: Response;\n try {\n res = await fetch(`${this.baseUrl}/api/mcp/execute`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${this.token}`,\n 'X-Project-Id': this.projectId,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ tool, args }),\n signal: AbortSignal.timeout(120_000),\n });\n } catch (err) {\n // Network errors, DNS failures, timeouts\n const cause = err instanceof Error && err.cause instanceof Error ? err.cause.message : '';\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Connection failed: ${msg}${cause ? ` (${cause})` : ''}`);\n }\n\n if (!res.ok) {\n const parsed = await res.json().catch(() => ({ error: res.statusText }));\n const body = parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? parsed as Record<string, unknown>\n : { error: res.statusText };\n throw new ApiResponseError(res.status, body);\n }\n\n return res.json();\n }\n\n /** project://test-conventions from the server (GET /api/mcp/test-conventions); null when the server predates it. */\n async getTestConventions(): Promise<unknown | null> {\n try {\n const res = await fetch(`${this.baseUrl}/api/mcp/test-conventions`, {\n headers: {\n 'Authorization': `Bearer ${this.token}`,\n 'X-Project-Id': this.projectId,\n },\n signal: AbortSignal.timeout(30_000),\n });\n if (!res.ok) return null;\n return await res.json();\n } catch {\n return null;\n }\n }\n\n async healthCheck(): Promise<boolean> {\n try {\n const res = await fetch(`${this.baseUrl}/health`, {\n signal: AbortSignal.timeout(5000),\n });\n return res.ok;\n } catch {\n return false;\n }\n }\n}\n","import { z } from 'zod';\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { toolErrorText, type ValidateQAClient } from '../api-client.js';\n\ntype ToolAnnotations = {\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n};\n\nfunction tool(\n server: McpServer,\n client: ValidateQAClient,\n name: string,\n description: string,\n schema: Record<string, z.ZodTypeAny>,\n annotations?: ToolAnnotations,\n) {\n const handler = async (args: Record<string, unknown>) => {\n try {\n const result = await client.executeTool(name, args);\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: toolErrorText(err) }],\n isError: true,\n };\n }\n };\n\n if (annotations) {\n server.tool(name, description, schema, annotations, handler);\n } else {\n server.tool(name, description, schema, handler);\n }\n}\n\n// The server answers one wait call within SERVER_WAIT_MAX_SECONDS (its proxy\n// cuts requests at 60 s). A longer wait here, up to WAIT_MAX_SECONDS, is a\n// chain of calls: each continues with wait_for_run / wait_for_batch until the\n// run is done or the time is used up.\nconst SERVER_WAIT_MAX_SECONDS = 55;\nconst WAIT_DEFAULT_SECONDS = 50;\nconst WAIT_MAX_SECONDS = 120;\n\ntype WaitKind = { tool: 'wait_for_run'; idKey: 'runId' } | { tool: 'wait_for_batch'; idKey: 'batchId' };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction waitSecondsFrom(raw: unknown, fallback: number): number {\n const n = typeof raw === 'number' ? raw : Number.NaN;\n if (!Number.isFinite(n)) return fallback;\n return Math.min(Math.max(n, 0), WAIT_MAX_SECONDS);\n}\n\n/**\n * Call `name` with up to SERVER_WAIT_MAX_SECONDS of `waitKey`, then keep\n * waiting with `kind.tool` while the result says timedOut and time is left.\n */\nasync function executeWithWait(\n client: ValidateQAClient,\n name: string,\n args: Record<string, unknown>,\n waitKey: 'waitSeconds' | 'timeoutSeconds',\n totalSeconds: number,\n kind: WaitKind,\n): Promise<unknown> {\n const deadline = Date.now() + totalSeconds * 1000;\n const first = Math.min(totalSeconds, SERVER_WAIT_MAX_SECONDS);\n let result = await client.executeTool(name, { ...args, [waitKey]: first });\n for (;;) {\n if (!isRecord(result) || result.timedOut !== true) return result;\n const id = result[kind.idKey];\n const left = Math.floor((deadline - Date.now()) / 1000);\n if (typeof id !== 'string' || left < 1) return result;\n result = await client.executeTool(kind.tool, { [kind.idKey]: id, timeoutSeconds: Math.min(left, SERVER_WAIT_MAX_SECONDS) });\n }\n}\n\nfunction waitTool(\n server: McpServer,\n client: ValidateQAClient,\n name: string,\n description: string,\n schema: Record<string, z.ZodTypeAny>,\n waitKey: 'waitSeconds' | 'timeoutSeconds',\n defaultSeconds: number,\n kind: WaitKind,\n annotations?: ToolAnnotations,\n) {\n const handler = async (args: Record<string, unknown>) => {\n try {\n const seconds = waitSecondsFrom(args[waitKey], defaultSeconds);\n const result = seconds > 0\n ? await executeWithWait(client, name, args, waitKey, seconds, kind)\n : await client.executeTool(name, args);\n return { content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }] };\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: toolErrorText(err) }],\n isError: true,\n };\n }\n };\n if (annotations) {\n server.tool(name, description, schema, annotations, handler);\n } else {\n server.tool(name, description, schema, handler);\n }\n}\n\nexport function registerAllTools(server: McpServer, client: ValidateQAClient) {\n // ── Test Management ──────────────────────────────────────────────────\n\n tool(server, client, 'list_tests',\n 'List tests in the current project. Returns test name, status, suite, tags, confidence, and the last run result. Paginated - use limit/offset to page through all tests.',\n {\n status: z.enum(['DRAFT', 'ACTIVE', 'DISABLED', 'QUARANTINED']).optional().describe('Filter by test lifecycle status'),\n suite: z.string().optional().describe('Filter by suite name'),\n search: z.string().optional().describe('Search test names (case-insensitive substring match)'),\n tag: z.string().optional().describe('Filter by tag (e.g. @regression, @smoke, @auth)'),\n limit: z.number().optional().describe('Max results to return (default: 50, max: 200)'),\n offset: z.number().optional().describe('Number of results to skip for pagination (default: 0)'),\n },\n { readOnlyHint: true },\n );\n\n tool(server, client, 'get_test',\n 'Get details of a specific test: name, status, tags, steps, session, and the 5 most recent run results. Code is truncated to 200 lines - use get_test_code for the full Playwright code.',\n { testId: z.string().describe('The test case ID') },\n { readOnlyHint: true },\n );\n\n waitTool(server, client, 'run_test',\n 'Queue a test for execution. Creates a PENDING test run that will be picked up by an online runner. Returns the run ID; with waitSeconds, the finished run (as wait_for_run). For a mobile (Appium) test, pass platform to run it on the OTHER platform than it was authored on - if some steps lack a native locator for that platform, a one-time locator-discovery pass runs first (supply appId once for the target-platform build), then the test runs automatically.',\n {\n testId: z.string().describe('The test case ID to run'),\n platform: z.enum(['IOS', 'ANDROID']).optional().describe('Mobile only: run this test on the given platform (cross-platform run). Omit to run on the authoring platform.'),\n appId: z.string().optional().describe('Mobile cross-platform only: the target-platform app id (bundleId/appPackage). Only needed the first time this project runs on the other platform.'),\n waitSeconds: z.number().min(0).max(WAIT_MAX_SECONDS).optional().describe(`Optional. Wait up to this many seconds (max ${WAIT_MAX_SECONDS}) for the run to finish and return its final result, like wait_for_run (timedOut: true if still going). 0 or omitted: return at once with the run ID.`),\n },\n 'waitSeconds', 0, { tool: 'wait_for_run', idKey: 'runId' },\n );\n\n tool(server, client, 'delete_test',\n 'Permanently delete a test case and all its run history. Cannot be undone.',\n { testId: z.string().describe('The test case ID to delete') },\n { destructiveHint: true },\n );\n\n tool(server, client, 'heal_test',\n 'Queue an AI healing run for a failing test. The AI agent replays the test in a real browser, analyzes the failure, and either fixes the Playwright code OR detects an application bug (quarantines the test with @bug-found if the app itself is broken, not the test).',\n { testId: z.string().describe('The failing test case ID') },\n );\n\n tool(server, client, 'edit_test_code',\n 'Update an existing test case. WEB (Playwright) tests: provide the full replacement playwrightCode (read project://test-conventions for patterns; code is validated - fix any warnings returned). MOBILE (Appium) tests: provide the FULL replacement steps array (playwrightCode is rejected - mobile tests execute structured steps, not code). Read the current form first with get_test_code.',\n {\n testId: z.string().describe('The test case ID to edit'),\n playwrightCode: z.string().optional().describe('Web tests only: new Playwright test code (full file replacement)'),\n steps: z.array(z.record(z.unknown())).optional().describe('Mobile (Appium) tests only: FULL replacement structured step array (same shape as create_test steps). Include every step, not just the changed ones.'),\n name: z.string().optional().describe('New test name'),\n tags: z.array(z.string()).optional().describe('New tags array (e.g. [\"@regression\", \"@smoke\"])'),\n },\n );\n\n tool(server, client, 'update_test_status',\n 'Change the lifecycle status of one or more tests (e.g. promote DRAFT→ACTIVE, disable a flaky test). Re-activating exactly ONE bug-found test (QUARANTINED→ACTIVE) also queues a verification run and returns its testRunId; with several ids no run is queued.',\n {\n testIds: z.array(z.string()).describe('Test IDs to update'),\n status: z.enum(['DRAFT', 'ACTIVE', 'DISABLED', 'QUARANTINED']).describe('New status to set'),\n },\n );\n\n // ── Test Runs ────────────────────────────────────────────────────────\n\n tool(server, client, 'get_test_run',\n 'Get the status and result of a specific test run once (to wait for it to finish, use wait_for_run, not a loop of this). Look up by runId, or the latest run for a testId. A FAILED or ERROR run also carries its failure evidence: error (up to 4 KB), consoleLog (the last 200 lines, at most 20 KB), failedSteps, and for a mobile run domSnapshot (the page source at the failure). Screenshots: get_test_screenshots. No Playwright trace is recorded.',\n {\n runId: z.string().optional().describe('The test run ID'),\n testId: z.string().optional().describe('Get the most recent run for this test case ID'),\n },\n { readOnlyHint: true },\n );\n\n waitTool(server, client, 'wait_for_run',\n `Wait until a test run (run_test, heal_test, a verification run) is PASSED, FAILED or ERROR, then return it in the get_test_run shape, failure evidence included. Returns after at most timeoutSeconds (default ${WAIT_DEFAULT_SECONDS}, max ${WAIT_MAX_SECONDS}) with timedOut: true and the current status if it is still pending or running; call it again to keep waiting. Use this instead of polling get_test_run.`,\n {\n runId: z.string().describe('The test run ID to wait for'),\n timeoutSeconds: z.number().min(0).max(WAIT_MAX_SECONDS).optional().describe(`How long to wait, in seconds (default ${WAIT_DEFAULT_SECONDS}, max ${WAIT_MAX_SECONDS})`),\n },\n 'timeoutSeconds', WAIT_DEFAULT_SECONDS, { tool: 'wait_for_run', idKey: 'runId' },\n { readOnlyHint: true },\n );\n\n waitTool(server, client, 'wait_for_batch',\n `Wait until a batch from batch_run_tests is COMPLETED, then return its counts (total, completed, passed, failed, errored) and, when tests failed, up to 20 failures with their runId and error. Returns after at most timeoutSeconds (default ${WAIT_DEFAULT_SECONDS}, max ${WAIT_MAX_SECONDS}) with timedOut: true and the current counts if it is still running; call it again to keep waiting. Use get_test_run on a failure's runId for its console log.`,\n {\n batchId: z.string().describe('The batch ID returned by batch_run_tests'),\n timeoutSeconds: z.number().min(0).max(WAIT_MAX_SECONDS).optional().describe(`How long to wait, in seconds (default ${WAIT_DEFAULT_SECONDS}, max ${WAIT_MAX_SECONDS})`),\n },\n 'timeoutSeconds', WAIT_DEFAULT_SECONDS, { tool: 'wait_for_batch', idKey: 'batchId' },\n { readOnlyHint: true },\n );\n\n tool(server, client, 'run_discovery',\n 'Start AI discovery for this project. For web, discovery uses the configured base URL. For mobile, pass platform and appId to explore a native app on a connected runner/device. Use survey to map features, deep with featureName to generate tests for one feature, or full for broad generation.',\n {\n mode: z.enum(['survey', 'deep', 'full']).optional().describe('Discovery mode. survey maps features/screens and generates no tests; deep generates tests for one feature; full explores and generates broadly.'),\n featureName: z.string().optional().describe('Required for deep mode: the feature name to generate tests for.'),\n focusAreas: z.array(z.string()).optional().describe('Optional routes, screens, or areas to focus discovery on.'),\n platform: z.enum(['IOS', 'ANDROID']).optional().describe('Mobile only: target platform. Requires appId.'),\n appId: z.string().optional().describe('Mobile only: bundle id/package id to explore. Requires platform.'),\n resetPolicy: z.enum(['AUTO', 'CLEAR_APP_DATA', 'PRESERVE_APP_DATA']).optional().describe('Mobile only: app-state policy for discovery/replay. AUTO uses default safe reset behavior.'),\n },\n );\n\n tool(server, client, 'get_discovery_status',\n 'Check progress for a discovery run. Omit discoveryRunId to get the latest discovery run for this project.',\n {\n discoveryRunId: z.string().optional().describe('Specific discovery run ID. Omit for latest.'),\n },\n { readOnlyHint: true },\n );\n\n // Custom handler - returns MCP image content blocks so the AI can see screenshots\n server.tool(\n 'get_test_screenshots',\n 'Get screenshots from a specific test run as images the AI can actually see. Use this to visually inspect what happened during a failed or passing run.',\n {\n runId: z.string().describe('The test run ID to fetch screenshots from'),\n limit: z.number().optional().describe('Max screenshots to return (default: 5, max: 10)'),\n },\n { readOnlyHint: true },\n async (args) => {\n try {\n const result = await client.executeTool('get_test_screenshots', args) as {\n runId: string;\n status: string;\n total: number;\n returned: number;\n screenshots: Array<{ index: number; data: string; mimeType: string }>;\n };\n\n if (!result.screenshots || result.screenshots.length === 0) {\n return {\n content: [{\n type: 'text' as const,\n text: `No screenshots available for run ${result.runId} (status: ${result.status})`,\n }],\n };\n }\n\n const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [\n {\n type: 'text' as const,\n text: `Run ${result.runId} - status: ${result.status} - showing ${result.returned} of ${result.total} screenshot(s)`,\n },\n ];\n\n for (const shot of result.screenshots) {\n content.push({ type: 'image' as const, data: shot.data, mimeType: shot.mimeType });\n }\n\n return { content };\n } catch (err) {\n return {\n content: [{ type: 'text' as const, text: toolErrorText(err) }],\n isError: true,\n };\n }\n },\n );\n\n tool(server, client, 'cancel_test_run',\n 'Cancel a pending or running test run. Can cancel by run ID or cancel the latest running batch.',\n {\n runId: z.string().optional().describe('The specific test run ID to cancel'),\n cancelBatch: z.boolean().optional().describe('If true, cancel the latest batch run instead'),\n },\n );\n\n waitTool(server, client, 'batch_run_tests',\n 'Run multiple tests from the database individually. Filter by test IDs or suite name; omit both to run all ACTIVE tests. Each test executes in its own browser. Returns the batchId; follow it with wait_for_batch, or pass waitSeconds.',\n {\n testIds: z.array(z.string()).optional().describe('Specific test IDs to run'),\n suite: z.string().optional().describe('Run all active tests in this suite'),\n waitSeconds: z.number().min(0).max(WAIT_MAX_SECONDS).optional().describe(`Optional. Wait up to this many seconds (max ${WAIT_MAX_SECONDS}) for the batch to complete and return the wait_for_batch result (timedOut: true if still running). 0 or omitted: return at once with the batchId.`),\n },\n 'waitSeconds', 0, { tool: 'wait_for_batch', idKey: 'batchId' },\n );\n\n // ── Features & API Endpoints ──────────────────────────────────────────\n\n tool(server, client, 'list_features',\n 'List all features with test counts and failure counts (last 24h). Use failingTests > 0 to identify which features need attention, then call get_test_failures({ suite: featureName }) to drill into the full error details for that feature.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'generate_tests_for_feature',\n 'Start test generation for an existing feature by id or name. For mobile, run_discovery with mode=deep, featureName, platform, and appId gives explicit device/platform control.',\n {\n featureId: z.string().optional().describe('Feature ID. Either featureId or featureName is required.'),\n featureName: z.string().optional().describe('Feature name. Either featureId or featureName is required.'),\n },\n );\n\n tool(server, client, 'list_api_endpoints',\n 'List captured API endpoints for the current project. Optionally scope to a specific feature name.',\n {\n featureName: z.string().optional().describe('Optional feature name to scope the endpoint list'),\n },\n { readOnlyHint: true },\n );\n\n // ── Infrastructure ───────────────────────────────────────────────────\n\n tool(server, client, 'get_runner_health',\n 'Check whether the project\\'s configured runners are online, including available device capabilities.',\n {},\n { readOnlyHint: true },\n );\n\n // ── Reports & Observability ──────────────────────────────────────────\n\n tool(server, client, 'get_project_overview',\n 'Get a workspace-level QA overview: test counts, pass rates, runner readiness, features, coverage gaps, variables, schedules, and notifications.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'get_reports_summary',\n 'Get a high-level report: total tests (active, never-run), 7-day pass rate, today\\'s run count, and the 10 most recent test run results.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'get_regression_stats',\n 'Get test counts by lifecycle status (active, quarantined, draft, disabled, total; API specs count their inner tests) and the 7-day pass rate, with rate-limit, config-issue and cancelled runs left out. The same numbers as the dashboard\\'s regression stats.',\n {},\n { readOnlyHint: true },\n );\n\n // ── Schedules (Admin) ────────────────────────────────────────────────\n\n tool(server, client, 'list_schedules',\n 'List all scheduled test runs in the project.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'create_schedule',\n 'Create a new recurring test schedule. Runs all matching tests from the database on the configured interval.',\n {\n name: z.string().describe('Name for the schedule (e.g. \"Nightly smoke tests\")'),\n mode: z.enum(['batch']).describe('Run mode: batch (runs project tests from the database)'),\n intervalMinutes: z.union([z.literal(60), z.literal(360), z.literal(720), z.literal(1440), z.literal(2880), z.literal(10080)]).describe('Interval in minutes: 60 (hourly), 360 (6h), 720 (12h), 1440 (daily), 2880 (2 days), 10080 (weekly)'),\n tags: z.array(z.string()).optional().describe('Tags to filter which tests run (e.g. [\"@smoke\"]). Omit to run all ACTIVE tests.'),\n autoHeal: z.boolean().optional().describe(\"Heal this schedule's failed runs (default false). Takes effect only while the project's auto-heal (toggle_auto_heal) is on: a run is healed only when both are on.\"),\n enabled: z.boolean().optional().describe('Whether the schedule is active (default: true)'),\n runImmediately: z.boolean().optional().describe('Whether to trigger the first run immediately (default: true)'),\n },\n );\n\n tool(server, client, 'update_schedule',\n 'Update an existing test schedule.',\n {\n scheduleId: z.string().describe('The schedule ID to update'),\n name: z.string().optional().describe('New name for the schedule'),\n intervalMinutes: z.union([z.literal(60), z.literal(360), z.literal(720), z.literal(1440), z.literal(2880), z.literal(10080)]).optional().describe('New interval in minutes'),\n suite: z.string().optional().describe('New suite name to filter tests'),\n tags: z.array(z.string()).optional().describe('New tag filter'),\n autoHeal: z.boolean().optional().describe(\"Heal this schedule's failed runs. Takes effect only while the project's auto-heal (toggle_auto_heal) is on.\"),\n enabled: z.boolean().optional().describe('Enable or disable the schedule'),\n },\n );\n\n tool(server, client, 'delete_schedule',\n 'Delete (remove) a test schedule permanently.',\n { scheduleId: z.string().describe('The schedule ID to delete') },\n { destructiveHint: true },\n );\n\n tool(server, client, 'run_schedule_now',\n 'Trigger a scheduled run immediately instead of waiting for the next scheduled time.',\n { scheduleId: z.string().describe('The schedule ID to trigger') },\n );\n\n // ── Configuration ────────────────────────────────────────────────────\n\n tool(server, client, 'get_variables',\n 'Get all test variables (environment variables) for the current project. Secrets are redacted.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'set_variable',\n 'Set or update a test variable (environment variable) for the project. Used to configure base URLs, credentials, etc.',\n {\n key: z.string().describe('Variable name (e.g. BASE_URL, TEST_USER_EMAIL, API_KEY)'),\n value: z.string().describe('Variable value. Set value to empty string to remove a variable.'),\n secret: z.boolean().optional().describe('Whether this variable is a secret (will be redacted in UI)'),\n },\n );\n\n tool(server, client, 'create_test',\n 'Create a new test case. WEB projects: provide playwrightCode (read project://test-conventions for templates BEFORE writing code; on a production BASE_URL use its read-only guard template). The response may carry warnings (weak selectors, hardcoded hosts in URL assertions, vacuous checks, a missing read-only guard) - they never block, fix them with edit_test_code. MOBILE (Appium) projects: provide steps - a structured step array is the ONLY executable form for mobile (code is never executed). The test starts as DRAFT - auto-runs and auto-promotes to ACTIVE on pass. IMPORTANT: (1) Set suite to the EXACT feature name. (2) After creating all tests for a web feature, you MUST call add_api_endpoints.',\n {\n name: z.string().describe('Test name (e.g. \"Login - Happy Path\")'),\n playwrightCode: z.string().optional().describe('Web projects: full Playwright test code (required). Mobile projects: optional WebdriverIO export for humans - never executed.'),\n steps: z.array(z.record(z.unknown())).optional().describe('Mobile (Appium) projects ONLY - required. Ordered steps: { action: tap|type|clear|swipe|scroll|back|home|waitForElement|assertVisible|assertText, description, target?: { primary, fallbacks?, screenName? }, value? }. target.primary: \"css=#domId\" for WebView-rendered (hybrid) controls, resource-id/accessibility-id/text= only for genuinely native UI. type/assertText require value ({{TEST_VAR}} placeholders supported). Do not author OS permission-dialog taps. End with an assert step. Call get_feature first for mapped screens + known selectors.'),\n suite: z.string().optional().describe('MUST match an existing feature name exactly to link the test to that feature (e.g. \"Authentication\", not \"Auth Tests\")'),\n tags: z.array(z.string()).optional().describe('Tags (e.g. [\"@smoke\", \"@auth\"])'),\n },\n );\n\n // ── Features ─────────────────────────────────────────────────────────\n\n tool(server, client, 'get_feature',\n 'Get detailed info about a feature including its pages, test plans, existing tests with lastRunStatus, and AI insights.',\n { featureName: z.string().describe('The feature name (case-insensitive match)') },\n { readOnlyHint: true },\n );\n\n tool(server, client, 'get_spec_coverage',\n 'Map spec items to the existing tests of a feature (heuristic: test names, tags and the copy in their code) and list the items no test covers yet. Pass the spec you were given as one item per line item, scoped by page (\"Sign up: malformed email shows an error\"); without specItems it uses the feature\\'s stored test plans. Call it before you stop writing tests for a feature, then cover every uncovered item.',\n {\n featureName: z.string().describe('The feature name (case-insensitive) - its suite holds the tests'),\n specItems: z.array(z.string()).optional().describe('Spec items, one per behaviour and page (max 200)'),\n },\n { readOnlyHint: true },\n );\n\n tool(server, client, 'create_feature',\n 'Create a new feature with page routes. Read the developer\\'s route files to provide accurate page URLs. Pages are used for coverage tracking and site map. Idempotent, not an upsert: if an active feature with this name already exists it is returned unchanged with existing: true (use update_feature with its id to change it). Fails only when the name belongs to an archived feature (restore it with restore_feature, or pick another name).',\n {\n name: z.string().describe('Feature name (e.g. \"Checkout Flow\")'),\n description: z.string().optional().describe('What the feature does and what to test'),\n pages: z.array(z.string()).describe('Page routes this feature covers (e.g. [\"/checkout\", \"/checkout/payment\"]). Required for test generation.'),\n criticality: z.enum(['critical', 'high', 'medium', 'low']).optional().describe('Feature criticality level (default: medium)'),\n },\n );\n\n // ── Full Test Code ───────────────────────────────────────────────────\n\n tool(server, client, 'get_test_code',\n 'Get the full (untruncated) Playwright test code for a test case. Use this when you need to read, analyze, or prepare edits for the complete test code.',\n { testId: z.string().describe('The test case ID') },\n { readOnlyHint: true },\n );\n\n // ── Project Settings ─────────────────────────────────────────────────\n\n tool(server, client, 'set_runner_preference',\n 'Switch between cloud and local runner for test execution.',\n { preference: z.enum(['cloud', 'local']).describe('Runner type: cloud (shared infrastructure) or local (runs on your machine)') },\n );\n\n tool(server, client, 'toggle_auto_heal',\n 'Enable or disable automatic AI healing when tests fail: the verification run after create_test, batch and suite runs. When off, no heal is queued automatically; heal_test still works.',\n { enabled: z.boolean().describe('true to enable auto-heal, false to disable') },\n );\n\n // ── Test Data ────────────────────────────────────────────────────────\n\n tool(server, client, 'list_test_data',\n 'List all test data sets in the project. Each set contains key-value pairs injected into AI prompts and test runs.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'create_test_data',\n 'Create a new test data set with key-value pairs. Max 200 entries per set.',\n {\n name: z.string().describe('Name of the test data set (max 100 chars)'),\n description: z.string().optional().describe('Optional description (max 1000 chars)'),\n data: z.record(z.string()).describe('Key-value pairs (e.g. {\"email\": \"test@example.com\", \"password\": \"secret\"})'),\n },\n );\n\n tool(server, client, 'delete_test_data',\n 'Delete a test data set by ID.',\n { dataSetId: z.string().describe('The test data set ID to delete') },\n { destructiveHint: true },\n );\n\n // ── Feature Management ───────────────────────────────────────────────\n\n tool(server, client, 'update_feature',\n 'Update a feature\\'s name, description, pages, or criticality.',\n {\n featureId: z.string().describe('The feature ID to update'),\n name: z.string().optional().describe('New feature name'),\n description: z.string().optional().describe('New description'),\n pages: z.array(z.string()).optional().describe('Updated page routes'),\n criticality: z.enum(['critical', 'high', 'medium', 'low']).optional().describe('Feature criticality level'),\n },\n );\n\n tool(server, client, 'archive_feature',\n 'Archive a feature (soft delete). Archived features are hidden from the dashboard but can be restored with restore_feature.',\n { featureId: z.string().describe('The feature ID to archive') },\n { destructiveHint: true },\n );\n\n tool(server, client, 'restore_feature',\n 'Restore an archived feature so it shows in the dashboard again. Does nothing for a feature that is already active. Fails if an active feature now holds the same name.',\n { featureId: z.string().describe('The ID of the archived feature to restore') },\n );\n\n // ── Site Map ─────────────────────────────────────────────────────────\n\n tool(server, client, 'get_site_map_coverage',\n 'Get site map coverage statistics: total pages, pages with tests, elements covered, coverage percentage, and per-page breakdown.',\n {},\n { readOnlyHint: true },\n );\n\n // ── Issue Triage ─────────────────────────────────────────────────────\n\n tool(server, client, 'list_bugs',\n 'Get all detected bugs: app bugs (quarantined tests with @bug-found), security findings, flaky tests, and visual issues flagged as bugs.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'list_visual_issues',\n 'List visual issues found on the app\\'s pages by the layout checks that run during surveys and discovery (clipped or overflowing text, covered or cut-off controls, broken images, sideways scrolling on phones, small tap targets, low contrast). Each has the page route, viewport, CSS selector, element box and a description, so you can find and fix the element in the code. Visual issues never fail tests.',\n {\n status: z.enum(['OPEN', 'ACCEPTED', 'DISMISSED', 'GONE']).optional().describe('Filter by status (default OPEN). ACCEPTED = flagged as a bug; GONE = no longer seen on the page'),\n severity: z.enum(['high', 'medium', 'low']).optional().describe('Filter by severity'),\n viewport: z.enum(['desktop', 'phone']).optional().describe('Filter by viewport'),\n route: z.string().optional().describe('Only this page route, e.g. /pricing'),\n },\n { readOnlyHint: true },\n );\n\n tool(server, client, 'flag_as_bug',\n 'Mark a failing test as a confirmed application bug - quarantines it with @bug-found and records the bug description. Use when the failure is caused by broken app behaviour, NOT a test script issue. Do NOT use for selector changes or timeout failures - use heal_test or edit_test_code for those.',\n {\n testId: z.string().describe('The failing test case ID'),\n description: z.string().describe('What is broken in the application (e.g. \"POST /api/checkout returns 500 when payment method is valid\")'),\n },\n );\n\n // ── Security Audit ───────────────────────────────────────────────────\n\n tool(server, client, 'run_security_audit',\n 'Run an AI security audit on captured API traffic. Requires prior browser-based test execution (discovery or capture) - analyzes real network traffic, not just registered endpoints. If no traffic exists, the developer can trigger \"Security Audit\" from the Dashboard which launches a live browser to capture it.',\n {},\n );\n\n tool(server, client, 'list_security_findings',\n 'List security audit findings with optional filters. Returns severity, category, status, and affected endpoints.',\n {\n severity: z.enum(['critical', 'high', 'medium', 'low', 'info']).optional().describe('Filter by severity'),\n status: z.enum(['open', 'acknowledged', 'resolved', 'false-positive']).optional().describe('Filter by status'),\n },\n { readOnlyHint: true },\n );\n\n // ── Project Settings ─────────────────────────────────────────────────\n\n tool(server, client, 'set_app_brief',\n 'Set or update the project\\'s application brief - a description of the app used by AI for better test generation.',\n { appBrief: z.string().describe('Application description. Set empty to clear.') },\n );\n\n // ── Coverage & Draft Verification ────────────────────────────────────\n\n tool(server, client, 'get_coverage_summary',\n 'Get feature-level test coverage: planned vs existing vs passing tests, plus API endpoint coverage. Shows uncoveredEndpoints per feature - use this to find which API endpoints still need tests.',\n {},\n { readOnlyHint: true },\n );\n\n tool(server, client, 'run_draft_tests',\n 'Run all DRAFT tests to verify them. Tests that pass auto-promote to ACTIVE. Optionally scope to a feature.',\n {\n featureName: z.string().optional().describe('Only run drafts for this feature (optional)'),\n },\n );\n\n // ── Project Setup ────────────────────────────────────────────────────\n\n tool(server, client, 'setup_project',\n 'One-shot project setup from codebase knowledge. Sets app brief, base URL, test credentials, and creates features with pages - all in one call. Use this when a developer says \"set up test coverage for my app.\"',\n {\n appBrief: z.string().optional().describe('Description of the application (what it does, key features, tech stack)'),\n baseUrl: z.string().describe('Application base URL (e.g. \"https://myapp.com\" or \"http://localhost:3000\")'),\n testCredentials: z.object({\n email: z.string().optional().describe('Test user email'),\n password: z.string().optional().describe('Test user password'),\n }).optional().describe('Login credentials for test execution'),\n features: z.array(z.object({\n name: z.string().describe('Feature name'),\n description: z.string().optional().describe('What the feature does'),\n pages: z.array(z.string()).describe('Page routes (e.g. [\"/login\", \"/register\"])'),\n criticality: z.enum(['critical', 'high', 'medium', 'low']).optional().describe('Feature criticality'),\n })).describe('Features to create with their page routes'),\n },\n );\n\n // ── API Endpoints ───────────────────────────────────────────────────\n\n tool(server, client, 'add_api_endpoints',\n 'Register API endpoints for a feature from codebase knowledge. Read the developer\\'s route handlers to extract methods, paths, request/response shapes. Populates the API intelligence dashboard.',\n {\n featureName: z.string().describe('Feature name to link these endpoints to'),\n endpoints: z.array(z.object({\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).describe('HTTP method'),\n path: z.string().describe('API path (e.g. \"/api/auth/login\")'),\n requestShape: z.record(z.string()).optional().describe('Request body fields with types (e.g. { \"email\": \"string\" })'),\n responseShapes: z.record(z.record(z.string())).optional().describe('Response shapes by status code (e.g. { \"200\": { \"token\": \"string\" } })'),\n requiresAuth: z.boolean().optional().describe('Whether endpoint requires authentication'),\n })).describe('API endpoints to register'),\n },\n );\n\n // ── Failure Diagnostics ──────────────────────────────────────────────\n\n tool(server, client, 'get_test_failures',\n 'Get recent test failures with full error messages, Playwright code, step-level failures, and heal context. Use this to understand why tests are failing.',\n {\n limit: z.number().optional().describe('Max failures to return (default: 50, max: 100)'),\n suite: z.string().optional().describe('Filter by feature/suite name'),\n mode: z.enum(['run', 'heal', 'all']).optional().describe('run = regular failures, heal = heal attempt failures, all = both (default)'),\n sinceHours: z.number().optional().describe('Only failures from the last N hours (default: 24)'),\n },\n { readOnlyHint: true },\n );\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAMA,SAAS,YAAY,WAAW,gBAAAA,eAAc,qBAAqB;AACnE,SAAS,WAAAC,UAAS,YAAY;AAQ9B,SAAS,cAAc,MAA0B;AAC/C,QAAM,OAA+B,CAAC;AACtC,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAM,M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AAmB;AAAA,UACnB,aAAa;AAAA,UACb,cAAc;AAAA,UACd,mBAAmB;AAAA,UACnB,YAAY;AAAA,UACZ,eAAe;AAAA,UACf,qBAAqB;AAAA,QACvB;AAAA,QACA,WAAW;AAAA,UACT,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UACX,UAAU;AAAA,UACV,WAAW;AAAA,UACX,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UACpB,kBAAkB;AAAA,QACpB;AAAA,QACA,aAAa;AAAA,UACX;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,QACA,eAAe;AAAA,UACb,UAAU;AAAA,UACV,cAAc;AAAA,UACd,WAAW;AAAA,QACb;AAAA,QACA,aAAa;AAAA,UACX,UAAU;AAAA,UACV,OAAO;AAAA,UACP,QAAQ;AAAA,UACR,QAAQ;AAAA,UACR,UAAU;AAAA,QACZ;AAAA,QACA,cAAa,oBAAI,KAAK,GAAE,YAAY;AAAA,MACtC;AACA,aAAO,EAAE,UAAU,CAAC,EAAE,KAAK,8BAA8B,UAAU,oBAAoB,MAAM,KAAK,UAAU,aAAa,MAAM,CAAC,EAAE,CAAC,EAAE;AAAA,IACvI,SAAS,KAAK;AACZ,aAAO,EAAE,UAAU,CAAC,EAAE,KAAK,8BAA8B,UAAU,cAAc,MAAM,+BAA+B,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,GAAG,CAAC,EAAE;AAAA,IAC9K;AAAA,EACF;AACF;AAGA,IAAM,YAAY,IAAI,qBAAqB;AAC3C,MAAM,OAAO,QAAQ,SAAS;","names":["readFileSync","resolve","config","tool","server","client","runInit"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@validate.qa/mcp",
3
- "version": "1.0.0",
4
- "description": "MCP server for Validate.QA — manage your QA platform from AI IDEs (Claude Code, Cursor, etc.)",
3
+ "version": "1.1.0",
4
+ "description": "MCP server for Validate.QA - manage your QA platform from AI IDEs (Claude Code, Cursor, etc.)",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "validate-mcp": "bin.cjs"
@@ -9,7 +9,9 @@
9
9
  "main": "dist/index.js",
10
10
  "scripts": {
11
11
  "build": "tsup",
12
- "dev": "tsx src/index.ts"
12
+ "dev": "tsx src/index.ts",
13
+ "test": "node --import tsx --test test/*.test.ts",
14
+ "prepublishOnly": "npm run build"
13
15
  },
14
16
  "files": [
15
17
  "dist",