qatools-cli 1.2.34 → 1.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/mcp-core.js +1115 -0
  2. package/package.json +2 -1
  3. package/qatools.js +81 -1047
package/qatools.js CHANGED
@@ -784,9 +784,10 @@ async function authenticate(options, { asMember = false } = {}) {
784
784
  }
785
785
  }
786
786
 
787
- // Backlog labels as the web app shows them (project.ts typePrefix): bug → AVV-12 etc.
788
- const BACKLOG_PREFIX = { bug: "AVV", improvement: "IMP", requirement_gap: "GAP", technical_defect: "DEF" };
789
- const backlogLabel = (type, n) => `${BACKLOG_PREFIX[type] || "AVV"}-${n}`;
787
+ // Labels and status guards are shared with the MCP tools (cli.mcp-access-parity): they live in mcp-core.js
788
+ const { backlogLabel, requirementEvidenceViolations, backlogResolveViolations: backlogResolveViolationsVia } = require("./mcp-core");
789
+ const cliCall = async (name, data) => (await httpsCallable(functions, name)(data)).data;
790
+ const backlogResolveViolations = (projectId, updates, opts) => backlogResolveViolationsVia(cliCall, projectId, updates, opts);
790
791
 
791
792
  // Images as evidence (testing.evidence-attachments): upload local image files through the backend and
792
793
  // return their storage paths, to pass as `attachments` with the evidence. Shared by CLI and MCP.
@@ -806,43 +807,6 @@ async function uploadEvidenceFiles(projectId, files) {
806
807
  return paths;
807
808
  }
808
809
 
809
- // Status guards shared by the CLI commands and the MCP server (cli.mcp-access-parity) —
810
- // one implementation, so an MCP tool can never be looser than its CLI counterpart.
811
- const REQUIREMENT_STATUSES_REQUIRING_EVIDENCE = new Set(["implemented", "tested"]);
812
-
813
- // updates: { requirementId: { status, ... } }, evidenceById: { requirementId: text }
814
- function requirementEvidenceViolations(updates, evidenceById) {
815
- const violations = [];
816
- for (const [id, u] of Object.entries(updates)) {
817
- if (u.status && REQUIREMENT_STATUSES_REQUIRING_EVIDENCE.has(u.status)) {
818
- const ev = (evidenceById[id] || "").trim();
819
- if (ev.length < 10) violations.push({ id, status: u.status });
820
- }
821
- }
822
- return violations;
823
- }
824
-
825
- // Backlog: status=resolved needs evidence (min 10 chars) and, for AVV/DEF/IMP, a prior ready_for_test.
826
- // GAP (requirement_gap) is exempt from both. Throws if the backlog can't be listed.
827
- async function backlogResolveViolations(projectId, updates, { skipTestVerification = false } = {}) {
828
- const out = { evidence: [], flow: [] };
829
- const resolving = Object.entries(updates).filter(([, u]) => u.status === "resolved");
830
- if (resolving.length === 0) return out;
831
- const listBacklog = httpsCallable(functions, "listBacklog");
832
- const listResult = await listBacklog({ projectId });
833
- const itemById = {};
834
- for (const it of listResult.data.items || []) itemById[it.id] = it;
835
- for (const [id, u] of resolving) {
836
- const item = itemById[id];
837
- if (!item) continue;
838
- if (item.type === "requirement_gap") continue;
839
- const v = { id, type: item.type, currentStatus: item.status, description: (item.description || "").substring(0, 80) };
840
- if ((u.evidence || "").trim().length < 10) out.evidence.push(v);
841
- if (!skipTestVerification && item.status !== "ready_for_test") out.flow.push(v);
842
- }
843
- return out;
844
- }
845
-
846
810
  program
847
811
  .name("qatools")
848
812
  .description("CLI for QA Tools")
@@ -962,7 +926,8 @@ program
962
926
 
963
927
  program
964
928
  .command("setup")
965
- .description("Select default project (login first with 'qatools login')")
929
+ .description("Select default project (login first with 'qatools login'). With --project the project is chosen without a prompt, so Claude can run it")
930
+ .option("--project <id>", "Project ID to select without a prompt")
966
931
  .option("-e, --email <email>", "Login email")
967
932
  .option("-p, --password <password>", "Login password")
968
933
  .action(async (options) => {
@@ -978,22 +943,32 @@ program
978
943
  process.exit(1);
979
944
  }
980
945
 
981
- console.log("Your projects:");
982
- projects.forEach((p, i) => console.log(` ${i + 1}. ${p.name} ${p.claudeEnabled ? '🤖' : ''} (${p.id})`));
983
-
984
- // Use readline for selection
985
- const readline = require("readline");
986
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
987
- const answer = await new Promise(resolve => rl.question(`\nSelect project (1-${projects.length}): `, resolve));
988
- rl.close();
989
-
990
- const idx = parseInt(answer, 10) - 1;
991
- if (idx < 0 || idx >= projects.length) {
992
- console.error("Invalid selection.");
993
- process.exit(1);
946
+ let selected;
947
+ if (options.project) {
948
+ // projects.existing-repo-start: no prompt, so a Claude session can select the project itself
949
+ selected = projects.find(p => p.id === options.project);
950
+ if (!selected) {
951
+ console.error(`Project ${options.project} is not one of yours. Your projects:`);
952
+ projects.forEach(p => console.error(` ${p.name} (${p.id})`));
953
+ process.exit(1);
954
+ }
955
+ } else {
956
+ console.log("Your projects:");
957
+ projects.forEach((p, i) => console.log(` ${i + 1}. ${p.name} ${p.claudeEnabled ? '🤖' : ''} (${p.id})`));
958
+
959
+ // Use readline for selection
960
+ const readline = require("readline");
961
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
962
+ const answer = await new Promise(resolve => rl.question(`\nSelect project (1-${projects.length}): `, resolve));
963
+ rl.close();
964
+
965
+ const idx = parseInt(answer, 10) - 1;
966
+ if (idx < 0 || idx >= projects.length) {
967
+ console.error("Invalid selection.");
968
+ process.exit(1);
969
+ }
970
+ selected = projects[idx];
994
971
  }
995
-
996
- const selected = projects[idx];
997
972
  const configPath = path.join(process.env.HOME || process.env.USERPROFILE, ".qatools");
998
973
  // Preserve existing credentials
999
974
  let existing = {};
@@ -1462,6 +1437,17 @@ program
1462
1437
  process.exit(0);
1463
1438
  });
1464
1439
 
1440
+ // loop.claude-builds-approved: the unattended loop run, for: claude -p "$(qatools loop-run-prompt)" in the app's repo
1441
+ program
1442
+ .command("loop-run-prompt")
1443
+ .description("Print the unattended self-playing-loop instructions (answer wishes, draft requirements, build one approved wish on a branch, test environment only), for: claude -p \"$(qatools loop-run-prompt)\" in the app's repo")
1444
+ .option("--project <id>", "Project ID to name in the instructions (default: the configured project)")
1445
+ .action((options) => {
1446
+ // No login needed — it only prints text. Same text as the MCP prompt loop_run.
1447
+ console.log(loopRunPrompt(options.project));
1448
+ process.exit(0);
1449
+ });
1450
+
1465
1451
  // security.repo-doctor: secrets in files and history, and the qa-tools hooks. No network; exit 1 when a secret is found.
1466
1452
  program
1467
1453
  .command("doctor")
@@ -1890,7 +1876,7 @@ program
1890
1876
  for (const k of ["id", "projectId", "name", "aiRules", "sections", "skills", "createdAt", "updatedAt"]) delete context[k];
1891
1877
  try {
1892
1878
  const { data } = await httpsCallable(functions, "proposeAppContext")({ projectId, context, summary: options.summary || "" });
1893
- console.log(`Proposed App Context (${data.fields.join(", ")})${data.superseded ? ` — replaces ${data.superseded} earlier pending proposal(s)` : ""}.`);
1879
+ console.log(`Proposed App Context (${data.fields.join(", ")})${data.otherPending ? ` — ${data.otherPending} other proposal(s) are pending too; the member chooses` : ""}.`);
1894
1880
  console.log("A project member approves or rejects it in qa-tools: Requirements → App Context.");
1895
1881
  } catch (e) {
1896
1882
  console.error("Failed:", e.message);
@@ -4116,978 +4102,18 @@ program
4116
4102
  });
4117
4103
 
4118
4104
  // ─── MCP server (cli.mcp-server) ────────────────────────────────────────────
4119
- // Local Model Context Protocol server over stdio: newline-delimited JSON-RPC 2.0 on stdin/stdout.
4120
- // Every tool calls the same Cloud Functions callable as its CLI counterpart — no direct Firestore
4121
- // access — and write tools reuse the shared status guards above (cli.mcp-access-parity).
4122
- // Deletes are deliberately not exposed: they stay behind the CLI/UI confirmation paths.
4123
-
4124
- const MCP_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
4125
-
4126
- const MCP_INSTRUCTIONS = `qa-tools: requirements-driven QA. Rules that apply to every tool:
4127
- - Build from requirements. Planning is Epics → Requirements → Sprints (requirement.sprintId).
4128
- - The backlog is signals (bug=AVV, requirement_gap=GAP, technical_defect=DEF, improvement=IMP), not a task list.
4129
- - Backlog flow: open → in_progress → ready_for_test → resolved. Set ready_for_test when you believe a fix is done; resolved needs evidence (min 10 chars) and, except GAP, a prior ready_for_test. on_hold = deliberately waiting for something outside the team (a decision, information); it needs a comment saying what it waits for, and goes back to open or in_progress when the wait is over.
4130
- - Requirement status implemented/tested needs evidence: test output, file:line, expected vs actual, or "no test applies because <reason>".
4131
- - Requirement flow: approved → in_progress → implemented → tested. When you start implementing an approved requirement, set status in_progress and assignedTo "me" (update_requirement); if you stop without finishing, set it back to approved.
4132
- - Requirements with a libraryId inherit from the account's requirement library: never try to change their title, description, criteria, type or category — only applicability, status, sprint, epic and assignee are the project's. When get_agenda lists libraryReverify, verify those requirements again against the new library text.
4133
- - New requirements must not break old ones: before completing a sprint or release, and after building something that touched shared code, run requirement_impact (sprint or since) with flag: true, and verify the listed requirements again. Put their manual tests in a "Regression" section of the sprint's test protocol.
4134
- - Sprint planning: plan approved, functional requirements only (update_requirement sprintId), never backlog items; non-functional requirements are continuous and never go into sprints. Gather facts first (list_sprints, sprint_velocity, list_epics, list_requirements), respect epic dependsOn, present the plan as a table (sprint | requirement | reason) and change NOTHING until the user approves it in this conversation. If the user isn't here or wants to decide later, save it with propose_sprint_plan instead — they approve in qa-tools. Full procedure: prompt plan_sprints.
4135
- - Every tool takes an optional projectId; without it the configured project (qatools setup) is used.`;
4136
-
4137
- const mcpStr = (description, extra = {}) => ({ type: "string", description, ...extra });
4138
- const mcpInt = (description, extra = {}) => ({ type: "integer", description, ...extra });
4139
- const mcpBool = (description) => ({ type: "boolean", description });
4140
- const mcpStrArray = (description, items = { type: "string" }) => ({ type: "array", items, description });
4141
- const MCP_PROJECT_PROP = { projectId: mcpStr("Project ID. Defaults to the configured project.") };
4142
- const MCP_REQ_STATUSES = ["draft", "approved", "in_progress", "rejected", "implemented", "tested", "superseded"];
4143
- const MCP_BACKLOG_STATUSES = ["open", "in_progress", "on_hold", "ready_for_test", "resolved", "rejected"];
4144
- const MCP_BACKLOG_TYPES = ["bug", "improvement", "requirement_gap", "technical_defect"];
4145
- const MCP_PRIORITY = mcpInt("Priority: 1 (high), 2 (medium), 3 (low)", { enum: [1, 2, 3] });
4146
-
4147
- function mcpSchema(props = {}, required = []) {
4148
- return { type: "object", properties: { ...MCP_PROJECT_PROP, ...props }, required, additionalProperties: false };
4149
- }
4150
-
4151
- async function mcpCall(name, data) {
4152
- const result = await httpsCallable(functions, name)(data);
4153
- return result.data;
4154
- }
4155
-
4156
- // Thrown by tool handlers for a refusal that should reach the client as a tool error, not a crash.
4157
- class McpToolError extends Error {}
4158
-
4159
- // Copies only the listed keys that the caller actually supplied.
4160
- function mcpPick(args, keys) {
4161
- const out = {};
4162
- for (const k of keys) if (args[k] !== undefined) out[k] = args[k];
4163
- return out;
4164
- }
4165
-
4166
- const mcpTools = [
4167
- {
4168
- name: "list_projects",
4169
- description: "List the qa-tools projects this login can access.",
4170
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
4171
- noProject: true,
4172
- run: async () => (await mcpCall("listProjects", {})).projects,
4173
- },
4174
- {
4175
- name: "get_agenda",
4176
- description: "What to work on next in the project (same data as `qatools next`): open signals, requirements awaiting work, sessions awaiting analysis.",
4177
- inputSchema: mcpSchema(),
4178
- run: async (a) => {
4179
- const agenda = await mcpCall("getProjectAgenda", { projectId: a.projectId });
4180
- return mcpWarnings.length ? { warnings: mcpWarnings, ...agenda } : agenda;
4181
- },
4182
- },
4183
- {
4184
- name: "get_app_context",
4185
- description: "The project's App Context: purpose, tech stack, conventions, AI rules, design principles.",
4186
- inputSchema: mcpSchema(),
4187
- run: async (a) => mcpCall("getAppContext", { projectId: a.projectId }),
4188
- },
4189
- {
4190
- name: "list_requirements",
4191
- description: "List requirements. Superseded requirements are hidden unless includeSuperseded is true.",
4192
- inputSchema: mcpSchema({
4193
- status: mcpStrArray("Only these statuses", { type: "string", enum: MCP_REQ_STATUSES }),
4194
- epicKey: mcpStr("Only requirements linked to this epic key"),
4195
- sprintId: mcpStr("Only requirements planned in this sprint"),
4196
- includeSuperseded: mcpBool("Include superseded requirements"),
4197
- }),
4198
- run: async (a) => {
4199
- let reqs = (await mcpCall("listRequirements", { projectId: a.projectId, status: null })).requirements;
4200
- if (!a.includeSuperseded) reqs = reqs.filter(r => r.status !== "superseded");
4201
- if (a.status?.length) { const s = new Set(a.status); reqs = reqs.filter(r => s.has(r.status)); }
4202
- if (a.epicKey) reqs = reqs.filter(r => r.epicKey === a.epicKey);
4203
- if (a.sprintId) reqs = reqs.filter(r => r.sprintId === a.sprintId);
4204
- return reqs;
4205
- },
4206
- },
4207
- {
4208
- name: "create_requirement",
4209
- description: "Create a requirement. Acceptance criteria must be Given/When/Then (Givet/När/Då for Swedish), never mixing languages. Returns error 'similar_exists' with matches if a semantically similar requirement exists — align with it, or pass force only if it really is separate.",
4210
- inputSchema: mcpSchema({
4211
- key: mcpStr("Semantic key, e.g. auth.login"),
4212
- title: mcpStr("Title"),
4213
- description: mcpStr("Description"),
4214
- acceptanceCriteria: mcpStr("Given/When/Then scenario(s), newline-separated"),
4215
- negativeCriteria: mcpStr("Negative Given/When/Then scenario(s)"),
4216
- type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }),
4217
- priority: MCP_PRIORITY,
4218
- category: mcpStr("Category"),
4219
- epicKey: mcpStr("Epic key"),
4220
- sprintId: mcpStr("Sprint ID to plan it in"),
4221
- status: mcpStr("Initial status (default draft)", { enum: MCP_REQ_STATUSES }),
4222
- force: mcpBool("Skip the semantic similarity check"),
4223
- points: { type: "integer", enum: [1, 2, 3, 5, 8], description: "Size in points. Split anything bigger than 8. Not for non-functional requirements." },
4224
- version: mcpInt("New version of an existing key (e.g. 2). Then set the old version to superseded with update_requirement."),
4225
- }, ["key", "title"]),
4226
- run: async (a) => mcpCall("createRequirement", { projectId: a.projectId, ...mcpPick(a, ["key", "title", "description", "acceptanceCriteria", "negativeCriteria", "type", "priority", "category", "epicKey", "sprintId", "status", "force", "version", "points"]) }),
4227
- },
4228
- {
4229
- name: "update_requirement",
4230
- description: "Update a requirement (status, assignee, epic, sprint, text). status implemented/tested REQUIRES evidence. When you start implementing an approved requirement, set status in_progress and assignedTo \"me\". Set sprintId to plan the requirement in a sprint, or empty string to unplan it.",
4231
- inputSchema: mcpSchema({
4232
- requirementId: mcpStr("Requirement document ID"),
4233
- status: mcpStr("New status", { enum: MCP_REQ_STATUSES }),
4234
- assignedTo: mcpStr("Assignee: a member's email, \"me\" (the Claude account), or empty string to clear. Setting status back to approved clears it."),
4235
- evidence: mcpStr("Required for implemented/tested (min 10 chars): test output, file:line, expected vs actual, or 'no test applies because <reason>'"),
4236
- epicKey: mcpStr("Epic key"),
4237
- sprintId: mcpStr("Sprint ID (empty string clears)"),
4238
- type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }),
4239
- title: mcpStr("Title"),
4240
- description: mcpStr("Description"),
4241
- acceptanceCriteria: mcpStr("Acceptance criteria"),
4242
- points: { type: ["integer", "null"], enum: [1, 2, 3, 5, 8, null], description: "Size in points (null clears). Split anything bigger than 8. Not for non-functional requirements." },
4243
- reason: mcpStr("Required for status rejected (min 5 chars): why it is rejected; kept with the requirement"),
4244
- attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
4245
- commit: mcpStr("Commit the evidence was verified on. Default: git HEAD of the server's working directory; empty string to leave it out"),
4246
- }, ["requirementId"]),
4247
- run: async (a) => {
4248
- const updates = mcpPick(a, ["status", "assignedTo", "epicKey", "sprintId", "type", "title", "description", "acceptanceCriteria", "points"]);
4249
- if (Object.keys(updates).length === 0) throw new McpToolError("No fields to update.");
4250
- const evidenceById = a.evidence ? { [a.requirementId]: a.evidence } : {};
4251
- if (requirementEvidenceViolations({ [a.requirementId]: updates }, evidenceById).length > 0) {
4252
- throw new McpToolError(`Refusing status=${updates.status} without evidence (min 10 chars). Cite the verification, or use a status that does not claim done.`);
4253
- }
4254
- if (updates.status === "rejected" && String(a.reason || a.evidence || "").trim().length < 5) {
4255
- throw new McpToolError("Refusing status=rejected without a reason (min 5 chars). Say why — it is kept with the requirement.");
4256
- }
4257
- const payload = { projectId: a.projectId, requirementId: a.requirementId, updates, ...(a.reason ? { reason: a.reason } : {}) };
4258
- if (a.evidence) {
4259
- payload.evidence = a.evidence;
4260
- const commit = a.commit !== undefined ? a.commit : currentGitCommit();
4261
- if (commit) payload.commit = commit;
4262
- }
4263
- if (a.attachments?.length) {
4264
- if (!a.evidence) throw new McpToolError("attachments need evidence — images belong to an evidence entry");
4265
- payload.attachments = await uploadEvidenceFiles(a.projectId, a.attachments);
4266
- }
4267
- await mcpCall("updateRequirement", payload);
4268
- return { updated: a.requirementId, fields: Object.keys(updates) };
4269
- },
4270
- },
4271
- {
4272
- name: "list_epics",
4273
- description: "List epics.",
4274
- inputSchema: mcpSchema(),
4275
- run: async (a) => (await mcpCall("listEpics", { projectId: a.projectId })).epics,
4276
- },
4277
- {
4278
- name: "create_epic",
4279
- description: "Create an epic. Check dependsOn against existing epics first (list_epics).",
4280
- inputSchema: mcpSchema({
4281
- key: mcpStr("Epic key, e.g. billing"),
4282
- title: mcpStr("Title"),
4283
- description: mcpStr("Description"),
4284
- value: mcpStr("Why this capability exists"),
4285
- scope: mcpStrArray("Scope items"),
4286
- dependsOn: mcpStrArray("Epic keys this depends on"),
4287
- priority: MCP_PRIORITY,
4288
- }, ["key", "title"]),
4289
- run: async (a) => mcpCall("createEpic", {
4290
- projectId: a.projectId, key: a.key, title: a.title, description: a.description || "", value: a.value || "",
4291
- scope: a.scope || [], dependsOn: a.dependsOn || [], priority: a.priority || 2,
4292
- }),
4293
- },
4294
- {
4295
- name: "update_epic",
4296
- description: "Update an epic.",
4297
- inputSchema: mcpSchema({
4298
- epicId: mcpStr("Epic document ID"),
4299
- status: mcpStr("Status", { enum: ["draft", "active", "completed"] }),
4300
- title: mcpStr("Title"),
4301
- description: mcpStr("Description"),
4302
- value: mcpStr("Value statement"),
4303
- scope: mcpStrArray("Scope items (replaces existing)"),
4304
- priority: MCP_PRIORITY,
4305
- }, ["epicId"]),
4306
- run: async (a) => {
4307
- const updates = mcpPick(a, ["status", "title", "description", "value", "scope", "priority"]);
4308
- if (Object.keys(updates).length === 0) throw new McpToolError("No fields to update.");
4309
- await mcpCall("updateEpic", { projectId: a.projectId, epicId: a.epicId, updates });
4310
- return { updated: a.epicId, fields: Object.keys(updates) };
4311
- },
4312
- },
4313
- {
4314
- name: "list_sprints",
4315
- description: "List sprints, ordered by release (end) date.",
4316
- inputSchema: mcpSchema(),
4317
- run: async (a) => (await mcpCall("listSprints", { projectId: a.projectId })).sprints,
4318
- },
4319
- {
4320
- name: "sprint_velocity",
4321
- description: "Planning capacity: per completed sprint, how many requirements were planned and done, plus what is already planned in each open sprint. Completed sprints use the numbers stored when they were completed (fromSnapshot true); older ones are counted from today's statuses (fromSnapshot false). averageCompletionRate = average share of planned requirements that got done. capacity (sprint.requirement-points) = average done points of the last three completed sprints with points, or — without such history — done requirements; plan each sprint up to it, counting what it already holds (openSprints[].points).",
4322
- inputSchema: mcpSchema(),
4323
- run: async (a) => {
4324
- const [{ sprints }, { requirements }] = await Promise.all([
4325
- mcpCall("listSprints", { projectId: a.projectId }),
4326
- mcpCall("listRequirements", { projectId: a.projectId, status: null }),
4327
- ]);
4328
- const DONE = new Set(["implemented", "tested"]);
4329
- const active = requirements.filter(r => r.status !== "superseded" && r.status !== "rejected");
4330
- const row = (s) => {
4331
- const base = { id: s.id, name: s.name, status: s.status, startDate: s.startDate || "", releaseDate: s.releaseDate || "" };
4332
- // sprint.completion-snapshot: completing moves the unfinished out, so only the stored numbers show what was planned.
4333
- if (s.status === "completed" && s.completionStats) {
4334
- const cs = s.completionStats;
4335
- return { ...base, planned: cs.planned, done: cs.done, moved: cs.moved, fromSnapshot: true, completedAt: cs.completedAt || "",
4336
- ...(typeof cs.donePoints === "number" ? { plannedPoints: cs.plannedPoints, donePoints: cs.donePoints } : {}) };
4337
- }
4338
- const reqs = active.filter(r => r.sprintId === s.id);
4339
- return { ...base, planned: reqs.length, done: reqs.filter(r => DONE.has(r.status)).length,
4340
- points: reqs.reduce((n, r) => n + (r.points || 0), 0), withoutPoints: reqs.filter(r => !r.points).length,
4341
- ...(s.status === "completed" ? { fromSnapshot: false } : {}) };
4342
- };
4343
- const completed = sprints.filter(s => s.status === "completed").map(row);
4344
- const withWork = completed.filter(s => s.planned > 0);
4345
- const avg = withWork.length ? withWork.reduce((n, s) => n + s.done, 0) / withWork.length : null;
4346
- const rate = withWork.length ? withWork.reduce((n, s) => n + s.done / s.planned, 0) / withWork.length : null;
4347
- // Same rule as the web app (sprint-capacity.ts): last three completed sprints with points, else done requirements
4348
- const recent = [...completed].filter(s => s.fromSnapshot).sort((x, y) => (y.completedAt || "").localeCompare(x.completedAt || ""));
4349
- const pointed = recent.filter(s => typeof s.donePoints === "number").slice(0, 3);
4350
- const basis = pointed.length ? pointed : recent.slice(0, 3);
4351
- const capacity = basis.length
4352
- ? { unit: pointed.length ? "points" : "requirements", value: Math.round(basis.reduce((n, s) => n + (pointed.length ? s.donePoints : s.done), 0) / basis.length), basedOn: basis.length,
4353
- ...(pointed.length ? {} : { note: "No completed sprint has points yet — capacity is counted in requirements" }) }
4354
- : null;
4355
- return {
4356
- capacity,
4357
- completedSprints: completed,
4358
- averageDonePerCompletedSprint: avg === null ? null : Math.round(avg * 10) / 10,
4359
- averageCompletionRate: rate === null ? null : Math.round(rate * 100) / 100,
4360
- openSprints: sprints.filter(s => s.status !== "completed").map(row),
4361
- unplannedApprovedRequirements: active.filter(r => r.status === "approved" && !r.sprintId).length,
4362
- unplannedApprovedWithoutPoints: active.filter(r => r.status === "approved" && !r.sprintId && r.type !== "non-functional" && !r.points).length,
4363
- };
4364
- },
4365
- },
4366
- {
4367
- name: "propose_sprint_plan",
4368
- description: "Save a sprint plan as a PENDING proposal instead of applying it. A project member reviews it in qa-tools (Sprints → Plan proposals), selects rows and approves — Claude can never approve. Use when the user isn't in this conversation, or asks to decide later. Only functional requirements: approved ones without a sprint, or — as a move — approved or in-progress ones in an overdue sprint (they keep status and assignee). Each row targets an existing sprintId OR a newSprintRef from newSprints. The whole proposal is refused if any row can't be planned.",
4369
- inputSchema: mcpSchema({
4370
- goal: mcpStr("What the plan optimises for, e.g. 'Release 4.0 by Nov 18'"),
4371
- summary: mcpStr("Short rationale: capacity used, dependency order, risks"),
4372
- items: {
4373
- type: "array",
4374
- description: "One row per requirement",
4375
- items: {
4376
- type: "object",
4377
- properties: {
4378
- requirementId: mcpStr("Requirement document ID"),
4379
- sprintId: mcpStr("Existing sprint ID (or use newSprintRef)"),
4380
- newSprintRef: mcpStr("ref of a sprint in newSprints"),
4381
- reason: mcpStr("Why this requirement goes in this sprint"),
4382
- selfVerification: mcpStr("How you will verify it yourself, e.g. 'unit tests for X + API call Y' (sprint.ai-planning-self-verification)"),
4383
- manualOnly: { type: "boolean", description: "true when you cannot verify it yourself at all — then testProtocols must have a test for it" },
4384
- points: { type: "integer", enum: [1, 2, 3, 5, 8], description: "Proposed size for a requirement that has no points yet (ignored when it has); approving the row sets it" },
4385
- },
4386
- required: ["requirementId", "reason"],
4387
- additionalProperties: false,
4388
- },
4389
- },
4390
- newSprints: {
4391
- type: "array",
4392
- description: "Sprints to create if the proposal is approved",
4393
- items: {
4394
- type: "object",
4395
- properties: {
4396
- ref: mcpStr("Your local reference, e.g. new-1"),
4397
- name: mcpStr("Sprint name"),
4398
- releaseDate: mcpStr("End date YYYY-MM-DD"),
4399
- startDate: mcpStr("Start date YYYY-MM-DD"),
4400
- },
4401
- required: ["ref", "name", "releaseDate"],
4402
- additionalProperties: false,
4403
- },
4404
- },
4405
- omitted: {
4406
- type: "array",
4407
- description: "Requirements deliberately left out, with why",
4408
- items: { type: "object", properties: { key: mcpStr("Requirement key"), reason: mcpStr("Why") }, required: ["key", "reason"], additionalProperties: false },
4409
- },
4410
- testProtocols: {
4411
- type: "array",
4412
- description: "One manual test protocol per target sprint: only tests a person must perform (you can't verify them yourself). Each test's requirementKey must be planned in that sprint by this proposal. Approved together with the proposal.",
4413
- items: {
4414
- type: "object",
4415
- properties: {
4416
- name: mcpStr("Protocol name, e.g. 'Release 4.1 — manual tests'"),
4417
- sprintId: mcpStr("Existing sprint ID (or use newSprintRef)"),
4418
- newSprintRef: mcpStr("ref of a sprint in newSprints"),
4419
- sections: {
4420
- type: "array",
4421
- description: "Sections of manual tests",
4422
- items: {
4423
- type: "object",
4424
- properties: {
4425
- title: mcpStr("Section title"),
4426
- tests: {
4427
- type: "array",
4428
- items: {
4429
- type: "object",
4430
- properties: {
4431
- id: mcpStr("Test id, e.g. M-1"),
4432
- name: mcpStr("What is tested"),
4433
- steps: mcpStr("Steps a person follows"),
4434
- expected: mcpStr("Expected result"),
4435
- purpose: mcpStr("Why a person must perform this, e.g. 'real phone camera', 'SMS must actually arrive', 'visual check'"),
4436
- requirementKey: mcpStr("Key of the requirement it verifies"),
4437
- },
4438
- required: ["name", "steps", "expected", "purpose", "requirementKey"],
4439
- additionalProperties: false,
4440
- },
4441
- },
4442
- },
4443
- required: ["title", "tests"],
4444
- additionalProperties: false,
4445
- },
4446
- },
4447
- },
4448
- required: ["name", "sections"],
4449
- additionalProperties: false,
4450
- },
4451
- },
4452
- swaps: {
4453
- type: "array",
4454
- description: "sprint.mid-release-swap: take a requirement into a sprint that is in progress and move not-started (approved) requirements out to the next open sprint so it fits its capacity. Never move out one that is in progress or done, or one a staying requirement depends on through its epic. outRequirementIds may be empty to keep the sprint over capacity — say why. A requirement may appear in items or in one swap, not both.",
4455
- items: {
4456
- type: "object",
4457
- properties: {
4458
- sprintId: mcpStr("Sprint in progress to take the requirement into"),
4459
- inRequirementId: mcpStr("Requirement taken in (approved or in progress)"),
4460
- outRequirementIds: mcpStrArray("Requirements moved out (approved, in that sprint)"),
4461
- reason: mcpStr("Why the change is worth it"),
4462
- },
4463
- required: ["sprintId", "inRequirementId", "outRequirementIds", "reason"],
4464
- additionalProperties: false,
4465
- },
4466
- },
4467
- }, []),
4468
- run: async (a) => {
4469
- if (!a.items?.length && !a.swaps?.length) throw new McpToolError("Give items, swaps or both.");
4470
- const r = await mcpCall("createPlanProposal", { projectId: a.projectId, ...mcpPick(a, ["goal", "summary", "items", "newSprints", "omitted", "testProtocols", "swaps"]) });
4471
- return { ...r, next: "Pending. A project member approves or rejects it in qa-tools under Sprints → Plan proposals." };
4472
- },
4473
- },
4474
- {
4475
- name: "list_plan_proposals",
4476
- description: "List sprint-plan proposals and their status (pending/approved/rejected), with who decided and what was applied.",
4477
- inputSchema: mcpSchema({ status: mcpStr("Filter by status", { enum: ["pending", "approved", "rejected"] }) }),
4478
- run: async (a) => (await mcpCall("listPlanProposals", { projectId: a.projectId, status: a.status || null })).proposals,
4479
- },
4480
- {
4481
- name: "list_compliance_due",
4482
- description: "The sprint's continuous requirements (non-functional, active epic) with their verification status for the sprint, including acceptance criteria / verification method. Check each against the sprint's diff (git log --since <startDate> in the repo), then record_compliance_verification.",
4483
- inputSchema: mcpSchema({ sprintId: mcpStr("Sprint ID (default: the active sprint)") }),
4484
- run: async (a) => mcpCall("listComplianceDue", { projectId: a.projectId, sprintId: a.sprintId || null }),
4485
- },
4486
- {
4487
- name: "record_compliance_verification",
4488
- description: "Record the result of checking a continuous requirement against the sprint's diff. Evidence is required (what was checked, file:line). failed creates an AVV signal (deduplicated). Not available to propose-only keys.",
4489
- inputSchema: mcpSchema({
4490
- requirementKey: mcpStr("Continuous requirement key"),
4491
- result: mcpStr("passed or failed", { enum: ["passed", "failed"] }),
4492
- evidence: mcpStr("What was checked in the sprint's diff and what was found (file:line), min 10 chars"),
4493
- sprintId: mcpStr("Sprint ID (default: the active sprint)"),
4494
- commit: mcpStr("Commit checked"),
4495
- attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
4496
- }, ["requirementKey", "result", "evidence"]),
4497
- run: async (a) => mcpCall("recordSprintVerification", { projectId: a.projectId, ...mcpPick(a, ["requirementKey", "result", "evidence", "sprintId", "commit"]), attachments: await uploadEvidenceFiles(a.projectId, a.attachments) }),
4498
- },
4499
- {
4500
- name: "notify_owner",
4501
- description: "Email the project owner (respects their opt-out). Used for the summary at the end of a scheduled agenda run. Plain text.",
4502
- inputSchema: mcpSchema({
4503
- subject: mcpStr("Email subject"),
4504
- message: mcpStr("Plain-text body"),
4505
- }, ["subject", "message"]),
4506
- run: async (a) => mcpCall("notifyUser", { projectId: a.projectId, to: "owner", subject: a.subject, message: a.message }),
4507
- },
4508
- {
4509
- name: "propose_app_context",
4510
- description: "Propose the project's App Context (purpose, domainObjects, actors, stack, architecture, security, constraints, conventions, environments, integrations), e.g. read from an existing repo. Only what the code shows. It counts only when a member approves it in the web app; a newer proposal replaces a pending older one.",
4511
- inputSchema: mcpSchema({
4512
- context: { type: "object", description: "App Context fields, shape as qatools context-template (stack: [{layer, technology, version, notes}], conventions: [{area, rule}], environments: [{name, url, notes}], integrations: [{name, purpose}], domainObjects/actors/constraints: string arrays)" },
4513
- summary: mcpStr("What the proposal is based on (files read)"),
4514
- }, ["context"]),
4515
- run: async (a) => mcpCall("proposeAppContext", { projectId: a.projectId, context: a.context, summary: a.summary || "" }),
4516
- },
4517
- {
4518
- name: "reject_plan_proposal",
4519
- description: "Reject (withdraw) a pending sprint-plan proposal, e.g. one you created that is superseded. Nothing gets planned. There is no approve tool: approval is a human decision in the qa-tools web app.",
4520
- inputSchema: mcpSchema({
4521
- proposalId: mcpStr("Proposal ID (from list_plan_proposals)"),
4522
- comment: mcpStr("Why it is rejected (min 5 chars) — required, kept with the proposal"),
4523
- }, ["proposalId", "comment"]),
4524
- run: async (a) => {
4525
- await mcpCall("decidePlanProposal", { projectId: a.projectId, proposalId: a.proposalId, decision: "reject", comment: a.comment || "" });
4526
- return { rejected: a.proposalId, planned: 0 };
4527
- },
4528
- },
4529
- {
4530
- name: "get_sprint_items",
4531
- description: "Everything planned in a sprint: its requirements (the planning unit) and the backlog signals linked to it.",
4532
- inputSchema: mcpSchema({ sprintId: mcpStr("Sprint ID") }, ["sprintId"]),
4533
- run: async (a) => mcpCall("getSprintItems", { projectId: a.projectId, sprintId: a.sprintId }),
4534
- },
4535
- {
4536
- name: "create_sprint",
4537
- description: "Create a sprint. Status derives from dates (planning/active/overdue); without startDate it stays in planning.",
4538
- inputSchema: mcpSchema({
4539
- name: mcpStr("Sprint name"),
4540
- releaseDate: mcpStr("End/release date, YYYY-MM-DD", { pattern: "^\\d{4}-\\d{2}-\\d{2}$" }),
4541
- startDate: mcpStr("Start date, YYYY-MM-DD", { pattern: "^\\d{4}-\\d{2}-\\d{2}$" }),
4542
- }, ["name", "releaseDate"]),
4543
- run: async (a) => (await mcpCall("createSprint", { projectId: a.projectId, name: a.name, startDate: a.startDate || "", releaseDate: a.releaseDate })).sprint,
4544
- },
4545
- {
4546
- name: "list_backlog",
4547
- description: "List backlog signals (AVV/GAP/DEF/IMP).",
4548
- inputSchema: mcpSchema({
4549
- sprintId: mcpStr("Only items in this sprint"),
4550
- status: mcpStrArray("Only these statuses", { type: "string", enum: MCP_BACKLOG_STATUSES }),
4551
- assignedTo: mcpStr("Only items assigned to this email"),
4552
- }),
4553
- run: async (a) => mcpCall("listBacklog", { projectId: a.projectId, ...mcpPick(a, ["sprintId", "assignedTo"]), ...(a.status?.length ? { status: a.status } : {}) }),
4554
- },
4555
- {
4556
- name: "create_backlog_item",
4557
- description: "Report a backlog signal: bug (AVV), requirement_gap (GAP), technical_defect (DEF) or improvement (IMP). Not for planning work — plan with requirements.",
4558
- inputSchema: mcpSchema({
4559
- description: mcpStr("What was observed"),
4560
- type: mcpStr("Signal type: bug = AVV (deviation from a requirement, default), requirement_gap = GAP, technical_defect = DEF, improvement = IMP", { enum: MCP_BACKLOG_TYPES }),
4561
- priority: MCP_PRIORITY,
4562
- assignedTo: mcpStr("Assignee email"),
4563
- developer: mcpStr("Responsible developer email"),
4564
- sprintId: mcpStr("Sprint ID"),
4565
- parentId: mcpStr("Parent item label, e.g. AVV-5"),
4566
- requirementKey: mcpStr("Requirement key it relates to"),
4567
- tags: mcpStrArray("Tags"),
4568
- mailNotify: mcpBool("Enable email notifications on this item (default off)"),
4569
- }, ["description"]),
4570
- run: async (a) => {
4571
- const r = await mcpCall("createBacklogItem", {
4572
- projectId: a.projectId, type: a.type || "bug", description: a.description, priority: a.priority || 2,
4573
- assignedTo: a.assignedTo || "", developer: a.developer || "", sprintId: a.sprintId || "", parentId: a.parentId || "",
4574
- requirementKey: a.requirementKey || "", tags: (a.tags || []).map(t => t.trim().toLowerCase()), mailNotify: !!a.mailNotify,
4575
- });
4576
- return { ...r, label: backlogLabel(r.type, r.bugNumber) };
4577
- },
4578
- },
4579
- {
4580
- name: "update_backlog_item",
4581
- description: "Update a backlog item. When you believe a fix is done, set ready_for_test — not resolved. resolved REQUIRES evidence and (except GAP) that the item is already ready_for_test.",
4582
- inputSchema: mcpSchema({
4583
- itemId: mcpStr("Backlog item document ID"),
4584
- status: mcpStr("New status", { enum: MCP_BACKLOG_STATUSES }),
4585
- evidence: mcpStr("Required for resolved (min 10 chars): test output, file:line, expected vs actual, or 'no test applies because <reason>'"),
4586
- comment: mcpStr("Comment to add"),
4587
- authorName: mcpStr("Comment author name (default Claude)"),
4588
- assignedTo: mcpStr("Assignee email"),
4589
- developer: mcpStr("Developer email"),
4590
- sprintId: mcpStr("Sprint ID"),
4591
- priority: MCP_PRIORITY,
4592
- requirementKey: mcpStr("Requirement key"),
4593
- tags: mcpStrArray("Tags (replaces existing)"),
4594
- description: mcpStr("New description"),
4595
- mailNotify: mcpBool("Item email notifications on/off"),
4596
- skipTestVerification: mcpBool("Allow resolved without ready_for_test — only when no test applies. Evidence is still required."),
4597
- attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
4598
- }, ["itemId"]),
4599
- run: async (a) => {
4600
- const u = mcpPick(a, ["status", "evidence", "assignedTo", "developer", "sprintId", "priority", "requirementKey", "description", "mailNotify"]);
4601
- if (a.comment) { u.comment = a.comment; u.authorName = a.authorName || "Claude"; }
4602
- if (a.tags) u.tags = a.tags.map(t => t.trim().toLowerCase());
4603
- if (Object.keys(u).length === 0) throw new McpToolError("No fields to update.");
4604
- if (u.status === "on_hold" && String(u.comment || "").trim().length < 5) throw new McpToolError("Refusing status=on_hold without a comment saying what it waits for (min 5 chars).");
4605
- const updates = { [a.itemId]: u };
4606
- if (u.status === "resolved") {
4607
- // Fail closed: unlike the interactive CLI, the MCP server refuses when the pre-check can't run.
4608
- let v;
4609
- try {
4610
- v = await backlogResolveViolations(a.projectId, updates, { skipTestVerification: !!a.skipTestVerification });
4611
- } catch (e) {
4612
- throw new McpToolError(`Could not verify the backlog flow before resolving (${e.message}). Nothing was changed.`);
4613
- }
4614
- if (v.evidence.length) throw new McpToolError("Refusing status=resolved without evidence (min 10 chars). Cite the verification, or set ready_for_test instead.");
4615
- if (v.flow.length) throw new McpToolError(`Refusing status=resolved: item is '${v.flow[0].currentStatus}', not ready_for_test. Backlog flow: open → in_progress → ready_for_test → resolved. Set ready_for_test and let a tester verify, or pass skipTestVerification if no test applies.`);
4616
- }
4617
- if (a.attachments?.length) {
4618
- if (!a.evidence) throw new McpToolError("attachments need evidence — images belong to an evidence entry");
4619
- u.attachments = await uploadEvidenceFiles(a.projectId, a.attachments);
4620
- }
4621
- const r = await mcpCall("updateBacklogItems", { updates });
4622
- // The backend skips items it can't find or the caller can't access, instead of throwing.
4623
- if (!r.updatedCount) throw new McpToolError(`Item ${a.itemId} was not updated — it does not exist or this login has no access to its project.`);
4624
- return { updated: a.itemId, fields: Object.keys(u) };
4625
- },
4626
- },
4627
- {
4628
- name: "requirement_impact",
4629
- description: "Regression check (testing.regression-impact): which implemented/tested requirements had their files changed by other work in a range of commits. Runs in the server's working directory, which must be the project's git repository. Use before completing a sprint or a release, and after building a requirement that touched shared code. flag: true records the risk in qa-tools; then verify those requirements again (tests, a session, or new evidence).",
4630
- inputSchema: mcpSchema({ since: mcpStr("Range start: a git ref"), sprint: mcpStr("Range start: this sprint's start date (id or name)"), flag: { type: "boolean", description: "Record the risk in qa-tools" }, main: mcpStr("The main branch, if not origin/HEAD / main / master") }),
4631
- run: async (a) => runImpact({ projectId: a.projectId || getCredentials()?.projectId, since: a.since, sprint: a.sprint, flag: !!a.flag, main: a.main }),
4632
- },
4633
- {
4634
- name: "list_feature_requests",
4635
- description: "Requests from the app's users (signals.user-feature-requests), most votes first: title, votes, status as the app sees it (new / accepted / planned / released / declined), requirementKey, sprint and releaseDate. Link or unlink with link_feature_request / unlink_feature_request; declining is a member's decision (web app or CLI with a member login).",
4636
- inputSchema: mcpSchema(),
4637
- run: async (a) => (await mcpCall("listFeatureRequests", { projectId: a.projectId })).requests,
4638
- },
4639
- {
4640
- name: "link_feature_request",
4641
- description: "Link a request from the app's users to a requirement (signals.feature-requests-cli). The app then shows it as accepted, or planned with the release and date when the requirement is in a sprint — so link only where the requirement really covers the request.",
4642
- inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)"), requirementKey: mcpStr("Requirement key, e.g. reports.export") }, ["id", "requirementKey"]),
4643
- run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "link", requirementKey: a.requirementKey }),
4644
- },
4645
- {
4646
- name: "unlink_feature_request",
4647
- description: "Undo a link between a request from the app's users and a requirement.",
4648
- inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)") }, ["id"]),
4649
- run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "unlink" }),
4650
- },
4651
- {
4652
- name: "requests_integration_prompt",
4653
- description: "Procedure, API and example code for connecting this app's own feature-request page to qa-tools: requests and votes in, status (planned / released / declined) back to the app. Use when the app has a page where users request features or vote.",
4654
- inputSchema: mcpSchema(),
4655
- run: async () => require("./context-sync").requestsIntegrationPrompt(getCredentials()?.projectName || ""),
4656
- },
4657
- {
4658
- name: "new_app_questions",
4659
- description: "projects.new-app-guide: the questions for a new app (purpose, users, client, backend and hosting, database, login, language, where code and CI live) with their choices. Ask them one at a time; then create_project and apply_new_app_answers. Prompt new_app has the whole flow.",
4660
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
4661
- run: async () => mcpCall("getNewAppQuestions", {}),
4662
- },
4663
- {
4664
- name: "create_project",
4665
- description: "Create a new qa-tools project owned by the logged-in user. Needs the user's own login (qatools login --google); refused with a Claude API key, which belongs to one project.",
4666
- inputSchema: { type: "object", properties: { name: mcpStr("The app's name"), description: mcpStr("One sentence: what it does") }, required: ["name"], additionalProperties: false },
4667
- run: async (a) => mcpCall("createProject", { name: a.name, description: a.description || "" }),
4668
- },
4669
- {
4670
- name: "apply_new_app_answers",
4671
- description: "Fill a project's App Context from the new-app answers: { purpose, users, client, backend, database, auth: [], languages: [], codeHost } with choice values from new_app_questions, \"other:<text>\" or \"undecided\". Fields that already have content are reported as conflicts and not saved unless overwrite is true — ask the user first.",
4672
- inputSchema: mcpSchema({
4673
- answers: { type: "object", description: "The answers, keyed by question id", additionalProperties: true },
4674
- overwrite: mcpBool("Replace fields that already have content — only after the user confirmed"),
4675
- }, ["answers"]),
4676
- run: async (a) => mcpCall("applyNewAppAnswers", { projectId: a.projectId || getCredentials()?.projectId, answers: a.answers, overwrite: !!a.overwrite }),
4677
- },
4678
- {
4679
- name: "release_notes_prompt",
4680
- description: "What a release delivered and how to write release notes for the app's users (releases.release-notes): only what users notice, in their words, no keys or technical details. Default: the latest completed release.",
4681
- inputSchema: mcpSchema({ sprintId: mcpStr("The release: sprint id or name (default: latest completed)") }),
4682
- run: async (a) => (await mcpCall("getReleaseNotesPrompt", { projectId: a.projectId, sprintId: a.sprintId || "" })).prompt,
4683
- },
4684
- {
4685
- name: "save_release_notes_draft",
4686
- description: "Save a draft of a release's notes for the app's users. Refused if it names requirement keys, signal ids or commits. A member edits and publishes it in the sprint view — you never publish.",
4687
- inputSchema: mcpSchema({ sprintId: mcpStr("The release: sprint id or name"), text: mcpStr("The notes: short points in the users' language") }, ["sprintId", "text"]),
4688
- run: async (a) => mcpCall("saveReleaseNotesDraft", { projectId: a.projectId, sprintId: a.sprintId, text: a.text }),
4689
- },
4690
- {
4691
- name: "infra_prompt",
4692
- description: "Procedure for setting up or configuring the app's cloud resources (projects.infra-setup-prompt): take stock with the user's own cloud CLI, propose a plan, write infrastructure code, apply only after the user approves, secrets only in the vault, environments into the App Context.",
4693
- inputSchema: mcpSchema({ platform: mcpStr("azure, gcp, aws or firebase (default: from the App Context)", { enum: ["azure", "gcp", "aws", "firebase"] }) }),
4694
- run: async (a) => (await mcpCall("getInfraPrompt", { projectId: a.projectId, platform: a.platform || "" })).prompt,
4695
- },
4696
- // ---- cli.mcp-parity: the CLI's project-data commands, through the same backend functions ----
4697
- {
4698
- name: "update_project",
4699
- description: "Change the project's name or description (owner).",
4700
- inputSchema: mcpSchema({ name: mcpStr("New name"), description: mcpStr("New description") }),
4701
- run: async (a) => {
4702
- const updates = mcpPick(a, ["name", "description"]);
4703
- if (!Object.keys(updates).length) throw new McpToolError("Give name and/or description.");
4704
- return mcpCall("updateProjectFields", { projectId: a.projectId, updates });
4705
- },
4706
- },
4707
- {
4708
- name: "add_member",
4709
- description: "Add a member to the project by email; they get an invitation email. Owner only.",
4710
- inputSchema: mcpSchema({ email: mcpStr("The member's email") }, ["email"]),
4711
- run: async (a) => mcpCall("addProjectMember", { projectId: a.projectId, email: a.email }),
4712
- },
4713
- {
4714
- name: "remove_member",
4715
- description: "Remove a member from the project (the owner cannot be removed). Destructive: confirm with the user in this conversation before calling.",
4716
- inputSchema: mcpSchema({ email: mcpStr("The member's email") }, ["email"]),
4717
- run: async (a) => mcpCall("removeProjectMember", { projectId: a.projectId, email: a.email }),
4718
- },
4719
- {
4720
- name: "delete_requirement",
4721
- description: "Delete a requirement — only for junk (duplicate, created by mistake, wrong project). A requirement that was considered and turned out wrong is set to rejected or superseded with update_requirement instead. Refused while backlog items or tests reference its key unless force. Destructive: confirm with the user first.",
4722
- inputSchema: mcpSchema({ requirementId: mcpStr("Requirement document id"), force: mcpBool("Delete even though items or tests reference it — re-point them first") }, ["requirementId"]),
4723
- run: async (a) => mcpCall("deleteRequirement", { projectId: a.projectId, requirementId: a.requirementId, force: !!a.force }),
4724
- },
4725
- {
4726
- name: "delete_epic",
4727
- description: "Delete an epic by key. Refused while requirements belong to it. Destructive: confirm with the user first.",
4728
- inputSchema: mcpSchema({ epicKey: mcpStr("Epic key") }, ["epicKey"]),
4729
- run: async (a) => {
4730
- const epic = ((await mcpCall("listEpics", { projectId: a.projectId })).epics || []).find(e => e.key === a.epicKey);
4731
- if (!epic) throw new McpToolError(`Epic '${a.epicKey}' not found.`);
4732
- return mcpCall("deleteEpic", { projectId: a.projectId, epicId: epic.id });
4733
- },
4734
- },
4735
- {
4736
- name: "requirement_coverage",
4737
- description: "Per requirement: its manual test cases and automated test runs, and which ones verify it.",
4738
- inputSchema: mcpSchema(),
4739
- run: async (a) => mcpCall("requirementCoverage", { projectId: a.projectId }),
4740
- },
4741
- {
4742
- name: "list_requirement_keys",
4743
- description: "Every requirement key in use in the project's test protocols and backlog, with where it is used.",
4744
- inputSchema: mcpSchema(),
4745
- run: async (a) => mcpCall("listRequirementKeys", { projectId: a.projectId }),
4746
- },
4747
- {
4748
- name: "reject_template",
4749
- description: "Reject a test protocol (version) with a reason; it can no longer be started as a session.",
4750
- inputSchema: mcpSchema({ templateId: mcpStr("Test protocol id"), reason: mcpStr("Why — at least a few words") }, ["templateId", "reason"]),
4751
- run: async (a) => mcpCall("rejectTemplate", { projectId: a.projectId, templateId: a.templateId, reason: a.reason }),
4752
- },
4753
- {
4754
- name: "upload_test_report",
4755
- description: "Upload test results from a JUnit XML or JSON file on this computer as evidence on requirements (tests tagged with a requirementKey or [req:<key>]). Commit and branch come from git or CI.",
4756
- inputSchema: mcpSchema({ file: mcpStr("Path to the results file"), format: mcpStr("junit or json (default: from the file extension)", { enum: ["junit", "json"] }) }, ["file"]),
4757
- run: async (a) => {
4758
- const filePath = path.resolve(a.file);
4759
- if (!fs.existsSync(filePath)) throw new McpToolError(`File not found: ${filePath}`);
4760
- const text = fs.readFileSync(filePath, "utf-8");
4761
- const format = a.format || (/\.json$/i.test(filePath) ? "json" : "junit");
4762
- const results = format === "json" ? parseTestJson(JSON.parse(text)) : parseJUnit(text);
4763
- if (!results.length) throw new McpToolError("No test results found in the file.");
4764
- return mcpCall("uploadTestRun", { projectId: a.projectId, run: ciRunMeta({}), results });
4765
- },
4766
- },
4767
- {
4768
- name: "find_duplicates",
4769
- description: "Find backlog items that look like duplicates of each other (uses the project's Anthropic key on the server).",
4770
- inputSchema: mcpSchema(),
4771
- run: async (a) => mcpCall("findDuplicates", { projectId: a.projectId }),
4772
- },
4773
- {
4774
- name: "import_security_scan",
4775
- description: "Import a SARIF file from a security scanner on this computer; each finding becomes a technical defect (DEF) linked to the project, duplicates skipped.",
4776
- inputSchema: mcpSchema({ file: mcpStr("Path to the SARIF file"), source: mcpStr("Scanner name, e.g. codeql") }, ["file"]),
4777
- run: async (a) => {
4778
- const filePath = path.resolve(a.file);
4779
- if (!fs.existsSync(filePath)) throw new McpToolError(`File not found: ${filePath}`);
4780
- return mcpCall("importSecurityScan", { projectId: a.projectId, sarif: JSON.parse(fs.readFileSync(filePath, "utf-8")), source: a.source || "" });
4781
- },
4782
- },
4783
- {
4784
- name: "set_app_context",
4785
- description: "Replace the project's App Context. Read it with get_app_context first, change what the user asked for, and send the whole object back — fields left out are lost. Show the change to the user before saving.",
4786
- inputSchema: mcpSchema({ context: { type: "object", description: "The whole App Context", additionalProperties: true } }, ["context"]),
4787
- run: async (a) => mcpCall("saveAppContext", { projectId: a.projectId, context: a.context }),
4788
- },
4789
- {
4790
- name: "get_access_model",
4791
- description: "The project's access model: roles and what each may do.",
4792
- inputSchema: mcpSchema(),
4793
- run: async (a) => mcpCall("getAccessModel", { projectId: a.projectId }),
4794
- },
4795
- {
4796
- name: "set_access_model",
4797
- description: "Replace the project's access model (roles and permissions). Read it with get_access_model first and show the change to the user before saving.",
4798
- inputSchema: mcpSchema({ model: { type: "object", description: "The whole access model", additionalProperties: true } }, ["model"]),
4799
- run: async (a) => mcpCall("saveAccessModel", { projectId: a.projectId, model: a.model }),
4800
- },
4801
- {
4802
- name: "decline_feature_request",
4803
- description: "Decline a request from the app's users with a reason the app shows them. A member's decision: refused for Claude's API key — use the member's own login, or ask the user to decline it.",
4804
- inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)"), reason: mcpStr("Why — shown to the app's users") }, ["id", "reason"]),
4805
- run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "decline", reason: a.reason }),
4806
- },
4807
- {
4808
- name: "list_skill_library",
4809
- description: "The shared skill library: skills that can be added to a project's App Context.",
4810
- inputSchema: mcpSchema(),
4811
- run: async () => mcpCall("listSkillLibrary", {}),
4812
- },
4813
- {
4814
- name: "get_library_skill",
4815
- description: "Read one skill from the shared skill library.",
4816
- inputSchema: mcpSchema({ name: mcpStr("Skill name") }, ["name"]),
4817
- run: async (a) => mcpCall("getLibrarySkill", { name: a.name }),
4818
- },
4819
- {
4820
- name: "save_library_skill",
4821
- description: "Add or update a skill in the shared skill library (superadmin).",
4822
- inputSchema: mcpSchema({ name: mcpStr("Skill name (file name without .md)"), title: mcpStr("Title"), description: mcpStr("One line about it"), content: mcpStr("The skill's markdown") }, ["name", "title", "content"]),
4823
- run: async (a) => mcpCall("saveLibrarySkill", { name: a.name, title: a.title, description: a.description || "", content: a.content }),
4824
- },
4825
- {
4826
- name: "delete_library_skill",
4827
- description: "Remove a skill from the shared skill library (superadmin). Destructive: confirm with the user first.",
4828
- inputSchema: mcpSchema({ name: mcpStr("Skill name") }, ["name"]),
4829
- run: async (a) => mcpCall("deleteLibrarySkill", { name: a.name }),
4830
- },
4831
- {
4832
- name: "baseline_prompt",
4833
- description: "Procedure for reconstructing requirements for what is already built (requirements.baseline-from-code), with the project's language, its epics and all existing requirements. Use when code exists that qa-tools has no requirements for.",
4834
- inputSchema: mcpSchema(),
4835
- run: async (a) => (await mcpCall("getBaselinePrompt", { projectId: a.projectId })).prompt,
4836
- },
4837
- {
4838
- name: "upload_baseline",
4839
- description: "Upload requirements reconstructed from code. Each needs key, title, acceptanceCriteria (Given/When/Then in the project's language) and at least one file or commit where it is built. Saved as drafts marked as reconstructed; duplicates of existing requirements are skipped. A member approves them as built in the web app — you never approve them yourself.",
4840
- inputSchema: mcpSchema({
4841
- requirements: {
4842
- type: "array", description: "Reconstructed requirements (at most 100)",
4843
- items: {
4844
- type: "object",
4845
- properties: {
4846
- key: mcpStr("Semantic key, e.g. keys.search"), title: mcpStr("Title"), description: mcpStr("Description"),
4847
- acceptanceCriteria: mcpStr("Given/When/Then scenario(s), newline-separated"), negativeCriteria: mcpStr("Negative scenario(s)"),
4848
- type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }), epicKey: mcpStr("Epic key"),
4849
- files: mcpStrArray("Files where it is built, e.g. src/app/x.ts:40-88"), commits: mcpStrArray("Commits where it was built"),
4850
- },
4851
- required: ["key", "title", "acceptanceCriteria"],
4852
- },
4853
- },
4854
- }, ["requirements"]),
4855
- run: async (a) => mcpCall("uploadBaselineRequirements", { projectId: a.projectId, requirements: a.requirements }),
4856
- },
4857
- {
4858
- name: "list_requirement_library",
4859
- description: "The account's requirement library (library.shared-requirements): requirements shared by all projects of the same owner, with key, title, category, type and version.",
4860
- inputSchema: mcpSchema({ category: mcpStr("Only this category") }),
4861
- run: async (a) => {
4862
- const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
4863
- return a.category ? entries.filter(e => (e.category || "").toLowerCase() === a.category.toLowerCase()) : entries;
4864
- },
4865
- },
4866
- {
4867
- name: "share_requirement_to_library",
4868
- description: "Share a project requirement into the account's library; the requirement then inherits from it. Give generic wording in text and keep what is specific to this project in applicability. You cannot change a library entry afterwards — only the owner can.",
4869
- inputSchema: mcpSchema({
4870
- requirementId: mcpStr("Requirement document ID"),
4871
- text: { type: "object", description: "Generic wording for the library", properties: { title: mcpStr("Title"), description: mcpStr("Description"), acceptanceCriteria: mcpStr("Given/When/Then"), negativeCriteria: mcpStr("Negative Given/When/Then"), category: mcpStr("Category") }, additionalProperties: false },
4872
- applicability: mcpStr("What is specific to this project, e.g. 'Applies to Twilio, SendGrid, Auth0'"),
4873
- }, ["requirementId"]),
4874
- run: async (a) => mcpCall("shareRequirementToLibrary", { projectId: a.projectId, ...mcpPick(a, ["requirementId", "text", "applicability"]) }),
4875
- },
4876
- {
4877
- name: "inherit_library_requirements",
4878
- description: "Inherit library entries into the project, by keys or a whole category. What you inherit is created as drafts for a member to approve.",
4879
- inputSchema: mcpSchema({ keys: mcpStrArray("Library keys"), category: mcpStr("Every entry in this category"), applicability: mcpStr("What they apply to in this project") }),
4880
- run: async (a) => {
4881
- let libraryIds;
4882
- if (a.keys?.length) {
4883
- const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
4884
- libraryIds = entries.filter(e => a.keys.includes(e.key)).map(e => e.id);
4885
- }
4886
- return mcpCall("inheritLibraryRequirements", { projectId: a.projectId, libraryIds, category: a.category, applicability: a.applicability });
4887
- },
4888
- },
4889
- {
4890
- name: "create_test_protocol",
4891
- description: "Create a sprint's manual test protocol after a plan was approved in this conversation (sprint.ai-planning-manual-tests). Only tests a person must perform — what you can verify yourself belongs in automated tests in the code. It is saved for review (pending_review); a project member approves it under Test protocols, never you.",
4892
- inputSchema: mcpSchema({
4893
- sprintId: mcpStr("Sprint ID the protocol belongs to"),
4894
- name: mcpStr("Protocol name, e.g. 'Release 4.1 — manual tests'"),
4895
- sections: {
4896
- type: "array",
4897
- description: "Sections of manual tests",
4898
- items: {
4899
- type: "object",
4900
- properties: {
4901
- title: mcpStr("Section title"),
4902
- tests: {
4903
- type: "array",
4904
- items: {
4905
- type: "object",
4906
- properties: {
4907
- id: mcpStr("Test id, e.g. M-1"),
4908
- name: mcpStr("What is tested"),
4909
- steps: mcpStr("Steps a person follows"),
4910
- expected: mcpStr("Expected result"),
4911
- purpose: mcpStr("Why a person must perform this, e.g. 'real phone camera', 'SMS must actually arrive', 'visual check'"),
4912
- requirementKey: mcpStr("Key of the requirement it verifies"),
4913
- },
4914
- required: ["name", "steps", "expected", "purpose", "requirementKey"],
4915
- additionalProperties: false,
4916
- },
4917
- },
4918
- },
4919
- required: ["title", "tests"],
4920
- additionalProperties: false,
4921
- },
4922
- },
4923
- replaces: mcpStr("Optional: the id of a protocol this is the next version of (it is superseded). The same name as an existing protocol makes the next version anyway"),
4924
- }, ["sprintId", "name", "sections"]),
4925
- run: async (a) => {
4926
- for (const sec of a.sections) for (const t of sec.tests || []) {
4927
- if (!String(t.purpose || "").trim()) throw new McpToolError(`Test "${t.name}" needs a purpose saying why a person must perform it`);
4928
- }
4929
- const r = await mcpCall("uploadTemplate", { projectId: a.projectId, sprintId: a.sprintId, name: a.name, sections: a.sections, ...(a.replaces ? { replaces: a.replaces } : {}) });
4930
- return { ...r, next: "Pending review. A project member approves it in qa-tools under Test protocols." };
4931
- },
4932
- },
4933
- {
4934
- name: "list_templates",
4935
- description: "List test templates (test protocols) and their review status.",
4936
- inputSchema: mcpSchema({ status: mcpStr("Filter by review status", { enum: ["draft", "pending_review", "approved", "rejected"] }) }),
4937
- run: async (a) => (await mcpCall("listTemplates", { projectId: a.projectId, status: a.status || null })).templates,
4938
- },
4939
- {
4940
- name: "pending_sessions",
4941
- description: "Test sessions awaiting Claude analysis.",
4942
- inputSchema: mcpSchema(),
4943
- run: async (a) => (await mcpCall("pendingSessions", { projectId: a.projectId })).pending,
4944
- },
4945
- {
4946
- name: "read_session",
4947
- description: "Read a test session with its template and linked backlog details.",
4948
- inputSchema: { type: "object", properties: { sessionId: mcpStr("Test session ID") }, required: ["sessionId"], additionalProperties: false },
4949
- noProject: true,
4950
- run: async (a) => mcpCall("readSession", { sessionId: a.sessionId }),
4951
- },
4952
- {
4953
- name: "upload_analysis",
4954
- description: "Upload an analysis of a test session (same format as `qatools upload-analysis`): analysis[] with verdicts, and optional backlogUpdates keyed by item ID.",
4955
- inputSchema: {
4956
- type: "object",
4957
- properties: {
4958
- sessionId: mcpStr("Test session ID"),
4959
- analysis: { type: "array", items: { type: "object" }, description: "Analysis entries" },
4960
- backlogUpdates: { type: "object", description: "Backlog updates keyed by item ID: { status, evidence, comment, assignedTo, priority }. status=resolved needs evidence (min 10 chars) and an item already in ready_for_test (GAP exempt) — otherwise the whole upload is refused and nothing is saved." },
4961
- },
4962
- required: ["sessionId", "analysis"],
4963
- additionalProperties: false,
4964
- },
4965
- noProject: true,
4966
- run: async (a) => mcpCall("uploadAnalysis", { sessionId: a.sessionId, analysis: a.analysis, backlogUpdates: a.backlogUpdates || {} }),
4967
- },
4968
- ];
4969
-
4970
- // automation.daily-agenda-run: the unattended procedure. Shared by the MCP prompt daily_agenda_run and
4971
- // `qatools agenda-run-prompt` (for `claude -p`), so both always say the same thing.
4972
- function dailyAgendaRunPrompt(projectId) {
4973
- const a = { projectId };
4974
- return `You are running UNATTENDED on the qa-tools project${a.projectId ? ` ${a.projectId}` : ""}. Nobody will answer questions. Use a propose-only key: the backend refuses status changes, planning, deletes and member changes — if a tool is refused, note it in the summary and move on; never try another way.
4975
-
4976
- Work through these steps, then stop:
4977
-
4978
- 1. get_agenda. This is your task list.
4979
- 2. Sessions awaiting analysis: for each, read_session and compare every FEL result against its requirement (list_requirements). Upload your analysis with upload_analysis — backlogUpdates may only contain comments. For a real deviation not already on the backlog (check list_backlog by requirementKey), create_backlog_item with type bug (AVV), requirement_gap (GAP) or technical_defect (DEF) and the requirementKey. Cite the test and expected vs actual; never speculate.
4980
- 3. Planning: list_plan_proposals with status pending. If one created by Claude is already pending, do NOT create another — mention it in the summary. Otherwise, if there are approved functional requirements without a sprint and sprints that are not completed, follow the plan_sprints procedure (sprint_velocity, epic dependsOn, priority) and save the result with propose_sprint_plan.
4981
- 4. Approved requirements without tests (from the agenda) and continuous requirements still unverified this sprint (list_compliance_due): do not act — a propose-only key can't record verifications — just count them and name the unverified continuous requirement keys in the summary.
4982
- 5. Finish with notify_owner. Subject: "qa-tools daily run: <project> — <n> to review". Body, plain text, short:
4983
- - what you analysed and which signals you created (labels),
4984
- - the plan proposal you saved (or why none),
4985
- - anything that was refused or that needs a human decision,
4986
- - where to look: qa-tools → Sprints → Plan proposals, Backlog.
4987
- If there was nothing to do, still send a one-line summary saying so.`;
4988
- }
4989
-
4990
- // Prompts (sprint.ai-planning): ready-made workflows the user picks in the client, e.g. the "+" menu in Claude Desktop.
4991
- const mcpPrompts = [
4992
- {
4993
- name: "plan_sprints",
4994
- description: "Plan approved requirements into sprints: Claude proposes, you approve, then it applies.",
4995
- arguments: [
4996
- { name: "projectId", description: "Project ID (default: configured project)", required: false },
4997
- { name: "goal", description: "What to optimise for, e.g. 'release 4.0 by Nov 18' or 'auth first'", required: false },
4998
- ],
4999
- text: (a) => `Plan sprints in qa-tools${a.projectId ? ` for project ${a.projectId}` : ""}.${a.goal ? ` Goal: ${a.goal}.` : ""}
5000
-
5001
- Follow these steps in order:
5002
-
5003
- 1. Gather facts, don't guess: list_sprints, sprint_velocity, list_epics, list_requirements (status approved, plus anything already planned in open sprints).
5004
- 2. Draft a plan. Only requirements are planned — never create backlog items as tasks. Rules:
5005
- - Only status=approved, functional requirements without a sprint are candidates. Non-functional (compliance) requirements are continuous — never plan them. Never touch completed sprints or the requirements in them. Requirements in other sprints stay where they are, except carry-over from overdue sprints (below).
5006
- - An epic's requirements never go into an earlier sprint than the requirements of the epics it dependsOn.
5007
- - Order by priority (1 first), then epic priority.
5008
- - Per sprint, plan up to sprint_velocity's capacity (points, or requirements when no completed sprint has points — say so), counting what is already planned there (openSprints[].points). If there is no history, say so and propose a conservative number. Mention averageCompletionRate (the share of planned requirements that usually gets done) in the proposal.
5009
- - User demand (signals.user-feature-requests): requirements carry requestVotes, the votes of the users' requests linked to them. Among requirements of the same priority, plan the ones with more votes first, and name the votes in the reason when they decided the order.
5010
- - Points (sprint.requirement-points): a requirement without points gets proposed points, 1, 2, 3, 5 or 8 — anything bigger should be split, say so instead. Pass them as points on the propose_sprint_plan row; approving the row sets them. Non-functional requirements have no points.
5011
- - Carry-over: a sprint is overdue when its end date (releaseDate) is before today and it is not completed. Requirements in an overdue sprint that are approved or in progress are candidates to MOVE to an open sprint; they keep their status and assignee, and the reason names the overdue sprint. Never move requirements out of a sprint that has not passed its end date.
5012
- - If the requirements don't fit in the existing sprints, propose new sprints (name + end date) — don't create them yet.
5013
- - Mid-release change (sprint.mid-release-swap): when the user wants something taken into a sprint that is in progress (start date passed, end date not), don't overfill it silently — propose a swap (propose_sprint_plan swaps): the requirement in, and not-started (approved) requirements of about the same points out to the next open sprint, lowest priority first, never one a staying requirement depends on through its epic. Show it as its own table: sprint | in | out | points freed | reason.
5014
- 3. Present the proposal as a table: sprint | requirement key | title | points (mark proposed ones) | reason (priority / epic dependency / capacity) | Claude verifies by (how you will verify it yourself — unit/integration tests, an API call, a build check — or "manual tests only" when you can't). Pass the same text as selfVerification on each propose_sprint_plan row, and manualOnly true for the "manual tests only" ones (the protocol must then have a test for them). Show moves out of overdue sprints as their own rows, marked as moves, separate from newly planned requirements. Also list what you deliberately left out and why, and any dependency conflicts you found.
5015
- 4. STOP and ask the user: approve here, or save it as a proposal to decide later in qa-tools? Change nothing before that. Apply any adjustments the user asks for and show the table again.
5016
- - If nobody is there to answer (an unattended run), or the user chooses "later": call propose_sprint_plan with the same rows, and report the result. Do not apply anything yourself.
5017
- 5. After approval in this conversation: create_sprint for any new sprints, then update_requirement with sprintId for each planned requirement. Report each change and any refusal verbatim — never retry a refused change in a different way.
5018
- 6. Manual tests, per sprint: draft a test protocol with the tests a person must perform because you can't verify them yourself — look and feel, real mobile devices, e-mail/SMS actually arriving, BankID/Freja, printing/PDF, flows between several parties. Each test has requirementKey (a requirement planned in that sprint) and a purpose saying why a person must do it. What you can verify yourself goes into automated tests in the code, not here. Show the tests with the plan. With propose_sprint_plan, pass them as testProtocols (approved together with the proposal). After approval in the conversation, save each with create_test_protocol (pending review — a member approves it). A sprint with nothing that needs a person gets no protocol; say so. Regression: run requirement_impact for the sprint; the approved manual tests of requirements it lists (or that get_agenda lists under regressionRisk) go into a section "Regression" of the same protocol.
5019
- 7. End with get_sprint_items for each affected sprint so the user can see the result.`,
5020
- },
5021
- {
5022
- name: "daily_agenda_run",
5023
- description: "Unattended run (automation.daily-agenda-run): work through the project agenda, propose — never apply — and email the owner a summary.",
5024
- arguments: [{ name: "projectId", description: "Project ID (default: configured project)", required: false }],
5025
- text: (a) => dailyAgendaRunPrompt(a.projectId),
5026
- },
5027
- {
5028
- name: "new_app",
5029
- description: "projects.new-app-guide: start a new app — ask the user how it should be built, create the project and fill its App Context.",
5030
- arguments: [{ name: "name", description: "The app's name, if already known", required: false }],
5031
- text: (a) => `Help the user start a new app in qa-tools${a.name ? ` called "${a.name}"` : ""}.
5032
-
5033
- 1. Get the questions: new_app_questions. Ask them ONE AT A TIME in the user's language, offering the listed choices plus "other" and "not decided yet". Let the user skip any question. Do not choose for the user; "not decided yet" is a fine answer.
5034
- 2. When you have the answers and a name, create the project: create_project (name, description = the purpose). It needs the user's own login; if it is refused because the MCP server runs with a Claude API key, tell the user to create the project in the web app (or run qatools login --google) and give you its ID, then continue with step 3.
5035
- 3. Fill its App Context: apply_new_app_answers with projectId and the answers (choice values, "other:<text>" or "undecided"). If it reports conflicts (an App Context that already has content), show the user which fields would change and call it again with overwrite: true only if they say yes.
5036
- 4. Tell the user the next step: in the new repo, qatools setup (pick the project) and qatools init; then you can propose the first epics from the App Context.`,
5037
- },
5038
- ];
5039
-
5040
- function mcpValidateArgs(tool, args) {
5041
- for (const k of tool.inputSchema.required || []) {
5042
- if (args[k] === undefined || args[k] === null || args[k] === "") throw new McpToolError(`Missing required argument: ${k}`);
5043
- }
5044
- const known = tool.inputSchema.properties;
5045
- const unknown = Object.keys(args).filter(k => !(k in known));
5046
- if (unknown.length) throw new McpToolError(`Unknown argument(s): ${unknown.join(", ")}`);
5047
- }
5048
-
5049
- async function mcpHandle(msg, defaultProjectId) {
5050
- const { method, params } = msg;
5051
- if (method === "initialize") {
5052
- const requested = params?.protocolVersion;
5053
- return {
5054
- protocolVersion: MCP_PROTOCOL_VERSIONS.includes(requested) ? requested : MCP_PROTOCOL_VERSIONS[0],
5055
- capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } },
5056
- serverInfo: { name: "qatools", version: require("./package.json").version },
5057
- instructions: MCP_INSTRUCTIONS + (mcpWarnings.length ? "\n- OUT OF DATE — tell the user before anything else: " + mcpWarnings.join(" ") : ""),
5058
- };
5059
- }
5060
- if (method === "ping") return {};
5061
- if (method === "tools/list") {
5062
- return { tools: mcpTools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) };
5063
- }
5064
- if (method === "prompts/list") {
5065
- return { prompts: mcpPrompts.map(({ name, description, arguments: args }) => ({ name, description, arguments: args })) };
5066
- }
5067
- if (method === "prompts/get") {
5068
- const prompt = mcpPrompts.find(p => p.name === params?.name);
5069
- if (!prompt) throw Object.assign(new Error(`Unknown prompt: ${params?.name}`), { code: -32602 });
5070
- const args = params.arguments || {};
5071
- return { description: prompt.description, messages: [{ role: "user", content: { type: "text", text: prompt.text(args) } }] };
5072
- }
5073
- if (method === "tools/call") {
5074
- const tool = mcpTools.find(t => t.name === params?.name);
5075
- if (!tool) throw Object.assign(new Error(`Unknown tool: ${params?.name}`), { code: -32602 });
5076
- const args = { ...(params.arguments || {}) };
5077
- try {
5078
- mcpValidateArgs(tool, args);
5079
- if (!tool.noProject) {
5080
- args.projectId = args.projectId || defaultProjectId;
5081
- if (!args.projectId) throw new McpToolError("No project configured. Pass projectId, or run: qatools setup");
5082
- }
5083
- const data = await tool.run(args);
5084
- return { content: [{ type: "text", text: typeof data === "string" ? data : JSON.stringify(data ?? null, null, 2) }] };
5085
- } catch (e) {
5086
- // Tool failures (refusals, backend permission errors) go back as tool results the model can read.
5087
- return { content: [{ type: "text", text: e.message || String(e) }], isError: true };
5088
- }
5089
- }
5090
- throw Object.assign(new Error(`Method not found: ${method}`), { code: -32601 });
4105
+ // Local Model Context Protocol server over stdio. The tools, prompts and handler live in mcp-core.js, shared with
4106
+ // the connector on qa-tools' server (loop.chat-connector).
4107
+ const { createMcp, dailyAgendaRunPrompt, loopRunPrompt } = require("./mcp-core");
4108
+ let mcpCore = null;
4109
+ function mcpHandle(msg, defaultProjectId) {
4110
+ mcpCore = mcpCore || createMcp({
4111
+ call: async (name, data) => (await httpsCallable(functions, name)(data)).data,
4112
+ version: require("./package.json").version,
4113
+ warnings: () => mcpWarnings,
4114
+ local: { fs, path, currentGitCommit, getCredentials, uploadEvidenceFiles, runImpact, runEvidenceBackfill, parseJUnit, parseTestJson, ciRunMeta },
4115
+ });
4116
+ return mcpCore.handle(msg, defaultProjectId);
5091
4117
  }
5092
4118
 
5093
4119
  program
@@ -5299,36 +4325,44 @@ program
5299
4325
  .option("--main <ref>", "The main branch (default: origin/HEAD, else origin/main, origin/master, main, master)")
5300
4326
  .option("--project <id>", "Target project ID")
5301
4327
  .action(async (options) => {
5302
- const { isGitRepo, mainRef, findKeyCommits } = require("./impact");
5303
- const cwd = process.cwd();
5304
- if (!isGitRepo(cwd)) { console.error("qatools evidence-backfill must run in the project's git repository"); process.exit(1); }
5305
- const main = mainRef(cwd, options.main);
5306
- if (!main) { console.error("No main branch found — pass --main <ref>"); process.exit(1); }
4328
+ const { isGitRepo, mainRef } = require("./impact");
4329
+ if (!isGitRepo(process.cwd())) { console.error("qatools evidence-backfill must run in the project's git repository"); process.exit(1); }
4330
+ if (!mainRef(process.cwd(), options.main)) { console.error("No main branch found — pass --main <ref>"); process.exit(1); }
5307
4331
  await authenticate(options);
5308
4332
  const projectId = options.project || getCredentials()?.projectId;
5309
4333
  if (!projectId) { console.error("No project configured. Run: qatools setup, or pass --project <id>"); process.exit(1); }
5310
4334
  try {
5311
- const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
5312
- const latest = new Map();
5313
- for (const r of requirements) {
5314
- if (r.status === "superseded") continue;
5315
- const cur = latest.get(r.key);
5316
- if (!cur || (r.version || 1) > (cur.version || 1)) latest.set(r.key, r);
5317
- }
5318
- const { found, none } = findKeyCommits({ cwd, requirements: [...latest.values()], main });
4335
+ const { main, found, none, linked, skipped } = await runEvidenceBackfill({ projectId, apply: !!options.apply, main: options.main });
5319
4336
  console.log(`${found.length} verified requirement(s) without an evidence commit have one on ${main}:\n`);
5320
4337
  for (const f of found) console.log(` ${f.key}: ${f.commit.slice(0, 8)} ${f.date} ${f.subject.slice(0, 70)}`);
5321
4338
  if (none.length) console.log(`\n${none.length} have no commit on ${main} that names their key: ${none.join(", ")}`);
5322
4339
  if (!options.apply) { if (found.length) console.log("\nAdd --apply to record these as commit links (not new verifications)."); process.exit(0); }
5323
- if (!found.length) process.exit(0);
5324
- const res = (await httpsCallable(functions, "linkEvidenceCommit")({ projectId, items: found.map(f => ({
5325
- requirementId: f.id, commit: f.commit, how: `newest commit on ${main} naming ${f.key}: ${f.subject.slice(0, 120)} (${f.date})`,
5326
- })) })).data;
5327
- console.log(`\nRecorded ${res.linked.length} commit link(s)${res.skipped.length ? `, skipped ${res.skipped.length}` : ""}.`);
4340
+ if (linked) console.log(`\nRecorded ${linked.length} commit link(s)${skipped.length ? `, skipped ${skipped.length}` : ""}.`);
5328
4341
  } catch (e) { console.error("Failed:", e.message); process.exit(1); }
5329
4342
  process.exit(0);
5330
4343
  });
5331
4344
 
4345
+ // traceability.evidence-commit-backfill: shared by the command and the MCP tool evidence_backfill (runs in the repo)
4346
+ async function runEvidenceBackfill({ projectId, apply = false, main: mainOpt, cwd = process.cwd() }) {
4347
+ const { isGitRepo, mainRef, findKeyCommits } = require("./impact");
4348
+ if (!isGitRepo(cwd)) throw new Error("evidence backfill must run in the project's git repository");
4349
+ const main = mainRef(cwd, mainOpt);
4350
+ if (!main) throw new Error("No main branch found — pass main");
4351
+ const { requirements } = (await httpsCallable(functions, "listRequirements")({ projectId, status: null })).data;
4352
+ const latest = new Map();
4353
+ for (const r of requirements) {
4354
+ if (r.status === "superseded") continue;
4355
+ const cur = latest.get(r.key);
4356
+ if (!cur || (r.version || 1) > (cur.version || 1)) latest.set(r.key, r);
4357
+ }
4358
+ const { found, none } = findKeyCommits({ cwd, requirements: [...latest.values()], main });
4359
+ if (!apply || !found.length) return { main, found, none };
4360
+ const res = (await httpsCallable(functions, "linkEvidenceCommit")({ projectId, items: found.map(f => ({
4361
+ requirementId: f.id, commit: f.commit, how: `newest commit on ${main} naming ${f.key}: ${f.subject.slice(0, 120)} (${f.date})`,
4362
+ })) })).data;
4363
+ return { main, found, none, linked: res.linked, skipped: res.skipped };
4364
+ }
4365
+
5332
4366
  // requirements.done-means-merged: branches with requirement work that is not merged
5333
4367
  program
5334
4368
  .command("branches")