qatools-cli 1.3.2 → 1.3.3

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 (4) hide show
  1. package/brief.js +9 -1
  2. package/mcp-core.js +1208 -1156
  3. package/package.json +1 -1
  4. package/qatools.js +8 -2
package/mcp-core.js CHANGED
@@ -1,1156 +1,1208 @@
1
- // cli.mcp-server / loop.chat-connector: the qa-tools MCP tools, prompts and request handler, shared by
2
- // `qatools mcp` (stdio, on the user's computer) and the connector on qa-tools' server (Claude adds it with one click).
3
- // Every tool calls the same backend function as its CLI counterpart, so the same checks apply everywhere.
4
- // createMcp(env):
5
- // env.call(name, data) → calls a backend function as the signed-in person (callable over HTTPS in the CLI,
6
- // in-process on the server)
7
- // env.local → helpers that need the user's computer (git, local files); null on the server, where
8
- // the tools that need them are left out and attachments are refused
9
- // env.warnings() → out-of-date warnings to pass on to the model; env.version → shown as serverInfo.version
10
- // env.noDefaultProject → true on the server: there is no configured project, so tools need projectId
11
- // functions/mcp-core.js is a copy made by scripts/sync-mcp-core.js; a test fails when the two differ.
12
-
13
- // Backlog labels as the web app shows them (project.ts typePrefix): bug → AVV-12 etc.
14
- const BACKLOG_PREFIX = { bug: "AVV", improvement: "IMP", requirement_gap: "GAP", technical_defect: "DEF" };
15
- const backlogLabel = (type, n) => `${BACKLOG_PREFIX[type] || "AVV"}-${n}`;
16
-
17
- // Status guards shared by the CLI commands and the MCP server (cli.mcp-access-parity) —
18
- // one implementation, so an MCP tool can never be looser than its CLI counterpart.
19
- const REQUIREMENT_STATUSES_REQUIRING_EVIDENCE = new Set(["implemented", "tested"]);
20
-
21
- // updates: { requirementId: { status, ... } }, evidenceById: { requirementId: text }
22
- function requirementEvidenceViolations(updates, evidenceById) {
23
- const violations = [];
24
- for (const [id, u] of Object.entries(updates)) {
25
- if (u.status && REQUIREMENT_STATUSES_REQUIRING_EVIDENCE.has(u.status)) {
26
- const ev = (evidenceById[id] || "").trim();
27
- if (ev.length < 10) violations.push({ id, status: u.status });
28
- }
29
- }
30
- return violations;
31
- }
32
-
33
- // Backlog: status=resolved needs evidence (min 10 chars) and, for AVV/DEF/IMP, a prior ready_for_test.
34
- // GAP (requirement_gap) is exempt from both. Throws if the backlog can't be listed.
35
- async function backlogResolveViolations(call, projectId, updates, { skipTestVerification = false } = {}) {
36
- const out = { evidence: [], flow: [] };
37
- const resolving = Object.entries(updates).filter(([, u]) => u.status === "resolved");
38
- if (resolving.length === 0) return out;
39
- const listResult = await call("listBacklog", { projectId });
40
- const itemById = {};
41
- for (const it of listResult.items || []) itemById[it.id] = it;
42
- for (const [id, u] of resolving) {
43
- const item = itemById[id];
44
- if (!item) continue;
45
- if (item.type === "requirement_gap") continue;
46
- const v = { id, type: item.type, currentStatus: item.status, description: (item.description || "").substring(0, 80) };
47
- if ((u.evidence || "").trim().length < 10) out.evidence.push(v);
48
- if (!skipTestVerification && item.status !== "ready_for_test") out.flow.push(v);
49
- }
50
- return out;
51
- }
52
-
53
- const MCP_LOCAL_ONLY = new Set(["requirement_impact", "upload_test_report", "import_security_scan", "evidence_backfill", "get_brief"]);
54
-
55
- // automation.daily-agenda-run: the unattended procedure. Shared by the MCP prompt daily_agenda_run and
56
- // `qatools agenda-run-prompt` (for `claude -p`), so both always say the same thing.
57
- function dailyAgendaRunPrompt(projectId) {
58
- const a = { projectId };
59
- 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.
60
-
61
- Work through these steps, then stop:
62
-
63
- 1. get_agenda. This is your task list.
64
- 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.
65
- 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.
66
- 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.
67
- 5. Finish with notify_owner with run: "daily" (or qatools notify --to <owner> --run daily) — it also tells qa-tools the run happened. Subject: "qa-tools daily run: <project> — <n> to review". Body, plain text, short:
68
- - what you analysed and which signals you created (labels),
69
- - the plan proposal you saved (or why none),
70
- - anything that was refused or that needs a human decision,
71
- - where to look: qa-tools → Sprints → Plan proposals, Backlog.
72
- If there was nothing to do, still send a one-line summary saying so.`;
73
- }
74
-
75
- // loop.claude-builds-approved (epic LOOP): the unattended run of the self-playing loop, in the app's repo — the
76
- // people who made the wishes only work in qa-tools. Shared by `qatools loop-run-prompt` (for claude -p) and the
77
- // MCP prompt loop_run, so both always say the same thing.
78
- function loopRunPrompt(projectId) {
79
- return `You are running UNATTENDED in this app's git repository, as the developer of the qa-tools project${projectId ? ` ${projectId}` : ""}. Nobody is at the keyboard. The people who made the wishes work only in qa-tools: everything you say to them goes into the wish (the backlog item) as a comment, in their language, in plain words — no code, file names or technical terms.
80
-
81
- Hard rules — never break them:
82
- - Use this repo's qa-tools key (QATOOLS_API_KEY, or the key file the repo documents) and pass the project; never run qatools setup or qatools login — they change the computer-wide default that other projects use. If an MCP tool refuses with "API key is not valid for this project", the MCP server runs on another project's login: do the same through the CLI with this repo's key (QATOOLS_API_KEY=<key> qatools …), e.g. qatools notify instead of notify_owner or notify_member.
83
- - Never deploy to production, never merge into the main branch, never push to it. Production is a person's decision.
84
- - Never approve a requirement, and never set a wish to resolved. You draft; a person approves and confirms.
85
- - At most ONE wish is built per run. When a test keeps failing or something is unclear, stop and say so in the wish.
86
- - Never try the same build a third time on your own: after two failed attempts the wish goes on hold for a person (step 2).
87
- - Nothing is done without evidence: implemented needs test output or file:line in evidence.
88
-
89
- Steps, in order:
90
-
91
- 1. Wishes to answer: list_backlog (statuses open, in_progress, on_hold). A wish is an item written by a person (not by Claude). Read its comments. Answer when it has no comment from you yet, or when the person wrote after your last comment. A wish on hold: answer only when the person wrote after your last comment, and then set it back to in_progress (update_backlog_item) — the person has looked at it, so its attempts count from zero again. Otherwise leave it on hold:
92
- - Something important unclear: ask ONE concrete question with 2–4 short choices (update_backlog_item comment).
93
- - Clear: write "Så här har jag förstått dig:" / "This is how I understood you:" and in a few plain sentences what will be built, ending with "Svara ja om det stämmer, annars vad som ska ändras." / "Answer yes if that is right, otherwise what to change."
94
- - When you write your understanding, also write the requirement as a DRAFT (create_requirement status draft, Given/When/Then in the wish's language, never mixing languages) and link the wish to it (update_backlog_item requirementKey). The person approves it in the wish with "Ja, det stämmer" / "Yes, that is right" — that sets the requirement approved. Never approve it yourself, and do not build it before it is approved. Tell the person who made the wish ONCE that it waits for their yes (notify_member, or qatools notify --to <them>; plain words, the wish's label; it respects their opt-out) — not again on later runs.
95
- A wish that comes back after it was built (the person tried it and wrote "Nej, det är inte vad jag menade: …" / "No, that is not what I meant: …"): its linked requirement is a draft again. Answer the same way, and change that draft with update_requirement (title, description, acceptance criteria) to what you now understand — do not create a new requirement. The person approves it again in the wish.
96
- At most 6 answers from you per wish; after that, say a person needs to look at it.
97
-
98
- 2. Build one approved wish: list_requirements status approved; take the first that a wish links to (its requirementKey), whose wish is not on hold, and that is not started. Then:
99
- - update_requirement status in_progress, assignedTo "me"; comment in the wish that you have started.
100
- - git switch -c loop/<requirement key> from the main branch (git pull first); if the branch exists (the wish came back after a "no"), switch to it and merge the main branch into it. Implement it the way the repo already works (read CLAUDE.md and the code around it). Add or extend automated tests for its acceptance criteria.
101
- - Verify with the project's own check commands: get_app_context verifyCommands (CLAUDE.md lists them too). Run every one, in a mode that ends by itself (no watch mode: e.g. --watch=false, CI=true). If none are set, run the repo's tests and build the same way, and say in the summary that the project has no check commands. If one fails and you cannot fix it: commit the work in progress on the branch, push the branch, set the requirement back to approved. Then count your comments in the wish that start with "Jag kom inte hela vägen" / "I could not finish it" and were written after the person's last comment:
102
- - none: comment "Jag kom inte hela vägen (försök 1 av 2): <what stops you, in plain words, including which check failed>" / "I could not finish it (attempt 1 of 2): …". The next run tries once more.
103
- - one or more: update_backlog_item status on_hold with the comment "Jag kom inte hela vägen (försök 2 av 2): <what was tried and what failed, in plain words>. En person behöver titta på det innan jag försöker igen." / "I could not finish it (attempt 2 of 2): … A person needs to look at it before I try again." Later runs skip it until the person writes in the wish.
104
- Stop.
105
- - When everything passes: commit (the message names the requirement key), push the branch, open a pull request if gh is available.
106
- - Test environment: get_app_context. If its environments list one named test (or Test, staging), deploy the branch there with the repo's own documented test deploy, and check that the change works there. If there is none, do NOT deploy.
107
- - update_requirement status implemented with evidence: each check command you ran and its result (numbers), the branch and commit, and the test address if deployed.
108
- - update_backlog_item status ready_for_test with a comment in plain words: what was built, and either "Prova här: <test address>" / "Try it here: <test address>", or that it is built and tested on a branch and waits for a person to put it on a test environment. The person who made the wish answers in qa-tools "Ja, det är vad jag menade" / "Yes, that is what I meant" (that sets the requirement tested and the wish done) or says what is wrong — never answer for them.
109
-
110
- 3. Finish with notify_owner with run: "loop" (or qatools notify --to <owner> --run loop) — always, also when there was nothing to do: it tells qa-tools the run happened. Subject: "qa-tools loop: <project> — <n> answered, <built or nothing built>". Body, plain text, short: which wishes you answered, which requirement drafts wait for approval, what you built (branch, test address) or why nothing, the wishes you put on hold after two failed attempts, anything that needs a person.`;
111
- }
112
-
113
-
114
- function createMcp(env) {
115
- let tools, instructions; // set below, once the tool table exists
116
- const warnings = () => (env.warnings ? env.warnings() : []);
117
- const local = env.local || {};
118
- const fs = local.fs, path = local.path;
119
- const currentGitCommit = local.currentGitCommit || (() => null);
120
- const getCredentials = local.getCredentials || (() => null);
121
- const runImpact = local.runImpact, runEvidenceBackfill = local.runEvidenceBackfill, parseJUnit = local.parseJUnit, parseTestJson = local.parseTestJson, ciRunMeta = local.ciRunMeta;
122
- const uploadEvidenceFiles = local.uploadEvidenceFiles || (async (projectId, files) => {
123
- if (files && files.length) throw new McpToolError("Attachments are local files and cannot be sent through the qa-tools connector — use qatools mcp on your computer, or attach them in the web app");
124
- return undefined;
125
- });
126
-
127
- // Local Model Context Protocol server over stdio: newline-delimited JSON-RPC 2.0 on stdin/stdout.
128
- // Every tool calls the same Cloud Functions callable as its CLI counterpart — no direct Firestore
129
- // access — and write tools reuse the shared status guards above (cli.mcp-access-parity).
130
- // Deletes are deliberately not exposed: they stay behind the CLI/UI confirmation paths.
131
-
132
- const MCP_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
133
-
134
- const MCP_INSTRUCTIONS = `qa-tools: requirements-driven QA. Rules that apply to every tool:
135
- - Build from requirements. Planning is Epics → Requirements → Sprints (requirement.sprintId).
136
- - The backlog is signals (bug=AVV, requirement_gap=GAP, technical_defect=DEF, improvement=IMP), not a task list.
137
- - 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.
138
- - Requirement status implemented/tested needs evidence: test output, file:line, expected vs actual, or "no test applies because <reason>".
139
- - Before implemented or ready_for_test, run the project's check commands (get_app_context verifyCommands) and see them pass; the evidence names each command and its result.
140
- - 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.
141
- - 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.
142
- - 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.
143
- - 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.
144
- - Every tool takes an optional projectId; without it the configured project (qatools setup) is used.`;
145
-
146
- const mcpStr = (description, extra = {}) => ({ type: "string", description, ...extra });
147
- const mcpInt = (description, extra = {}) => ({ type: "integer", description, ...extra });
148
- const mcpBool = (description) => ({ type: "boolean", description });
149
- const mcpStrArray = (description, items = { type: "string" }) => ({ type: "array", items, description });
150
- const MCP_PROJECT_PROP = { projectId: mcpStr("Project ID. Defaults to the configured project.") };
151
- const MCP_REQ_STATUSES = ["draft", "approved", "in_progress", "rejected", "implemented", "tested", "superseded"];
152
- const MCP_BACKLOG_STATUSES = ["open", "in_progress", "on_hold", "ready_for_test", "resolved", "rejected"];
153
- const MCP_BACKLOG_TYPES = ["bug", "improvement", "requirement_gap", "technical_defect"];
154
- const MCP_PRIORITY = mcpInt("Priority: 1 (high), 2 (medium), 3 (low)", { enum: [1, 2, 3] });
155
-
156
- function mcpSchema(props = {}, required = []) {
157
- return { type: "object", properties: { ...MCP_PROJECT_PROP, ...props }, required, additionalProperties: false };
158
- }
159
-
160
- const mcpCall = (name, data) => env.call(name, data);
161
-
162
- // Thrown by tool handlers for a refusal that should reach the client as a tool error, not a crash.
163
- class McpToolError extends Error {}
164
-
165
- // Copies only the listed keys that the caller actually supplied.
166
- function mcpPick(args, keys) {
167
- const out = {};
168
- for (const k of keys) if (args[k] !== undefined) out[k] = args[k];
169
- return out;
170
- }
171
-
172
- const mcpTools = [
173
- {
174
- name: "list_projects",
175
- description: "List the qa-tools projects this login can access.",
176
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
177
- noProject: true,
178
- run: async () => (await mcpCall("listProjects", {})).projects,
179
- },
180
- {
181
- // agents.brief-without-hook: the session brief for agents that have no session-start hook (Codex, Copilot)
182
- name: "get_brief",
183
- description: "The qa-tools brief for the start of a session: requirements in progress, items flagged for re-verification, the agenda, hot requests, this branch's requirements, and whether qatools-cli is out of date. Read it before you start working, unless you already got the brief at session start.",
184
- inputSchema: mcpSchema(),
185
- run: async (a) => {
186
- if (!local.brief) throw new McpToolError("The brief needs qatools mcp on your computer, in the repo");
187
- return local.brief({ projectId: a.projectId });
188
- },
189
- },
190
- {
191
- name: "get_agenda",
192
- description: "What to work on next in the project (same data as `qatools next`): open signals, requirements awaiting work, sessions awaiting analysis.",
193
- inputSchema: mcpSchema(),
194
- run: async (a) => {
195
- const agenda = await mcpCall("getProjectAgenda", { projectId: a.projectId });
196
- return warnings().length ? { warnings: warnings(), ...agenda } : agenda;
197
- },
198
- },
199
- {
200
- name: "get_app_context",
201
- description: "The project's App Context: purpose, tech stack, conventions, AI rules, design principles.",
202
- inputSchema: mcpSchema(),
203
- run: async (a) => mcpCall("getAppContext", { projectId: a.projectId }),
204
- },
205
- {
206
- name: "list_requirements",
207
- description: "List requirements. Superseded requirements are hidden unless includeSuperseded is true.",
208
- inputSchema: mcpSchema({
209
- status: mcpStrArray("Only these statuses", { type: "string", enum: MCP_REQ_STATUSES }),
210
- epicKey: mcpStr("Only requirements linked to this epic key"),
211
- sprintId: mcpStr("Only requirements planned in this sprint"),
212
- includeSuperseded: mcpBool("Include superseded requirements"),
213
- }),
214
- run: async (a) => {
215
- let reqs = (await mcpCall("listRequirements", { projectId: a.projectId, status: null })).requirements;
216
- if (!a.includeSuperseded) reqs = reqs.filter(r => r.status !== "superseded");
217
- if (a.status?.length) { const s = new Set(a.status); reqs = reqs.filter(r => s.has(r.status)); }
218
- if (a.epicKey) reqs = reqs.filter(r => r.epicKey === a.epicKey);
219
- if (a.sprintId) reqs = reqs.filter(r => r.sprintId === a.sprintId);
220
- return reqs;
221
- },
222
- },
223
- {
224
- name: "create_requirement",
225
- 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.",
226
- inputSchema: mcpSchema({
227
- key: mcpStr("Semantic key, e.g. auth.login"),
228
- title: mcpStr("Title"),
229
- description: mcpStr("Description"),
230
- acceptanceCriteria: mcpStr("Given/When/Then scenario(s), newline-separated"),
231
- negativeCriteria: mcpStr("Negative Given/When/Then scenario(s)"),
232
- type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }),
233
- priority: MCP_PRIORITY,
234
- category: mcpStr("Category"),
235
- epicKey: mcpStr("Epic key"),
236
- sprintId: mcpStr("Sprint ID to plan it in"),
237
- status: mcpStr("Initial status (default draft)", { enum: MCP_REQ_STATUSES }),
238
- force: mcpBool("Skip the semantic similarity check"),
239
- points: { type: "integer", enum: [1, 2, 3, 5, 8], description: "Size in points. Split anything bigger than 8. Not for non-functional requirements." },
240
- version: mcpInt("New version of an existing key (e.g. 2). Then set the old version to superseded with update_requirement."),
241
- }, ["key", "title"]),
242
- run: async (a) => mcpCall("createRequirement", { projectId: a.projectId, ...mcpPick(a, ["key", "title", "description", "acceptanceCriteria", "negativeCriteria", "type", "priority", "category", "epicKey", "sprintId", "status", "force", "version", "points"]) }),
243
- },
244
- {
245
- name: "update_requirement",
246
- 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.",
247
- inputSchema: mcpSchema({
248
- requirementId: mcpStr("Requirement document ID"),
249
- status: mcpStr("New status", { enum: MCP_REQ_STATUSES }),
250
- assignedTo: mcpStr("Assignee: a member's email, \"me\" (the Claude account), or empty string to clear. Setting status back to approved clears it."),
251
- evidence: mcpStr("Required for implemented/tested (min 10 chars): test output, file:line, expected vs actual, or 'no test applies because <reason>'"),
252
- epicKey: mcpStr("Epic key"),
253
- sprintId: mcpStr("Sprint ID (empty string clears)"),
254
- type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }),
255
- title: mcpStr("Title"),
256
- description: mcpStr("Description"),
257
- acceptanceCriteria: mcpStr("Acceptance criteria"),
258
- 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." },
259
- reason: mcpStr("Required for status rejected (min 5 chars): why it is rejected; kept with the requirement"),
260
- attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
261
- commit: mcpStr("Commit the evidence was verified on. Default: git HEAD of the server's working directory; empty string to leave it out"),
262
- }, ["requirementId"]),
263
- run: async (a) => {
264
- const updates = mcpPick(a, ["status", "assignedTo", "epicKey", "sprintId", "type", "title", "description", "acceptanceCriteria", "points"]);
265
- if (Object.keys(updates).length === 0) throw new McpToolError("No fields to update.");
266
- const evidenceById = a.evidence ? { [a.requirementId]: a.evidence } : {};
267
- if (requirementEvidenceViolations({ [a.requirementId]: updates }, evidenceById).length > 0) {
268
- throw new McpToolError(`Refusing status=${updates.status} without evidence (min 10 chars). Cite the verification, or use a status that does not claim done.`);
269
- }
270
- if (updates.status === "rejected" && String(a.reason || a.evidence || "").trim().length < 5) {
271
- throw new McpToolError("Refusing status=rejected without a reason (min 5 chars). Say why — it is kept with the requirement.");
272
- }
273
- const payload = { projectId: a.projectId, requirementId: a.requirementId, updates, ...(a.reason ? { reason: a.reason } : {}) };
274
- if (a.evidence) {
275
- payload.evidence = a.evidence;
276
- const commit = a.commit !== undefined ? a.commit : currentGitCommit();
277
- if (commit) payload.commit = commit;
278
- }
279
- if (a.attachments?.length) {
280
- if (!a.evidence) throw new McpToolError("attachments need evidence — images belong to an evidence entry");
281
- payload.attachments = await uploadEvidenceFiles(a.projectId, a.attachments);
282
- }
283
- await mcpCall("updateRequirement", payload);
284
- return { updated: a.requirementId, fields: Object.keys(updates) };
285
- },
286
- },
287
- {
288
- name: "list_epics",
289
- description: "List epics.",
290
- inputSchema: mcpSchema(),
291
- run: async (a) => (await mcpCall("listEpics", { projectId: a.projectId })).epics,
292
- },
293
- {
294
- name: "create_epic",
295
- description: "Create an epic. Check dependsOn against existing epics first (list_epics).",
296
- inputSchema: mcpSchema({
297
- key: mcpStr("Epic key, e.g. billing"),
298
- title: mcpStr("Title"),
299
- description: mcpStr("Description"),
300
- value: mcpStr("Why this capability exists"),
301
- scope: mcpStrArray("Scope items"),
302
- dependsOn: mcpStrArray("Epic keys this depends on"),
303
- priority: MCP_PRIORITY,
304
- }, ["key", "title"]),
305
- run: async (a) => mcpCall("createEpic", {
306
- projectId: a.projectId, key: a.key, title: a.title, description: a.description || "", value: a.value || "",
307
- scope: a.scope || [], dependsOn: a.dependsOn || [], priority: a.priority || 2,
308
- }),
309
- },
310
- {
311
- name: "update_epic",
312
- description: "Update an epic.",
313
- inputSchema: mcpSchema({
314
- epicId: mcpStr("Epic document ID"),
315
- status: mcpStr("Status", { enum: ["draft", "active", "completed"] }),
316
- title: mcpStr("Title"),
317
- description: mcpStr("Description"),
318
- value: mcpStr("Value statement"),
319
- scope: mcpStrArray("Scope items (replaces existing)"),
320
- priority: MCP_PRIORITY,
321
- }, ["epicId"]),
322
- run: async (a) => {
323
- const updates = mcpPick(a, ["status", "title", "description", "value", "scope", "priority"]);
324
- if (Object.keys(updates).length === 0) throw new McpToolError("No fields to update.");
325
- await mcpCall("updateEpic", { projectId: a.projectId, epicId: a.epicId, updates });
326
- return { updated: a.epicId, fields: Object.keys(updates) };
327
- },
328
- },
329
- {
330
- name: "list_sprints",
331
- description: "List sprints, ordered by release (end) date.",
332
- inputSchema: mcpSchema(),
333
- run: async (a) => (await mcpCall("listSprints", { projectId: a.projectId })).sprints,
334
- },
335
- {
336
- name: "sprint_velocity",
337
- 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).",
338
- inputSchema: mcpSchema(),
339
- run: async (a) => {
340
- const [{ sprints }, { requirements }] = await Promise.all([
341
- mcpCall("listSprints", { projectId: a.projectId }),
342
- mcpCall("listRequirements", { projectId: a.projectId, status: null }),
343
- ]);
344
- const DONE = new Set(["implemented", "tested"]);
345
- const active = requirements.filter(r => r.status !== "superseded" && r.status !== "rejected");
346
- const row = (s) => {
347
- const base = { id: s.id, name: s.name, status: s.status, startDate: s.startDate || "", releaseDate: s.releaseDate || "" };
348
- // sprint.completion-snapshot: completing moves the unfinished out, so only the stored numbers show what was planned.
349
- if (s.status === "completed" && s.completionStats) {
350
- const cs = s.completionStats;
351
- return { ...base, planned: cs.planned, done: cs.done, moved: cs.moved, fromSnapshot: true, completedAt: cs.completedAt || "",
352
- ...(typeof cs.donePoints === "number" ? { plannedPoints: cs.plannedPoints, donePoints: cs.donePoints } : {}) };
353
- }
354
- const reqs = active.filter(r => r.sprintId === s.id);
355
- return { ...base, planned: reqs.length, done: reqs.filter(r => DONE.has(r.status)).length,
356
- points: reqs.reduce((n, r) => n + (r.points || 0), 0), withoutPoints: reqs.filter(r => !r.points).length,
357
- ...(s.status === "completed" ? { fromSnapshot: false } : {}) };
358
- };
359
- const completed = sprints.filter(s => s.status === "completed").map(row);
360
- const withWork = completed.filter(s => s.planned > 0);
361
- const avg = withWork.length ? withWork.reduce((n, s) => n + s.done, 0) / withWork.length : null;
362
- const rate = withWork.length ? withWork.reduce((n, s) => n + s.done / s.planned, 0) / withWork.length : null;
363
- // Same rule as the web app (sprint-capacity.ts): last three completed sprints with points, else done requirements
364
- const recent = [...completed].filter(s => s.fromSnapshot).sort((x, y) => (y.completedAt || "").localeCompare(x.completedAt || ""));
365
- const pointed = recent.filter(s => typeof s.donePoints === "number").slice(0, 3);
366
- const basis = pointed.length ? pointed : recent.slice(0, 3);
367
- const capacity = basis.length
368
- ? { 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,
369
- ...(pointed.length ? {} : { note: "No completed sprint has points yet — capacity is counted in requirements" }) }
370
- : null;
371
- return {
372
- capacity,
373
- completedSprints: completed,
374
- averageDonePerCompletedSprint: avg === null ? null : Math.round(avg * 10) / 10,
375
- averageCompletionRate: rate === null ? null : Math.round(rate * 100) / 100,
376
- openSprints: sprints.filter(s => s.status !== "completed").map(row),
377
- unplannedApprovedRequirements: active.filter(r => r.status === "approved" && !r.sprintId).length,
378
- unplannedApprovedWithoutPoints: active.filter(r => r.status === "approved" && !r.sprintId && r.type !== "non-functional" && !r.points).length,
379
- };
380
- },
381
- },
382
- {
383
- name: "propose_sprint_plan",
384
- 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.",
385
- inputSchema: mcpSchema({
386
- goal: mcpStr("What the plan optimises for, e.g. 'Release 4.0 by Nov 18'"),
387
- summary: mcpStr("Short rationale: capacity used, dependency order, risks"),
388
- items: {
389
- type: "array",
390
- description: "One row per requirement",
391
- items: {
392
- type: "object",
393
- properties: {
394
- requirementId: mcpStr("Requirement document ID"),
395
- sprintId: mcpStr("Existing sprint ID (or use newSprintRef)"),
396
- newSprintRef: mcpStr("ref of a sprint in newSprints"),
397
- reason: mcpStr("Why this requirement goes in this sprint"),
398
- selfVerification: mcpStr("How you will verify it yourself, e.g. 'unit tests for X + API call Y' (sprint.ai-planning-self-verification)"),
399
- manualOnly: { type: "boolean", description: "true when you cannot verify it yourself at all — then testProtocols must have a test for it" },
400
- 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" },
401
- },
402
- required: ["requirementId", "reason"],
403
- additionalProperties: false,
404
- },
405
- },
406
- newSprints: {
407
- type: "array",
408
- description: "Sprints to create if the proposal is approved",
409
- items: {
410
- type: "object",
411
- properties: {
412
- ref: mcpStr("Your local reference, e.g. new-1"),
413
- name: mcpStr("Sprint name"),
414
- releaseDate: mcpStr("End date YYYY-MM-DD"),
415
- startDate: mcpStr("Start date YYYY-MM-DD"),
416
- },
417
- required: ["ref", "name", "releaseDate"],
418
- additionalProperties: false,
419
- },
420
- },
421
- omitted: {
422
- type: "array",
423
- description: "Requirements deliberately left out, with why",
424
- items: { type: "object", properties: { key: mcpStr("Requirement key"), reason: mcpStr("Why") }, required: ["key", "reason"], additionalProperties: false },
425
- },
426
- testProtocols: {
427
- type: "array",
428
- 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.",
429
- items: {
430
- type: "object",
431
- properties: {
432
- name: mcpStr("Protocol name, e.g. 'Release 4.1 — manual tests'"),
433
- sprintId: mcpStr("Existing sprint ID (or use newSprintRef)"),
434
- newSprintRef: mcpStr("ref of a sprint in newSprints"),
435
- sections: {
436
- type: "array",
437
- description: "Sections of manual tests",
438
- items: {
439
- type: "object",
440
- properties: {
441
- title: mcpStr("Section title"),
442
- tests: {
443
- type: "array",
444
- items: {
445
- type: "object",
446
- properties: {
447
- id: mcpStr("Test id, e.g. M-1"),
448
- name: mcpStr("What is tested"),
449
- steps: mcpStr("Steps a person follows"),
450
- expected: mcpStr("Expected result"),
451
- purpose: mcpStr("Why a person must perform this, e.g. 'real phone camera', 'SMS must actually arrive', 'visual check'"),
452
- requirementKey: mcpStr("Key of the requirement it verifies"),
453
- },
454
- required: ["name", "steps", "expected", "purpose", "requirementKey"],
455
- additionalProperties: false,
456
- },
457
- },
458
- },
459
- required: ["title", "tests"],
460
- additionalProperties: false,
461
- },
462
- },
463
- },
464
- required: ["name", "sections"],
465
- additionalProperties: false,
466
- },
467
- },
468
- swaps: {
469
- type: "array",
470
- 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.",
471
- items: {
472
- type: "object",
473
- properties: {
474
- sprintId: mcpStr("Sprint in progress to take the requirement into"),
475
- inRequirementId: mcpStr("Requirement taken in (approved or in progress)"),
476
- outRequirementIds: mcpStrArray("Requirements moved out (approved, in that sprint)"),
477
- reason: mcpStr("Why the change is worth it"),
478
- },
479
- required: ["sprintId", "inRequirementId", "outRequirementIds", "reason"],
480
- additionalProperties: false,
481
- },
482
- },
483
- }, []),
484
- run: async (a) => {
485
- if (!a.items?.length && !a.swaps?.length) throw new McpToolError("Give items, swaps or both.");
486
- const r = await mcpCall("createPlanProposal", { projectId: a.projectId, ...mcpPick(a, ["goal", "summary", "items", "newSprints", "omitted", "testProtocols", "swaps"]) });
487
- return { ...r, next: "Pending. A project member approves or rejects it in qa-tools under Sprints → Plan proposals." };
488
- },
489
- },
490
- {
491
- name: "list_plan_proposals",
492
- description: "List sprint-plan proposals and their status (pending/approved/rejected), with who decided and what was applied.",
493
- inputSchema: mcpSchema({ status: mcpStr("Filter by status", { enum: ["pending", "approved", "rejected"] }) }),
494
- run: async (a) => (await mcpCall("listPlanProposals", { projectId: a.projectId, status: a.status || null })).proposals,
495
- },
496
- {
497
- name: "list_compliance_due",
498
- 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.",
499
- inputSchema: mcpSchema({ sprintId: mcpStr("Sprint ID (default: the active sprint)") }),
500
- run: async (a) => mcpCall("listComplianceDue", { projectId: a.projectId, sprintId: a.sprintId || null }),
501
- },
502
- {
503
- name: "record_compliance_verification",
504
- 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.",
505
- inputSchema: mcpSchema({
506
- requirementKey: mcpStr("Continuous requirement key"),
507
- result: mcpStr("passed or failed", { enum: ["passed", "failed"] }),
508
- evidence: mcpStr("What was checked in the sprint's diff and what was found (file:line), min 10 chars"),
509
- sprintId: mcpStr("Sprint ID (default: the active sprint)"),
510
- commit: mcpStr("Commit checked"),
511
- attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
512
- }, ["requirementKey", "result", "evidence"]),
513
- run: async (a) => mcpCall("recordSprintVerification", { projectId: a.projectId, ...mcpPick(a, ["requirementKey", "result", "evidence", "sprintId", "commit"]), attachments: await uploadEvidenceFiles(a.projectId, a.attachments) }),
514
- },
515
- {
516
- name: "notify_member",
517
- description: "Email one project member, e.g. the person who made a wish that now waits for their yes (respects their opt-out — a mail they turned off is not sent). An addressed, deliberate message; plain text.",
518
- inputSchema: mcpSchema({
519
- to: mcpStr("The member's email"),
520
- subject: mcpStr("Email subject"),
521
- message: mcpStr("Plain-text body"),
522
- }, ["to", "subject", "message"]),
523
- run: async (a) => mcpCall("notifyUser", { projectId: a.projectId, to: a.to, subject: a.subject, message: a.message }),
524
- },
525
- {
526
- name: "notify_owner",
527
- description: "Email the project owner (respects their opt-out). Used for the summary at the end of a scheduled run — pass run so qa-tools knows the run happened. Plain text.",
528
- inputSchema: mcpSchema({
529
- subject: mcpStr("Email subject"),
530
- message: mcpStr("Plain-text body"),
531
- run: { type: "string", enum: ["loop", "daily"], description: "The scheduled run this summary ends (loop = loop_run, daily = daily_agenda_run); the session brief warns when one stops" },
532
- }, ["subject", "message"]),
533
- run: async (a) => mcpCall("notifyUser", { projectId: a.projectId, to: "owner", subject: a.subject, message: a.message, ...(a.run ? { run: a.run } : {}) }),
534
- },
535
- {
536
- name: "propose_app_context",
537
- description: "Propose the project's App Context (purpose, domainObjects, actors, stack, architecture, security, constraints, conventions, environments, integrations, verifyCommands — the check commands its CI runs), e.g. read from an existing repo. Only what the code shows. It counts only when a member approves it in the web app. Several proposals can be pending side by side (e.g. from parallel sessions); say in summary what yours covers.",
538
- inputSchema: mcpSchema({
539
- 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, verifyCommands: the commands the repo's CI runs, e.g. [\"npm test\", \"npm run build\"])" },
540
- summary: mcpStr("What the proposal is based on (files read)"),
541
- }, ["context"]),
542
- run: async (a) => mcpCall("proposeAppContext", { projectId: a.projectId, context: a.context, summary: a.summary || "" }),
543
- },
544
- {
545
- name: "reject_plan_proposal",
546
- 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.",
547
- inputSchema: mcpSchema({
548
- proposalId: mcpStr("Proposal ID (from list_plan_proposals)"),
549
- comment: mcpStr("Why it is rejected (min 5 chars) — required, kept with the proposal"),
550
- }, ["proposalId", "comment"]),
551
- run: async (a) => {
552
- await mcpCall("decidePlanProposal", { projectId: a.projectId, proposalId: a.proposalId, decision: "reject", comment: a.comment || "" });
553
- return { rejected: a.proposalId, planned: 0 };
554
- },
555
- },
556
- {
557
- name: "get_sprint_items",
558
- description: "Everything planned in a sprint: its requirements (the planning unit) and the backlog signals linked to it.",
559
- inputSchema: mcpSchema({ sprintId: mcpStr("Sprint ID") }, ["sprintId"]),
560
- run: async (a) => mcpCall("getSprintItems", { projectId: a.projectId, sprintId: a.sprintId }),
561
- },
562
- {
563
- name: "create_sprint",
564
- description: "Create a sprint. Status derives from dates (planning/active/overdue); without startDate it stays in planning.",
565
- inputSchema: mcpSchema({
566
- name: mcpStr("Sprint name"),
567
- releaseDate: mcpStr("End/release date, YYYY-MM-DD", { pattern: "^\\d{4}-\\d{2}-\\d{2}$" }),
568
- startDate: mcpStr("Start date, YYYY-MM-DD", { pattern: "^\\d{4}-\\d{2}-\\d{2}$" }),
569
- }, ["name", "releaseDate"]),
570
- run: async (a) => (await mcpCall("createSprint", { projectId: a.projectId, name: a.name, startDate: a.startDate || "", releaseDate: a.releaseDate })).sprint,
571
- },
572
- {
573
- name: "list_backlog",
574
- description: "List backlog signals (AVV/GAP/DEF/IMP).",
575
- inputSchema: mcpSchema({
576
- sprintId: mcpStr("Only items in this sprint"),
577
- status: mcpStrArray("Only these statuses", { type: "string", enum: MCP_BACKLOG_STATUSES }),
578
- assignedTo: mcpStr("Only items assigned to this email"),
579
- }),
580
- run: async (a) => mcpCall("listBacklog", { projectId: a.projectId, ...mcpPick(a, ["sprintId", "assignedTo"]), ...(a.status?.length ? { status: a.status } : {}) }),
581
- },
582
- {
583
- name: "create_backlog_item",
584
- description: "Report a backlog signal: bug (AVV), requirement_gap (GAP), technical_defect (DEF) or improvement (IMP). Not for planning work — plan with requirements.",
585
- inputSchema: mcpSchema({
586
- description: mcpStr("What was observed"),
587
- type: mcpStr("Signal type: bug = AVV (deviation from a requirement, default), requirement_gap = GAP, technical_defect = DEF, improvement = IMP", { enum: MCP_BACKLOG_TYPES }),
588
- priority: MCP_PRIORITY,
589
- assignedTo: mcpStr("Assignee email"),
590
- developer: mcpStr("Responsible developer email"),
591
- sprintId: mcpStr("Sprint ID"),
592
- parentId: mcpStr("Parent item label, e.g. AVV-5"),
593
- requirementKey: mcpStr("Requirement key it relates to"),
594
- tags: mcpStrArray("Tags"),
595
- mailNotify: mcpBool("Enable email notifications on this item (default off)"),
596
- securitySeverity: mcpStr("Mark as a security item, on any type", { enum: ["critical", "high", "medium", "low"] }),
597
- }, ["description"]),
598
- run: async (a) => {
599
- const r = await mcpCall("createBacklogItem", {
600
- projectId: a.projectId, type: a.type || "bug", description: a.description, priority: a.priority || 2,
601
- assignedTo: a.assignedTo || "", developer: a.developer || "", sprintId: a.sprintId || "", parentId: a.parentId || "",
602
- requirementKey: a.requirementKey || "", tags: (a.tags || []).map(t => t.trim().toLowerCase()), mailNotify: !!a.mailNotify,
603
- securitySeverity: a.securitySeverity || "",
604
- });
605
- return { ...r, label: backlogLabel(r.type, r.bugNumber) };
606
- },
607
- },
608
- {
609
- name: "update_backlog_item",
610
- 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.",
611
- inputSchema: mcpSchema({
612
- itemId: mcpStr("Backlog item document ID"),
613
- status: mcpStr("New status", { enum: MCP_BACKLOG_STATUSES }),
614
- evidence: mcpStr("Required for resolved (min 10 chars): test output, file:line, expected vs actual, or 'no test applies because <reason>'"),
615
- comment: mcpStr("Comment to add"),
616
- authorName: mcpStr("Comment author name (default Claude)"),
617
- assignedTo: mcpStr("Assignee email"),
618
- developer: mcpStr("Developer email"),
619
- sprintId: mcpStr("Sprint ID"),
620
- priority: MCP_PRIORITY,
621
- requirementKey: mcpStr("Requirement key"),
622
- tags: mcpStrArray("Tags (replaces existing)"),
623
- description: mcpStr("New description"),
624
- mailNotify: mcpBool("Item email notifications on/off"),
625
- securitySeverity: mcpStr("Security marking; none takes it away", { enum: ["critical", "high", "medium", "low", "none"] }),
626
- skipTestVerification: mcpBool("Allow resolved without ready_for_test — only when no test applies. Evidence is still required."),
627
- attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
628
- }, ["itemId"]),
629
- run: async (a) => {
630
- const u = mcpPick(a, ["status", "evidence", "assignedTo", "developer", "sprintId", "priority", "requirementKey", "description", "mailNotify"]);
631
- if (a.comment) { u.comment = a.comment; u.authorName = a.authorName || env.agentName || "Claude"; }
632
- if (a.tags) u.tags = a.tags.map(t => t.trim().toLowerCase());
633
- if (a.securitySeverity) u.securitySeverity = a.securitySeverity === "none" ? "" : a.securitySeverity;
634
- if (Object.keys(u).length === 0) throw new McpToolError("No fields to update.");
635
- 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).");
636
- const updates = { [a.itemId]: u };
637
- if (u.status === "resolved") {
638
- // Fail closed: unlike the interactive CLI, the MCP server refuses when the pre-check can't run.
639
- let v;
640
- try {
641
- v = await backlogResolveViolations(mcpCall, a.projectId, updates, { skipTestVerification: !!a.skipTestVerification });
642
- } catch (e) {
643
- throw new McpToolError(`Could not verify the backlog flow before resolving (${e.message}). Nothing was changed.`);
644
- }
645
- if (v.evidence.length) throw new McpToolError("Refusing status=resolved without evidence (min 10 chars). Cite the verification, or set ready_for_test instead.");
646
- 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.`);
647
- }
648
- if (a.attachments?.length) {
649
- if (!a.evidence) throw new McpToolError("attachments need evidence — images belong to an evidence entry");
650
- u.attachments = await uploadEvidenceFiles(a.projectId, a.attachments);
651
- }
652
- const r = await mcpCall("updateBacklogItems", { updates });
653
- // The backend skips items it can't find or the caller can't access, instead of throwing.
654
- 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.`);
655
- return { updated: a.itemId, fields: Object.keys(u) };
656
- },
657
- },
658
- {
659
- name: "requirement_impact",
660
- 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).",
661
- 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") }),
662
- run: async (a) => runImpact({ projectId: a.projectId || getCredentials()?.projectId, since: a.since, sprint: a.sprint, flag: !!a.flag, main: a.main }),
663
- },
664
- {
665
- name: "list_feature_requests",
666
- 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).",
667
- inputSchema: mcpSchema(),
668
- run: async (a) => (await mcpCall("listFeatureRequests", { projectId: a.projectId })).requests,
669
- },
670
- {
671
- name: "link_feature_request",
672
- 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.",
673
- inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)"), requirementKey: mcpStr("Requirement key, e.g. reports.export") }, ["id", "requirementKey"]),
674
- run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "link", requirementKey: a.requirementKey }),
675
- },
676
- {
677
- name: "unlink_feature_request",
678
- description: "Undo a link between a request from the app's users and a requirement.",
679
- inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)") }, ["id"]),
680
- run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "unlink" }),
681
- },
682
- {
683
- name: "requests_integration_prompt",
684
- 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.",
685
- inputSchema: mcpSchema(),
686
- run: async () => require("./context-sync").requestsIntegrationPrompt(getCredentials()?.projectName || ""),
687
- },
688
- {
689
- name: "new_app_questions",
690
- 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.",
691
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
692
- run: async () => mcpCall("getNewAppQuestions", {}),
693
- },
694
- {
695
- name: "create_project",
696
- description: "projects.claude-proposes-new-project: start a new qa-tools project. Creates nothing: it returns a link with the name and purpose filled in. Give the link to the user, who creates the project there as themselves. Never change ~/.qatools or log in as the user to do it.",
697
- inputSchema: { type: "object", properties: { name: mcpStr("The app's name"), description: mcpStr("One sentence: what it does") }, required: ["name"], additionalProperties: false },
698
- run: async (a) => {
699
- const name = String(a.name).trim().slice(0, 100);
700
- if (!name) throw new McpToolError("name required");
701
- const params = new URLSearchParams({ name, description: String(a.description || "").slice(0, 1000) });
702
- return {
703
- created: false,
704
- link: `https://qa-tools.com/new-project?${params}`,
705
- next: "Give the user this link. They create the project there, signed in as themselves, with Claude switched on. The page shows the project's ID, and for Claude Code the command that gives you your own login for the repo, which they run in their own terminal. In a chat, ask them for the ID.",
706
- };
707
- },
708
- },
709
- {
710
- name: "apply_new_app_answers",
711
- 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.",
712
- inputSchema: mcpSchema({
713
- answers: { type: "object", description: "The answers, keyed by question id", additionalProperties: true },
714
- overwrite: mcpBool("Replace fields that already have content — only after the user confirmed"),
715
- }, ["answers"]),
716
- run: async (a) => mcpCall("applyNewAppAnswers", { projectId: a.projectId || getCredentials()?.projectId, answers: a.answers, overwrite: !!a.overwrite }),
717
- },
718
- {
719
- name: "release_notes_prompt",
720
- 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.",
721
- inputSchema: mcpSchema({ sprintId: mcpStr("The release: sprint id or name (default: latest completed)") }),
722
- run: async (a) => (await mcpCall("getReleaseNotesPrompt", { projectId: a.projectId, sprintId: a.sprintId || "" })).prompt,
723
- },
724
- {
725
- name: "save_release_notes_draft",
726
- 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.",
727
- inputSchema: mcpSchema({ sprintId: mcpStr("The release: sprint id or name"), text: mcpStr("The notes: short points in the users' language") }, ["sprintId", "text"]),
728
- run: async (a) => mcpCall("saveReleaseNotesDraft", { projectId: a.projectId, sprintId: a.sprintId, text: a.text }),
729
- },
730
- {
731
- name: "infra_prompt",
732
- 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.",
733
- inputSchema: mcpSchema({ platform: mcpStr("azure, gcp, aws or firebase (default: from the App Context)", { enum: ["azure", "gcp", "aws", "firebase"] }) }),
734
- run: async (a) => (await mcpCall("getInfraPrompt", { projectId: a.projectId, platform: a.platform || "" })).prompt,
735
- },
736
- // ---- cli.mcp-parity: the CLI's project-data commands, through the same backend functions ----
737
- {
738
- name: "update_project",
739
- description: "Change the project's name or description (owner).",
740
- inputSchema: mcpSchema({ name: mcpStr("New name"), description: mcpStr("New description") }),
741
- run: async (a) => {
742
- const updates = mcpPick(a, ["name", "description"]);
743
- if (!Object.keys(updates).length) throw new McpToolError("Give name and/or description.");
744
- return mcpCall("updateProjectFields", { projectId: a.projectId, updates });
745
- },
746
- },
747
- {
748
- name: "add_member",
749
- description: "Add a member to the project by email; they get an invitation email. Owner only.",
750
- inputSchema: mcpSchema({ email: mcpStr("The member's email") }, ["email"]),
751
- run: async (a) => mcpCall("addProjectMember", { projectId: a.projectId, email: a.email }),
752
- },
753
- {
754
- name: "remove_member",
755
- description: "Remove a member from the project (the owner cannot be removed). Destructive: confirm with the user in this conversation before calling.",
756
- inputSchema: mcpSchema({ email: mcpStr("The member's email") }, ["email"]),
757
- run: async (a) => mcpCall("removeProjectMember", { projectId: a.projectId, email: a.email }),
758
- },
759
- {
760
- name: "delete_requirement",
761
- 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.",
762
- inputSchema: mcpSchema({ requirementId: mcpStr("Requirement document id"), force: mcpBool("Delete even though items or tests reference it — re-point them first") }, ["requirementId"]),
763
- run: async (a) => mcpCall("deleteRequirement", { projectId: a.projectId, requirementId: a.requirementId, force: !!a.force }),
764
- },
765
- {
766
- name: "delete_epic",
767
- description: "Delete an epic by key. Refused while requirements belong to it. Destructive: confirm with the user first.",
768
- inputSchema: mcpSchema({ epicKey: mcpStr("Epic key") }, ["epicKey"]),
769
- run: async (a) => {
770
- const epic = ((await mcpCall("listEpics", { projectId: a.projectId })).epics || []).find(e => e.key === a.epicKey);
771
- if (!epic) throw new McpToolError(`Epic '${a.epicKey}' not found.`);
772
- return mcpCall("deleteEpic", { projectId: a.projectId, epicId: epic.id });
773
- },
774
- },
775
- {
776
- name: "requirement_coverage",
777
- description: "Per requirement: its manual test cases and automated test runs, and which ones verify it.",
778
- inputSchema: mcpSchema(),
779
- run: async (a) => mcpCall("requirementCoverage", { projectId: a.projectId }),
780
- },
781
- {
782
- name: "list_requirement_keys",
783
- description: "Every requirement key in use in the project's test protocols and backlog, with where it is used.",
784
- inputSchema: mcpSchema(),
785
- run: async (a) => mcpCall("listRequirementKeys", { projectId: a.projectId }),
786
- },
787
- {
788
- name: "reject_template",
789
- description: "Reject a test protocol (version) with a reason; it can no longer be started as a session.",
790
- inputSchema: mcpSchema({ templateId: mcpStr("Test protocol id"), reason: mcpStr("Why — at least a few words") }, ["templateId", "reason"]),
791
- run: async (a) => mcpCall("rejectTemplate", { projectId: a.projectId, templateId: a.templateId, reason: a.reason }),
792
- },
793
- {
794
- name: "upload_test_report",
795
- 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.",
796
- inputSchema: mcpSchema({ file: mcpStr("Path to the results file"), format: mcpStr("junit or json (default: from the file extension)", { enum: ["junit", "json"] }) }, ["file"]),
797
- run: async (a) => {
798
- const filePath = path.resolve(a.file);
799
- if (!fs.existsSync(filePath)) throw new McpToolError(`File not found: ${filePath}`);
800
- const text = fs.readFileSync(filePath, "utf-8");
801
- const format = a.format || (/\.json$/i.test(filePath) ? "json" : "junit");
802
- const results = format === "json" ? parseTestJson(JSON.parse(text)) : parseJUnit(text);
803
- if (!results.length) throw new McpToolError("No test results found in the file.");
804
- return mcpCall("uploadTestRun", { projectId: a.projectId, run: ciRunMeta({}), results });
805
- },
806
- },
807
- {
808
- name: "find_duplicates",
809
- description: "Find backlog items that look like duplicates of each other (uses the project's Anthropic key on the server).",
810
- inputSchema: mcpSchema(),
811
- run: async (a) => mcpCall("findDuplicates", { projectId: a.projectId }),
812
- },
813
- {
814
- name: "import_security_scan",
815
- 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.",
816
- inputSchema: mcpSchema({ file: mcpStr("Path to the SARIF file"), source: mcpStr("Scanner name, e.g. codeql") }, ["file"]),
817
- run: async (a) => {
818
- const filePath = path.resolve(a.file);
819
- if (!fs.existsSync(filePath)) throw new McpToolError(`File not found: ${filePath}`);
820
- return mcpCall("importSecurityScan", { projectId: a.projectId, sarif: JSON.parse(fs.readFileSync(filePath, "utf-8")), source: a.source || "" });
821
- },
822
- },
823
- {
824
- name: "set_app_context",
825
- 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.",
826
- inputSchema: mcpSchema({ context: { type: "object", description: "The whole App Context", additionalProperties: true } }, ["context"]),
827
- run: async (a) => mcpCall("saveAppContext", { projectId: a.projectId, context: a.context }),
828
- },
829
- {
830
- name: "get_access_model",
831
- description: "The project's access model: roles and what each may do.",
832
- inputSchema: mcpSchema(),
833
- run: async (a) => mcpCall("getAccessModel", { projectId: a.projectId }),
834
- },
835
- {
836
- name: "set_access_model",
837
- 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.",
838
- inputSchema: mcpSchema({ model: { type: "object", description: "The whole access model", additionalProperties: true } }, ["model"]),
839
- run: async (a) => mcpCall("saveAccessModel", { projectId: a.projectId, model: a.model }),
840
- },
841
- {
842
- name: "decline_feature_request",
843
- 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.",
844
- inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)"), reason: mcpStr("Why — shown to the app's users") }, ["id", "reason"]),
845
- run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "decline", reason: a.reason }),
846
- },
847
- {
848
- name: "list_skill_library",
849
- description: "The shared skill library: skills that can be added to a project's App Context.",
850
- inputSchema: mcpSchema(),
851
- run: async () => mcpCall("listSkillLibrary", {}),
852
- },
853
- {
854
- name: "get_library_skill",
855
- description: "Read one skill from the shared skill library.",
856
- inputSchema: mcpSchema({ name: mcpStr("Skill name") }, ["name"]),
857
- run: async (a) => mcpCall("getLibrarySkill", { name: a.name }),
858
- },
859
- {
860
- name: "save_library_skill",
861
- description: "Add or update a skill in the shared skill library (superadmin).",
862
- 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"]),
863
- run: async (a) => mcpCall("saveLibrarySkill", { name: a.name, title: a.title, description: a.description || "", content: a.content }),
864
- },
865
- {
866
- name: "delete_library_skill",
867
- description: "Remove a skill from the shared skill library (superadmin). Destructive: confirm with the user first.",
868
- inputSchema: mcpSchema({ name: mcpStr("Skill name") }, ["name"]),
869
- run: async (a) => mcpCall("deleteLibrarySkill", { name: a.name }),
870
- },
871
- {
872
- name: "baseline_prompt",
873
- 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.",
874
- inputSchema: mcpSchema(),
875
- run: async (a) => (await mcpCall("getBaselinePrompt", { projectId: a.projectId })).prompt,
876
- },
877
- {
878
- name: "upload_baseline",
879
- 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.",
880
- inputSchema: mcpSchema({
881
- requirements: {
882
- type: "array", description: "Reconstructed requirements (at most 100)",
883
- items: {
884
- type: "object",
885
- properties: {
886
- key: mcpStr("Semantic key, e.g. keys.search"), title: mcpStr("Title"), description: mcpStr("Description"),
887
- acceptanceCriteria: mcpStr("Given/When/Then scenario(s), newline-separated"), negativeCriteria: mcpStr("Negative scenario(s)"),
888
- type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }), epicKey: mcpStr("Epic key"),
889
- files: mcpStrArray("Files where it is built, e.g. src/app/x.ts:40-88"), commits: mcpStrArray("Commits where it was built"),
890
- },
891
- required: ["key", "title", "acceptanceCriteria"],
892
- },
893
- },
894
- }, ["requirements"]),
895
- run: async (a) => mcpCall("uploadBaselineRequirements", { projectId: a.projectId, requirements: a.requirements }),
896
- },
897
- {
898
- name: "update_library_requirement",
899
- description: "Change an entry in the account's requirement library (owner only). The new text reaches every requirement in every project that inherits it — confirm with the user first.",
900
- inputSchema: mcpSchema({
901
- key: mcpStr("Library key"),
902
- title: mcpStr("New title"), description: mcpStr("New description"),
903
- acceptanceCriteria: mcpStr("New acceptance criteria"), negativeCriteria: mcpStr("New negative criteria"), category: mcpStr("New category"),
904
- }, ["key"]),
905
- run: async (a) => {
906
- const updates = mcpPick(a, ["title", "description", "acceptanceCriteria", "negativeCriteria", "category"]);
907
- if (!Object.keys(updates).length) throw new McpToolError("Give at least one field to change");
908
- const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
909
- const entry = entries.find(e => e.key === a.key);
910
- if (!entry) throw new McpToolError(`Not in the library: ${a.key}`);
911
- return mcpCall("updateLibraryRequirement", { projectId: a.projectId, libraryId: entry.id, updates });
912
- },
913
- },
914
- {
915
- name: "list_audit_log",
916
- description: "The project's security log (security.audit-log): who changed keys, members and other security settings, and when. Owner or superadmin only.",
917
- inputSchema: mcpSchema({ limit: mcpInt("Number of entries (default 50)") }),
918
- run: async (a) => (await mcpCall("listAuditLog", { projectId: a.projectId, limit: a.limit || 50 })).entries,
919
- },
920
- {
921
- name: "evidence_backfill",
922
- description: "Verified requirements without an evidence commit: find the newest commit on main naming the key (runs in the repo on the user's computer). apply: true records them as commit links — not new verifications.",
923
- inputSchema: mcpSchema({ apply: mcpBool("Record the commits in qa-tools (default: only show them)"), main: mcpStr("The main branch (default: origin/HEAD, else origin/main, origin/master, main, master)") }),
924
- run: async (a) => runEvidenceBackfill({ projectId: a.projectId, apply: !!a.apply, main: a.main }),
925
- },
926
- {
927
- name: "list_requirement_library",
928
- 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.",
929
- inputSchema: mcpSchema({ category: mcpStr("Only this category") }),
930
- run: async (a) => {
931
- const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
932
- return a.category ? entries.filter(e => (e.category || "").toLowerCase() === a.category.toLowerCase()) : entries;
933
- },
934
- },
935
- {
936
- name: "share_requirement_to_library",
937
- 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.",
938
- inputSchema: mcpSchema({
939
- requirementId: mcpStr("Requirement document ID"),
940
- 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 },
941
- applicability: mcpStr("What is specific to this project, e.g. 'Applies to Twilio, SendGrid, Auth0'"),
942
- }, ["requirementId"]),
943
- run: async (a) => mcpCall("shareRequirementToLibrary", { projectId: a.projectId, ...mcpPick(a, ["requirementId", "text", "applicability"]) }),
944
- },
945
- {
946
- name: "inherit_library_requirements",
947
- 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.",
948
- inputSchema: mcpSchema({ keys: mcpStrArray("Library keys"), category: mcpStr("Every entry in this category"), applicability: mcpStr("What they apply to in this project") }),
949
- run: async (a) => {
950
- let libraryIds;
951
- if (a.keys?.length) {
952
- const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
953
- libraryIds = entries.filter(e => a.keys.includes(e.key)).map(e => e.id);
954
- }
955
- return mcpCall("inheritLibraryRequirements", { projectId: a.projectId, libraryIds, category: a.category, applicability: a.applicability });
956
- },
957
- },
958
- {
959
- name: "create_test_protocol",
960
- 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.",
961
- inputSchema: mcpSchema({
962
- sprintId: mcpStr("Sprint ID the protocol belongs to"),
963
- name: mcpStr("Protocol name, e.g. 'Release 4.1 — manual tests'"),
964
- sections: {
965
- type: "array",
966
- description: "Sections of manual tests",
967
- items: {
968
- type: "object",
969
- properties: {
970
- title: mcpStr("Section title"),
971
- tests: {
972
- type: "array",
973
- items: {
974
- type: "object",
975
- properties: {
976
- id: mcpStr("Test id, e.g. M-1"),
977
- name: mcpStr("What is tested"),
978
- steps: mcpStr("Steps a person follows"),
979
- expected: mcpStr("Expected result"),
980
- purpose: mcpStr("Why a person must perform this, e.g. 'real phone camera', 'SMS must actually arrive', 'visual check'"),
981
- requirementKey: mcpStr("Key of the requirement it verifies"),
982
- },
983
- required: ["name", "steps", "expected", "purpose", "requirementKey"],
984
- additionalProperties: false,
985
- },
986
- },
987
- },
988
- required: ["title", "tests"],
989
- additionalProperties: false,
990
- },
991
- },
992
- 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"),
993
- }, ["sprintId", "name", "sections"]),
994
- run: async (a) => {
995
- for (const sec of a.sections) for (const t of sec.tests || []) {
996
- if (!String(t.purpose || "").trim()) throw new McpToolError(`Test "${t.name}" needs a purpose saying why a person must perform it`);
997
- }
998
- const r = await mcpCall("uploadTemplate", { projectId: a.projectId, sprintId: a.sprintId, name: a.name, sections: a.sections, ...(a.replaces ? { replaces: a.replaces } : {}) });
999
- return { ...r, next: "Pending review. A project member approves it in qa-tools under Test protocols." };
1000
- },
1001
- },
1002
- {
1003
- name: "list_templates",
1004
- description: "List test templates (test protocols) and their review status.",
1005
- inputSchema: mcpSchema({ status: mcpStr("Filter by review status", { enum: ["draft", "pending_review", "approved", "rejected"] }) }),
1006
- run: async (a) => (await mcpCall("listTemplates", { projectId: a.projectId, status: a.status || null })).templates,
1007
- },
1008
- {
1009
- name: "pending_sessions",
1010
- description: "Test sessions awaiting Claude analysis.",
1011
- inputSchema: mcpSchema(),
1012
- run: async (a) => (await mcpCall("pendingSessions", { projectId: a.projectId })).pending,
1013
- },
1014
- {
1015
- name: "read_session",
1016
- description: "Read a test session with its template and linked backlog details.",
1017
- inputSchema: { type: "object", properties: { sessionId: mcpStr("Test session ID") }, required: ["sessionId"], additionalProperties: false },
1018
- noProject: true,
1019
- run: async (a) => mcpCall("readSession", { sessionId: a.sessionId }),
1020
- },
1021
- {
1022
- name: "upload_analysis",
1023
- description: "Upload an analysis of a test session (same format as `qatools upload-analysis`): analysis[] with verdicts, and optional backlogUpdates keyed by item ID.",
1024
- inputSchema: {
1025
- type: "object",
1026
- properties: {
1027
- sessionId: mcpStr("Test session ID"),
1028
- analysis: { type: "array", items: { type: "object" }, description: "Analysis entries" },
1029
- 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." },
1030
- },
1031
- required: ["sessionId", "analysis"],
1032
- additionalProperties: false,
1033
- },
1034
- noProject: true,
1035
- run: async (a) => mcpCall("uploadAnalysis", { sessionId: a.sessionId, analysis: a.analysis, backlogUpdates: a.backlogUpdates || {} }),
1036
- },
1037
- ];
1038
-
1039
-
1040
- // Prompts (sprint.ai-planning): ready-made workflows the user picks in the client, e.g. the "+" menu in Claude Desktop.
1041
- const mcpPrompts = [
1042
- {
1043
- name: "plan_sprints",
1044
- description: "Plan approved requirements into sprints: Claude proposes, you approve, then it applies.",
1045
- arguments: [
1046
- { name: "projectId", description: "Project ID (default: configured project)", required: false },
1047
- { name: "goal", description: "What to optimise for, e.g. 'release 4.0 by Nov 18' or 'auth first'", required: false },
1048
- ],
1049
- text: (a) => `Plan sprints in qa-tools${a.projectId ? ` for project ${a.projectId}` : ""}.${a.goal ? ` Goal: ${a.goal}.` : ""}
1050
-
1051
- Follow these steps in order:
1052
-
1053
- 1. Gather facts, don't guess: list_sprints, sprint_velocity, list_epics, list_requirements (status approved, plus anything already planned in open sprints).
1054
- 2. Draft a plan. Only requirements are planned — never create backlog items as tasks. Rules:
1055
- - 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).
1056
- - An epic's requirements never go into an earlier sprint than the requirements of the epics it dependsOn.
1057
- - Order by priority (1 first), then epic priority.
1058
- - 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.
1059
- - 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.
1060
- - 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.
1061
- - 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.
1062
- - If the requirements don't fit in the existing sprints, propose new sprints (name + end date) — don't create them yet.
1063
- - 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.
1064
- 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.
1065
- 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.
1066
- - 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.
1067
- 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.
1068
- 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.
1069
- 7. End with get_sprint_items for each affected sprint so the user can see the result.`,
1070
- },
1071
- {
1072
- name: "daily_agenda_run",
1073
- description: "Unattended run (automation.daily-agenda-run): work through the project agenda, propose — never apply — and email the owner a summary.",
1074
- arguments: [{ name: "projectId", description: "Project ID (default: configured project)", required: false }],
1075
- text: (a) => dailyAgendaRunPrompt(a.projectId),
1076
- },
1077
- {
1078
- name: "loop_run",
1079
- description: "Unattended run of the self-playing loop (loop.claude-builds-approved), in the app's repo: answer wishes, draft requirements, build one approved wish on a branch, deploy to the test environment only, never to production.",
1080
- arguments: [{ name: "projectId", description: "Project ID (default: configured project)", required: false }],
1081
- text: (a) => loopRunPrompt(a.projectId),
1082
- },
1083
- {
1084
- name: "new_app",
1085
- 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.",
1086
- arguments: [{ name: "name", description: "The app's name, if already known", required: false }],
1087
- text: (a) => `Help the user start a new app in qa-tools${a.name ? ` called "${a.name}"` : ""}.
1088
-
1089
- 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.
1090
- 2. When you have the answers and a name, call create_project (name, description = the purpose). It creates nothing and returns a link: give it to the user. They create the project there, signed in as themselves, and the page shows the project's ID. In Claude Code the page also shows the command qatools init --agent claude --project <id>, which they run in their own terminal, in the repo; then they restart Claude Code and resume this conversation. In a chat, ask them for the ID and continue. Never change ~/.qatools, never log in as the user and never use their login to create the project, even if a tool or command refuses you.
1091
- 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.
1092
- 4. Propose the first epics from the App Context.`,
1093
- },
1094
- ];
1095
-
1096
- function mcpValidateArgs(tool, args) {
1097
- for (const k of tool.inputSchema.required || []) {
1098
- if (args[k] === undefined || args[k] === null || args[k] === "") throw new McpToolError(`Missing required argument: ${k}`);
1099
- }
1100
- const known = tool.inputSchema.properties;
1101
- const unknown = Object.keys(args).filter(k => !(k in known));
1102
- if (unknown.length) throw new McpToolError(`Unknown argument(s): ${unknown.join(", ")}`);
1103
- }
1104
-
1105
- async function mcpHandle(msg, defaultProjectId) {
1106
- const { method, params } = msg;
1107
- if (method === "initialize") {
1108
- const requested = params?.protocolVersion;
1109
- return {
1110
- protocolVersion: MCP_PROTOCOL_VERSIONS.includes(requested) ? requested : MCP_PROTOCOL_VERSIONS[0],
1111
- capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } },
1112
- serverInfo: { name: "qatools", version: env.version || "" },
1113
- instructions: instructions + (warnings().length ? "\n- OUT OF DATE: " + warnings().join(" ") + " Upgrade yourself (npm install -g qatools-cli@latest, then qatools init in the repo, commit the .claude changes) and tell the user in one line — unless this is an unattended run, which never upgrades mid-run." : ""),
1114
- };
1115
- }
1116
- if (method === "ping") return {};
1117
- if (method === "tools/list") {
1118
- return { tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) };
1119
- }
1120
- if (method === "prompts/list") {
1121
- return { prompts: mcpPrompts.map(({ name, description, arguments: args }) => ({ name, description, arguments: args })) };
1122
- }
1123
- if (method === "prompts/get") {
1124
- const prompt = mcpPrompts.find(p => p.name === params?.name);
1125
- if (!prompt) throw Object.assign(new Error(`Unknown prompt: ${params?.name}`), { code: -32602 });
1126
- const args = params.arguments || {};
1127
- return { description: prompt.description, messages: [{ role: "user", content: { type: "text", text: prompt.text(args) } }] };
1128
- }
1129
- if (method === "tools/call") {
1130
- const tool = tools.find(t => t.name === params?.name);
1131
- if (!tool) throw Object.assign(new Error(`Unknown tool: ${params?.name}`), { code: -32602 });
1132
- const args = { ...(params.arguments || {}) };
1133
- try {
1134
- mcpValidateArgs(tool, args);
1135
- if (!tool.noProject) {
1136
- args.projectId = args.projectId || defaultProjectId;
1137
- if (!args.projectId) throw new McpToolError(env.noDefaultProject ? "Pass projectId — list_projects shows the projects you are a member of" : "No project configured. Pass projectId, or run: qatools setup");
1138
- }
1139
- const data = await tool.run(args);
1140
- return { content: [{ type: "text", text: typeof data === "string" ? data : JSON.stringify(data ?? null, null, 2) }] };
1141
- } catch (e) {
1142
- // Tool failures (refusals, backend permission errors) go back as tool results the model can read.
1143
- return { content: [{ type: "text", text: e.message || String(e) }], isError: true };
1144
- }
1145
- }
1146
- throw Object.assign(new Error(`Method not found: ${method}`), { code: -32601 });
1147
- }
1148
-
1149
-
1150
- tools = env.local ? mcpTools : mcpTools.filter(t => !MCP_LOCAL_ONLY.has(t.name));
1151
- // agents.brief-without-hook: an agent without Claude Code's session hook reads the brief first
1152
- instructions = MCP_INSTRUCTIONS + (local.brief ? "\n- Before you start working in a session, call get_brief (unless the qa-tools brief was already shown at session start): what is in progress, what waits, and whether qa-tools is out of date." : "") + (env.noDefaultProject ? "\n- This is the qa-tools connector in Claude: there is no configured project. Call list_projects first and pass projectId to every tool; when it is unclear which project the person means, ask them." : "");
1153
- return { tools, prompts: mcpPrompts, handle: (msg, defaultProjectId) => mcpHandle(msg, defaultProjectId), instructions };
1154
- }
1155
-
1156
- module.exports = { createMcp, dailyAgendaRunPrompt, loopRunPrompt, MCP_LOCAL_ONLY, backlogLabel, requirementEvidenceViolations, backlogResolveViolations };
1
+ // cli.mcp-server / loop.chat-connector: the qa-tools MCP tools, prompts and request handler, shared by
2
+ // `qatools mcp` (stdio, on the user's computer) and the connector on qa-tools' server (Claude adds it with one click).
3
+ // Every tool calls the same backend function as its CLI counterpart, so the same checks apply everywhere.
4
+ // createMcp(env):
5
+ // env.call(name, data) → calls a backend function as the signed-in person (callable over HTTPS in the CLI,
6
+ // in-process on the server)
7
+ // env.local → helpers that need the user's computer (git, local files); null on the server, where
8
+ // the tools that need them are left out and attachments are refused
9
+ // env.warnings() → out-of-date warnings to pass on to the model; env.version → shown as serverInfo.version
10
+ // env.noDefaultProject → true on the server: there is no configured project, so tools need projectId
11
+ // functions/mcp-core.js is a copy made by scripts/sync-mcp-core.js; a test fails when the two differ.
12
+
13
+ // Backlog labels as the web app shows them (project.ts typePrefix): bug → AVV-12 etc.
14
+ const BACKLOG_PREFIX = { bug: "AVV", improvement: "IMP", requirement_gap: "GAP", technical_defect: "DEF" };
15
+ const backlogLabel = (type, n) => `${BACKLOG_PREFIX[type] || "AVV"}-${n}`;
16
+
17
+ // Status guards shared by the CLI commands and the MCP server (cli.mcp-access-parity) —
18
+ // one implementation, so an MCP tool can never be looser than its CLI counterpart.
19
+ const REQUIREMENT_STATUSES_REQUIRING_EVIDENCE = new Set(["implemented", "tested"]);
20
+
21
+ // updates: { requirementId: { status, ... } }, evidenceById: { requirementId: text }
22
+ function requirementEvidenceViolations(updates, evidenceById) {
23
+ const violations = [];
24
+ for (const [id, u] of Object.entries(updates)) {
25
+ if (u.status && REQUIREMENT_STATUSES_REQUIRING_EVIDENCE.has(u.status)) {
26
+ const ev = (evidenceById[id] || "").trim();
27
+ if (ev.length < 10) violations.push({ id, status: u.status });
28
+ }
29
+ }
30
+ return violations;
31
+ }
32
+
33
+ // Backlog: status=resolved needs evidence (min 10 chars) and, for AVV/DEF/IMP, a prior ready_for_test.
34
+ // GAP (requirement_gap) is exempt from both. Throws if the backlog can't be listed.
35
+ async function backlogResolveViolations(call, projectId, updates, { skipTestVerification = false } = {}) {
36
+ const out = { evidence: [], flow: [] };
37
+ const resolving = Object.entries(updates).filter(([, u]) => u.status === "resolved");
38
+ if (resolving.length === 0) return out;
39
+ const listResult = await call("listBacklog", { projectId });
40
+ const itemById = {};
41
+ for (const it of listResult.items || []) itemById[it.id] = it;
42
+ for (const [id, u] of resolving) {
43
+ const item = itemById[id];
44
+ if (!item) continue;
45
+ if (item.type === "requirement_gap") continue;
46
+ const v = { id, type: item.type, currentStatus: item.status, description: (item.description || "").substring(0, 80) };
47
+ if ((u.evidence || "").trim().length < 10) out.evidence.push(v);
48
+ if (!skipTestVerification && item.status !== "ready_for_test") out.flow.push(v);
49
+ }
50
+ return out;
51
+ }
52
+
53
+ const MCP_LOCAL_ONLY = new Set(["requirement_impact", "upload_test_report", "import_security_scan", "evidence_backfill", "get_brief"]);
54
+
55
+ // automation.daily-agenda-run: the unattended procedure. Shared by the MCP prompt daily_agenda_run and
56
+ // `qatools agenda-run-prompt` (for `claude -p`), so both always say the same thing.
57
+ function dailyAgendaRunPrompt(projectId) {
58
+ const a = { projectId };
59
+ 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.
60
+
61
+ Work through these steps, then stop:
62
+
63
+ 1. get_agenda. This is your task list.
64
+ 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.
65
+ 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.
66
+ 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.
67
+ 5. Finish with notify_owner with run: "daily" (or qatools notify --to <owner> --run daily) — it also tells qa-tools the run happened. Subject: "qa-tools daily run: <project> — <n> to review". Body, plain text, short:
68
+ - what you analysed and which signals you created (labels),
69
+ - the plan proposal you saved (or why none),
70
+ - anything that was refused or that needs a human decision,
71
+ - where to look: qa-tools → Sprints → Plan proposals, Backlog.
72
+ If there was nothing to do, still send a one-line summary saying so.`;
73
+ }
74
+
75
+ // loop.claude-builds-approved (epic LOOP): the unattended run of the self-playing loop, in the app's repo — the
76
+ // people who made the wishes only work in qa-tools. Shared by `qatools loop-run-prompt` (for claude -p) and the
77
+ // MCP prompt loop_run, so both always say the same thing.
78
+ function loopRunPrompt(projectId) {
79
+ return `You are running UNATTENDED in this app's git repository, as the developer of the qa-tools project${projectId ? ` ${projectId}` : ""}. Nobody is at the keyboard. The people who made the wishes work only in qa-tools: everything you say to them goes into the wish (the backlog item) as a comment, in their language, in plain words — no code, file names or technical terms.
80
+
81
+ Hard rules — never break them:
82
+ - Use this repo's qa-tools key (QATOOLS_API_KEY, or the key file the repo documents) and pass the project; never run qatools setup or qatools login — they change the computer-wide default that other projects use. If an MCP tool refuses with "API key is not valid for this project", the MCP server runs on another project's login: do the same through the CLI with this repo's key (QATOOLS_API_KEY=<key> qatools …), e.g. qatools notify instead of notify_owner or notify_member.
83
+ - Never deploy to production, never merge into the main branch, never push to it. Production is a person's decision.
84
+ - Never approve a requirement, and never set a wish to resolved. You draft; a person approves and confirms.
85
+ - At most ONE wish is built per run. When a test keeps failing or something is unclear, stop and say so in the wish.
86
+ - Never try the same build a third time on your own: after two failed attempts the wish goes on hold for a person (step 2).
87
+ - Nothing is done without evidence: implemented needs test output or file:line in evidence.
88
+
89
+ Steps, in order:
90
+
91
+ 1. Wishes to answer: list_backlog (statuses open, in_progress, on_hold). A wish is an item written by a person (not by Claude). Read its comments. Answer when it has no comment from you yet, or when the person wrote after your last comment. A wish on hold: answer only when the person wrote after your last comment, and then set it back to in_progress (update_backlog_item) — the person has looked at it, so its attempts count from zero again. Otherwise leave it on hold:
92
+ - Something important unclear: ask ONE concrete question with 2–4 short choices (update_backlog_item comment).
93
+ - Clear: write "Så här har jag förstått dig:" / "This is how I understood you:" and in a few plain sentences what will be built, ending with "Svara ja om det stämmer, annars vad som ska ändras." / "Answer yes if that is right, otherwise what to change."
94
+ - When you write your understanding, also write the requirement as a DRAFT (create_requirement status draft, Given/When/Then in the wish's language, never mixing languages) and link the wish to it (update_backlog_item requirementKey). The person approves it in the wish with "Ja, det stämmer" / "Yes, that is right" — that sets the requirement approved. Never approve it yourself, and do not build it before it is approved. Tell the person who made the wish ONCE that it waits for their yes (notify_member, or qatools notify --to <them>; plain words, the wish's label; it respects their opt-out) — not again on later runs.
95
+ A wish that comes back after it was built (the person tried it and wrote "Nej, det är inte vad jag menade: …" / "No, that is not what I meant: …"): its linked requirement is a draft again. Answer the same way, and change that draft with update_requirement (title, description, acceptance criteria) to what you now understand — do not create a new requirement. The person approves it again in the wish.
96
+ At most 6 answers from you per wish; after that, say a person needs to look at it.
97
+
98
+ 2. Build one approved wish: list_requirements status approved; take the first that a wish links to (its requirementKey), whose wish is not on hold, and that is not started. Then:
99
+ - update_requirement status in_progress, assignedTo "me"; comment in the wish that you have started.
100
+ - git switch -c loop/<requirement key> from the main branch (git pull first); if the branch exists (the wish came back after a "no"), switch to it and merge the main branch into it. Implement it the way the repo already works (read CLAUDE.md and the code around it). Add or extend automated tests for its acceptance criteria.
101
+ - Verify with the project's own check commands: get_app_context verifyCommands (CLAUDE.md lists them too). Run every one, in a mode that ends by itself (no watch mode: e.g. --watch=false, CI=true). If none are set, run the repo's tests and build the same way, and say in the summary that the project has no check commands. If one fails and you cannot fix it: commit the work in progress on the branch, push the branch, set the requirement back to approved. Then count your comments in the wish that start with "Jag kom inte hela vägen" / "I could not finish it" and were written after the person's last comment:
102
+ - none: comment "Jag kom inte hela vägen (försök 1 av 2): <what stops you, in plain words, including which check failed>" / "I could not finish it (attempt 1 of 2): …". The next run tries once more.
103
+ - one or more: update_backlog_item status on_hold with the comment "Jag kom inte hela vägen (försök 2 av 2): <what was tried and what failed, in plain words>. En person behöver titta på det innan jag försöker igen." / "I could not finish it (attempt 2 of 2): … A person needs to look at it before I try again." Later runs skip it until the person writes in the wish.
104
+ Stop.
105
+ - When everything passes: commit (the message names the requirement key), push the branch, open a pull request if gh is available.
106
+ - Test environment: get_app_context. If its environments list one named test (or Test, staging), deploy the branch there with the repo's own documented test deploy, and check that the change works there. If there is none, do NOT deploy.
107
+ - update_requirement status implemented with evidence: each check command you ran and its result (numbers), the branch and commit, and the test address if deployed.
108
+ - update_backlog_item status ready_for_test with a comment in plain words: what was built, and either "Prova här: <test address>" / "Try it here: <test address>", or that it is built and tested on a branch and waits for a person to put it on a test environment. The person who made the wish answers in qa-tools "Ja, det är vad jag menade" / "Yes, that is what I meant" (that sets the requirement tested and the wish done) or says what is wrong — never answer for them.
109
+
110
+ 3. Finish with notify_owner with run: "loop" (or qatools notify --to <owner> --run loop) — always, also when there was nothing to do: it tells qa-tools the run happened. Subject: "qa-tools loop: <project> — <n> answered, <built or nothing built>". Body, plain text, short: which wishes you answered, which requirement drafts wait for approval, what you built (branch, test address) or why nothing, the wishes you put on hold after two failed attempts, anything that needs a person.`;
111
+ }
112
+
113
+
114
+ function createMcp(env) {
115
+ let tools, instructions; // set below, once the tool table exists
116
+ const warnings = () => (env.warnings ? env.warnings() : []);
117
+ const local = env.local || {};
118
+ const fs = local.fs, path = local.path;
119
+ const currentGitCommit = local.currentGitCommit || (() => null);
120
+ const getCredentials = local.getCredentials || (() => null);
121
+ const runImpact = local.runImpact, runEvidenceBackfill = local.runEvidenceBackfill, parseJUnit = local.parseJUnit, parseTestJson = local.parseTestJson, ciRunMeta = local.ciRunMeta;
122
+ const uploadEvidenceFiles = local.uploadEvidenceFiles || (async (projectId, files) => {
123
+ if (files && files.length) throw new McpToolError("Attachments are local files and cannot be sent through the qa-tools connector — use qatools mcp on your computer, or attach them in the web app");
124
+ return undefined;
125
+ });
126
+
127
+ // Local Model Context Protocol server over stdio: newline-delimited JSON-RPC 2.0 on stdin/stdout.
128
+ // Every tool calls the same Cloud Functions callable as its CLI counterpart — no direct Firestore
129
+ // access — and write tools reuse the shared status guards above (cli.mcp-access-parity).
130
+ // Deletes are deliberately not exposed: they stay behind the CLI/UI confirmation paths.
131
+
132
+ const MCP_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
133
+
134
+ const MCP_INSTRUCTIONS = `qa-tools: requirements-driven QA. Rules that apply to every tool:
135
+ - Build from requirements. Planning is Epics → Requirements → Sprints (requirement.sprintId).
136
+ - The backlog is signals (bug=AVV, requirement_gap=GAP, technical_defect=DEF, improvement=IMP), not a task list.
137
+ - 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.
138
+ - Requirement status implemented/tested needs evidence: test output, file:line, expected vs actual, or "no test applies because <reason>".
139
+ - Before implemented or ready_for_test, run the project's check commands (get_app_context verifyCommands) and see them pass; the evidence names each command and its result.
140
+ - 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.
141
+ - 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.
142
+ - 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.
143
+ - Approving (approvals.in-conversation): when the person tells you they approve a requirement, a reconstructed requirement, a sprint-plan proposal or an App Context proposal, record it with onBehalfOf (their email) and quote (their exact words) — never on your own initiative, never for someone who did not say it. Whether that is allowed, and whether an agent may approve by itself (with reason), is the project's "Who approves" setting (the session brief says which); App Context changes always need a person.
144
+ - 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.
145
+ - Every tool takes an optional projectId; without it the configured project (qatools setup) is used.`;
146
+
147
+ const mcpStr = (description, extra = {}) => ({ type: "string", description, ...extra });
148
+ const mcpInt = (description, extra = {}) => ({ type: "integer", description, ...extra });
149
+ const mcpBool = (description) => ({ type: "boolean", description });
150
+ const mcpStrArray = (description, items = { type: "string" }) => ({ type: "array", items, description });
151
+ const MCP_PROJECT_PROP = { projectId: mcpStr("Project ID. Defaults to the configured project.") };
152
+ // approvals.in-conversation: who approved, when Claude records an approval (the project's "Who approves" setting decides what is accepted)
153
+ const APPROVAL_PARAMS = {
154
+ onBehalfOf: mcpStr("When a person approved it in this conversation: that member's email. Never name someone who did not say it."),
155
+ quote: mcpStr("The person's own words approving it, verbatim from this conversation (e.g. \"godkänt\") — required with onBehalfOf"),
156
+ };
157
+ const pickApproval = (a) => ({ ...(a.onBehalfOf ? { onBehalfOf: a.onBehalfOf } : {}), ...(a.quote ? { quote: a.quote } : {}) });
158
+ const MCP_REQ_STATUSES = ["draft", "approved", "in_progress", "rejected", "implemented", "tested", "superseded"];
159
+ const MCP_BACKLOG_STATUSES = ["open", "in_progress", "on_hold", "ready_for_test", "resolved", "rejected"];
160
+ const MCP_BACKLOG_TYPES = ["bug", "improvement", "requirement_gap", "technical_defect"];
161
+ const MCP_PRIORITY = mcpInt("Priority: 1 (high), 2 (medium), 3 (low)", { enum: [1, 2, 3] });
162
+
163
+ function mcpSchema(props = {}, required = []) {
164
+ return { type: "object", properties: { ...MCP_PROJECT_PROP, ...props }, required, additionalProperties: false };
165
+ }
166
+
167
+ const mcpCall = (name, data) => env.call(name, data);
168
+
169
+ // Thrown by tool handlers for a refusal that should reach the client as a tool error, not a crash.
170
+ class McpToolError extends Error {}
171
+
172
+ // Copies only the listed keys that the caller actually supplied.
173
+ function mcpPick(args, keys) {
174
+ const out = {};
175
+ for (const k of keys) if (args[k] !== undefined) out[k] = args[k];
176
+ return out;
177
+ }
178
+
179
+ const mcpTools = [
180
+ {
181
+ name: "list_projects",
182
+ description: "List the qa-tools projects this login can access.",
183
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
184
+ noProject: true,
185
+ run: async () => (await mcpCall("listProjects", {})).projects,
186
+ },
187
+ {
188
+ // agents.brief-without-hook: the session brief for agents that have no session-start hook (Codex, Copilot)
189
+ name: "get_brief",
190
+ description: "The qa-tools brief for the start of a session: requirements in progress, items flagged for re-verification, the agenda, hot requests, this branch's requirements, and whether qatools-cli is out of date. Read it before you start working, unless you already got the brief at session start.",
191
+ inputSchema: mcpSchema(),
192
+ run: async (a) => {
193
+ if (!local.brief) throw new McpToolError("The brief needs qatools mcp on your computer, in the repo");
194
+ return local.brief({ projectId: a.projectId });
195
+ },
196
+ },
197
+ {
198
+ name: "get_agenda",
199
+ description: "What to work on next in the project (same data as `qatools next`): open signals, requirements awaiting work, sessions awaiting analysis.",
200
+ inputSchema: mcpSchema(),
201
+ run: async (a) => {
202
+ const agenda = await mcpCall("getProjectAgenda", { projectId: a.projectId });
203
+ return warnings().length ? { warnings: warnings(), ...agenda } : agenda;
204
+ },
205
+ },
206
+ {
207
+ name: "get_app_context",
208
+ description: "The project's App Context: purpose, tech stack, conventions, AI rules, design principles.",
209
+ inputSchema: mcpSchema(),
210
+ run: async (a) => mcpCall("getAppContext", { projectId: a.projectId }),
211
+ },
212
+ {
213
+ name: "list_requirements",
214
+ description: "List requirements. Superseded requirements are hidden unless includeSuperseded is true.",
215
+ inputSchema: mcpSchema({
216
+ status: mcpStrArray("Only these statuses", { type: "string", enum: MCP_REQ_STATUSES }),
217
+ epicKey: mcpStr("Only requirements linked to this epic key"),
218
+ sprintId: mcpStr("Only requirements planned in this sprint"),
219
+ includeSuperseded: mcpBool("Include superseded requirements"),
220
+ }),
221
+ run: async (a) => {
222
+ let reqs = (await mcpCall("listRequirements", { projectId: a.projectId, status: null })).requirements;
223
+ if (!a.includeSuperseded) reqs = reqs.filter(r => r.status !== "superseded");
224
+ if (a.status?.length) { const s = new Set(a.status); reqs = reqs.filter(r => s.has(r.status)); }
225
+ if (a.epicKey) reqs = reqs.filter(r => r.epicKey === a.epicKey);
226
+ if (a.sprintId) reqs = reqs.filter(r => r.sprintId === a.sprintId);
227
+ return reqs;
228
+ },
229
+ },
230
+ {
231
+ name: "create_requirement",
232
+ 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.",
233
+ inputSchema: mcpSchema({
234
+ key: mcpStr("Semantic key, e.g. auth.login"),
235
+ title: mcpStr("Title"),
236
+ description: mcpStr("Description"),
237
+ acceptanceCriteria: mcpStr("Given/When/Then scenario(s), newline-separated"),
238
+ negativeCriteria: mcpStr("Negative Given/When/Then scenario(s)"),
239
+ type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }),
240
+ priority: MCP_PRIORITY,
241
+ category: mcpStr("Category"),
242
+ epicKey: mcpStr("Epic key"),
243
+ sprintId: mcpStr("Sprint ID to plan it in"),
244
+ status: mcpStr("Initial status (default draft)", { enum: MCP_REQ_STATUSES }),
245
+ force: mcpBool("Skip the semantic similarity check"),
246
+ points: { type: "integer", enum: [1, 2, 3, 5, 8], description: "Size in points. Split anything bigger than 8. Not for non-functional requirements." },
247
+ version: mcpInt("New version of an existing key (e.g. 2). Then set the old version to superseded with update_requirement."),
248
+ ...APPROVAL_PARAMS,
249
+ reason: mcpStr("Status rejected: why (min 5 chars). Status approved by an agent itself, where the project allows it: why you approve it"),
250
+ }, ["key", "title"]),
251
+ run: async (a) => mcpCall("createRequirement", { projectId: a.projectId, ...mcpPick(a, ["key", "title", "description", "acceptanceCriteria", "negativeCriteria", "type", "priority", "category", "epicKey", "sprintId", "status", "force", "version", "points", "reason"]), ...pickApproval(a) }),
252
+ },
253
+ {
254
+ name: "update_requirement",
255
+ 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.",
256
+ inputSchema: mcpSchema({
257
+ requirementId: mcpStr("Requirement document ID"),
258
+ status: mcpStr("New status", { enum: MCP_REQ_STATUSES }),
259
+ assignedTo: mcpStr("Assignee: a member's email, \"me\" (the Claude account), or empty string to clear. Setting status back to approved clears it."),
260
+ evidence: mcpStr("Required for implemented/tested (min 10 chars): test output, file:line, expected vs actual, or 'no test applies because <reason>'"),
261
+ epicKey: mcpStr("Epic key"),
262
+ sprintId: mcpStr("Sprint ID (empty string clears)"),
263
+ type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }),
264
+ title: mcpStr("Title"),
265
+ description: mcpStr("Description"),
266
+ acceptanceCriteria: mcpStr("Acceptance criteria"),
267
+ negativeCriteria: mcpStr("Negative criteria (what must not happen)"),
268
+ 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." },
269
+ reason: mcpStr("Required for status rejected (min 5 chars): why it is rejected; kept with the requirement. For status approved by an agent itself, where the project allows it: why you approve it"),
270
+ ...APPROVAL_PARAMS,
271
+ attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
272
+ commit: mcpStr("Commit the evidence was verified on. Default: git HEAD of the server's working directory; empty string to leave it out"),
273
+ }, ["requirementId"]),
274
+ run: async (a) => {
275
+ const updates = mcpPick(a, ["status", "assignedTo", "epicKey", "sprintId", "type", "title", "description", "acceptanceCriteria", "negativeCriteria", "points"]);
276
+ if (Object.keys(updates).length === 0) throw new McpToolError("No fields to update.");
277
+ const evidenceById = a.evidence ? { [a.requirementId]: a.evidence } : {};
278
+ if (requirementEvidenceViolations({ [a.requirementId]: updates }, evidenceById).length > 0) {
279
+ throw new McpToolError(`Refusing status=${updates.status} without evidence (min 10 chars). Cite the verification, or use a status that does not claim done.`);
280
+ }
281
+ if (updates.status === "rejected" && String(a.reason || a.evidence || "").trim().length < 5) {
282
+ throw new McpToolError("Refusing status=rejected without a reason (min 5 chars). Say why — it is kept with the requirement.");
283
+ }
284
+ const payload = { projectId: a.projectId, requirementId: a.requirementId, updates, ...(a.reason ? { reason: a.reason } : {}), ...pickApproval(a) };
285
+ if (a.evidence) {
286
+ payload.evidence = a.evidence;
287
+ const commit = a.commit !== undefined ? a.commit : currentGitCommit();
288
+ if (commit) payload.commit = commit;
289
+ }
290
+ if (a.attachments?.length) {
291
+ if (!a.evidence) throw new McpToolError("attachments need evidence — images belong to an evidence entry");
292
+ payload.attachments = await uploadEvidenceFiles(a.projectId, a.attachments);
293
+ }
294
+ const r = await mcpCall("updateRequirement", payload);
295
+ return { updated: a.requirementId, fields: Object.keys(updates), ...(r?.approvedBy ? { approvedBy: r.approvedBy, approvedIn: r.approvedIn } : {}) };
296
+ },
297
+ },
298
+ {
299
+ name: "list_epics",
300
+ description: "List epics.",
301
+ inputSchema: mcpSchema(),
302
+ run: async (a) => (await mcpCall("listEpics", { projectId: a.projectId })).epics,
303
+ },
304
+ {
305
+ name: "create_epic",
306
+ description: "Create an epic. Check dependsOn against existing epics first (list_epics).",
307
+ inputSchema: mcpSchema({
308
+ key: mcpStr("Epic key, e.g. billing"),
309
+ title: mcpStr("Title"),
310
+ description: mcpStr("Description"),
311
+ value: mcpStr("Why this capability exists"),
312
+ scope: mcpStrArray("Scope items"),
313
+ dependsOn: mcpStrArray("Epic keys this depends on"),
314
+ priority: MCP_PRIORITY,
315
+ }, ["key", "title"]),
316
+ run: async (a) => mcpCall("createEpic", {
317
+ projectId: a.projectId, key: a.key, title: a.title, description: a.description || "", value: a.value || "",
318
+ scope: a.scope || [], dependsOn: a.dependsOn || [], priority: a.priority || 2,
319
+ }),
320
+ },
321
+ {
322
+ name: "update_epic",
323
+ description: "Update an epic.",
324
+ inputSchema: mcpSchema({
325
+ epicId: mcpStr("Epic document ID"),
326
+ status: mcpStr("Status", { enum: ["draft", "active", "completed"] }),
327
+ title: mcpStr("Title"),
328
+ description: mcpStr("Description"),
329
+ value: mcpStr("Value statement"),
330
+ scope: mcpStrArray("Scope items (replaces existing)"),
331
+ priority: MCP_PRIORITY,
332
+ }, ["epicId"]),
333
+ run: async (a) => {
334
+ const updates = mcpPick(a, ["status", "title", "description", "value", "scope", "priority"]);
335
+ if (Object.keys(updates).length === 0) throw new McpToolError("No fields to update.");
336
+ await mcpCall("updateEpic", { projectId: a.projectId, epicId: a.epicId, updates });
337
+ return { updated: a.epicId, fields: Object.keys(updates) };
338
+ },
339
+ },
340
+ {
341
+ name: "list_sprints",
342
+ description: "List sprints, ordered by release (end) date.",
343
+ inputSchema: mcpSchema(),
344
+ run: async (a) => (await mcpCall("listSprints", { projectId: a.projectId })).sprints,
345
+ },
346
+ {
347
+ name: "sprint_velocity",
348
+ 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).",
349
+ inputSchema: mcpSchema(),
350
+ run: async (a) => {
351
+ const [{ sprints }, { requirements }] = await Promise.all([
352
+ mcpCall("listSprints", { projectId: a.projectId }),
353
+ mcpCall("listRequirements", { projectId: a.projectId, status: null }),
354
+ ]);
355
+ const DONE = new Set(["implemented", "tested"]);
356
+ const active = requirements.filter(r => r.status !== "superseded" && r.status !== "rejected");
357
+ const row = (s) => {
358
+ const base = { id: s.id, name: s.name, status: s.status, startDate: s.startDate || "", releaseDate: s.releaseDate || "" };
359
+ // sprint.completion-snapshot: completing moves the unfinished out, so only the stored numbers show what was planned.
360
+ if (s.status === "completed" && s.completionStats) {
361
+ const cs = s.completionStats;
362
+ return { ...base, planned: cs.planned, done: cs.done, moved: cs.moved, fromSnapshot: true, completedAt: cs.completedAt || "",
363
+ ...(typeof cs.donePoints === "number" ? { plannedPoints: cs.plannedPoints, donePoints: cs.donePoints } : {}) };
364
+ }
365
+ const reqs = active.filter(r => r.sprintId === s.id);
366
+ return { ...base, planned: reqs.length, done: reqs.filter(r => DONE.has(r.status)).length,
367
+ points: reqs.reduce((n, r) => n + (r.points || 0), 0), withoutPoints: reqs.filter(r => !r.points).length,
368
+ ...(s.status === "completed" ? { fromSnapshot: false } : {}) };
369
+ };
370
+ const completed = sprints.filter(s => s.status === "completed").map(row);
371
+ const withWork = completed.filter(s => s.planned > 0);
372
+ const avg = withWork.length ? withWork.reduce((n, s) => n + s.done, 0) / withWork.length : null;
373
+ const rate = withWork.length ? withWork.reduce((n, s) => n + s.done / s.planned, 0) / withWork.length : null;
374
+ // Same rule as the web app (sprint-capacity.ts): last three completed sprints with points, else done requirements
375
+ const recent = [...completed].filter(s => s.fromSnapshot).sort((x, y) => (y.completedAt || "").localeCompare(x.completedAt || ""));
376
+ const pointed = recent.filter(s => typeof s.donePoints === "number").slice(0, 3);
377
+ const basis = pointed.length ? pointed : recent.slice(0, 3);
378
+ const capacity = basis.length
379
+ ? { 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,
380
+ ...(pointed.length ? {} : { note: "No completed sprint has points yet — capacity is counted in requirements" }) }
381
+ : null;
382
+ return {
383
+ capacity,
384
+ completedSprints: completed,
385
+ averageDonePerCompletedSprint: avg === null ? null : Math.round(avg * 10) / 10,
386
+ averageCompletionRate: rate === null ? null : Math.round(rate * 100) / 100,
387
+ openSprints: sprints.filter(s => s.status !== "completed").map(row),
388
+ unplannedApprovedRequirements: active.filter(r => r.status === "approved" && !r.sprintId).length,
389
+ unplannedApprovedWithoutPoints: active.filter(r => r.status === "approved" && !r.sprintId && r.type !== "non-functional" && !r.points).length,
390
+ };
391
+ },
392
+ },
393
+ {
394
+ name: "propose_sprint_plan",
395
+ 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 — or tells you so, and you record it with approve_plan_proposal (the project's 'Who approves' setting decides). 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.",
396
+ inputSchema: mcpSchema({
397
+ goal: mcpStr("What the plan optimises for, e.g. 'Release 4.0 by Nov 18'"),
398
+ summary: mcpStr("Short rationale: capacity used, dependency order, risks"),
399
+ items: {
400
+ type: "array",
401
+ description: "One row per requirement",
402
+ items: {
403
+ type: "object",
404
+ properties: {
405
+ requirementId: mcpStr("Requirement document ID"),
406
+ sprintId: mcpStr("Existing sprint ID (or use newSprintRef)"),
407
+ newSprintRef: mcpStr("ref of a sprint in newSprints"),
408
+ reason: mcpStr("Why this requirement goes in this sprint"),
409
+ selfVerification: mcpStr("How you will verify it yourself, e.g. 'unit tests for X + API call Y' (sprint.ai-planning-self-verification)"),
410
+ manualOnly: { type: "boolean", description: "true when you cannot verify it yourself at all — then testProtocols must have a test for it" },
411
+ 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" },
412
+ },
413
+ required: ["requirementId", "reason"],
414
+ additionalProperties: false,
415
+ },
416
+ },
417
+ newSprints: {
418
+ type: "array",
419
+ description: "Sprints to create if the proposal is approved",
420
+ items: {
421
+ type: "object",
422
+ properties: {
423
+ ref: mcpStr("Your local reference, e.g. new-1"),
424
+ name: mcpStr("Sprint name"),
425
+ releaseDate: mcpStr("End date YYYY-MM-DD"),
426
+ startDate: mcpStr("Start date YYYY-MM-DD"),
427
+ },
428
+ required: ["ref", "name", "releaseDate"],
429
+ additionalProperties: false,
430
+ },
431
+ },
432
+ omitted: {
433
+ type: "array",
434
+ description: "Requirements deliberately left out, with why",
435
+ items: { type: "object", properties: { key: mcpStr("Requirement key"), reason: mcpStr("Why") }, required: ["key", "reason"], additionalProperties: false },
436
+ },
437
+ testProtocols: {
438
+ type: "array",
439
+ 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.",
440
+ items: {
441
+ type: "object",
442
+ properties: {
443
+ name: mcpStr("Protocol name, e.g. 'Release 4.1 — manual tests'"),
444
+ sprintId: mcpStr("Existing sprint ID (or use newSprintRef)"),
445
+ newSprintRef: mcpStr("ref of a sprint in newSprints"),
446
+ sections: {
447
+ type: "array",
448
+ description: "Sections of manual tests",
449
+ items: {
450
+ type: "object",
451
+ properties: {
452
+ title: mcpStr("Section title"),
453
+ tests: {
454
+ type: "array",
455
+ items: {
456
+ type: "object",
457
+ properties: {
458
+ id: mcpStr("Test id, e.g. M-1"),
459
+ name: mcpStr("What is tested"),
460
+ steps: mcpStr("Steps a person follows"),
461
+ expected: mcpStr("Expected result"),
462
+ purpose: mcpStr("Why a person must perform this, e.g. 'real phone camera', 'SMS must actually arrive', 'visual check'"),
463
+ requirementKey: mcpStr("Key of the requirement it verifies"),
464
+ },
465
+ required: ["name", "steps", "expected", "purpose", "requirementKey"],
466
+ additionalProperties: false,
467
+ },
468
+ },
469
+ },
470
+ required: ["title", "tests"],
471
+ additionalProperties: false,
472
+ },
473
+ },
474
+ },
475
+ required: ["name", "sections"],
476
+ additionalProperties: false,
477
+ },
478
+ },
479
+ swaps: {
480
+ type: "array",
481
+ 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.",
482
+ items: {
483
+ type: "object",
484
+ properties: {
485
+ sprintId: mcpStr("Sprint in progress to take the requirement into"),
486
+ inRequirementId: mcpStr("Requirement taken in (approved or in progress)"),
487
+ outRequirementIds: mcpStrArray("Requirements moved out (approved, in that sprint)"),
488
+ reason: mcpStr("Why the change is worth it"),
489
+ },
490
+ required: ["sprintId", "inRequirementId", "outRequirementIds", "reason"],
491
+ additionalProperties: false,
492
+ },
493
+ },
494
+ }, []),
495
+ run: async (a) => {
496
+ if (!a.items?.length && !a.swaps?.length) throw new McpToolError("Give items, swaps or both.");
497
+ const r = await mcpCall("createPlanProposal", { projectId: a.projectId, ...mcpPick(a, ["goal", "summary", "items", "newSprints", "omitted", "testProtocols", "swaps"]) });
498
+ return { ...r, next: "Pending. A project member approves or rejects it in qa-tools under Sprints → Plan proposals, or tells you — then approve_plan_proposal with their words." };
499
+ },
500
+ },
501
+ {
502
+ name: "list_plan_proposals",
503
+ description: "List sprint-plan proposals and their status (pending/approved/rejected), with who decided and what was applied.",
504
+ inputSchema: mcpSchema({ status: mcpStr("Filter by status", { enum: ["pending", "approved", "rejected"] }) }),
505
+ run: async (a) => (await mcpCall("listPlanProposals", { projectId: a.projectId, status: a.status || null })).proposals,
506
+ },
507
+ {
508
+ name: "list_compliance_due",
509
+ 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.",
510
+ inputSchema: mcpSchema({ sprintId: mcpStr("Sprint ID (default: the active sprint)") }),
511
+ run: async (a) => mcpCall("listComplianceDue", { projectId: a.projectId, sprintId: a.sprintId || null }),
512
+ },
513
+ {
514
+ name: "record_compliance_verification",
515
+ 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.",
516
+ inputSchema: mcpSchema({
517
+ requirementKey: mcpStr("Continuous requirement key"),
518
+ result: mcpStr("passed or failed", { enum: ["passed", "failed"] }),
519
+ evidence: mcpStr("What was checked in the sprint's diff and what was found (file:line), min 10 chars"),
520
+ sprintId: mcpStr("Sprint ID (default: the active sprint)"),
521
+ commit: mcpStr("Commit checked"),
522
+ attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
523
+ }, ["requirementKey", "result", "evidence"]),
524
+ run: async (a) => mcpCall("recordSprintVerification", { projectId: a.projectId, ...mcpPick(a, ["requirementKey", "result", "evidence", "sprintId", "commit"]), attachments: await uploadEvidenceFiles(a.projectId, a.attachments) }),
525
+ },
526
+ {
527
+ name: "notify_member",
528
+ description: "Email one project member, e.g. the person who made a wish that now waits for their yes (respects their opt-out — a mail they turned off is not sent). An addressed, deliberate message; plain text.",
529
+ inputSchema: mcpSchema({
530
+ to: mcpStr("The member's email"),
531
+ subject: mcpStr("Email subject"),
532
+ message: mcpStr("Plain-text body"),
533
+ }, ["to", "subject", "message"]),
534
+ run: async (a) => mcpCall("notifyUser", { projectId: a.projectId, to: a.to, subject: a.subject, message: a.message }),
535
+ },
536
+ {
537
+ name: "notify_owner",
538
+ description: "Email the project owner (respects their opt-out). Used for the summary at the end of a scheduled run — pass run so qa-tools knows the run happened. Plain text.",
539
+ inputSchema: mcpSchema({
540
+ subject: mcpStr("Email subject"),
541
+ message: mcpStr("Plain-text body"),
542
+ run: { type: "string", enum: ["loop", "daily"], description: "The scheduled run this summary ends (loop = loop_run, daily = daily_agenda_run); the session brief warns when one stops" },
543
+ }, ["subject", "message"]),
544
+ run: async (a) => mcpCall("notifyUser", { projectId: a.projectId, to: "owner", subject: a.subject, message: a.message, ...(a.run ? { run: a.run } : {}) }),
545
+ },
546
+ {
547
+ name: "propose_app_context",
548
+ description: "Propose the project's App Context (purpose, domainObjects, actors, stack, architecture, security, constraints, conventions, environments, integrations, verifyCommands — the check commands its CI runs), e.g. read from an existing repo. Only what the code shows. It counts only when a member approves it — in the web app, or by telling you (decide_app_context_proposal with their words). Several proposals can be pending side by side (e.g. from parallel sessions); say in summary what yours covers.",
549
+ inputSchema: mcpSchema({
550
+ 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, verifyCommands: the commands the repo's CI runs, e.g. [\"npm test\", \"npm run build\"])" },
551
+ summary: mcpStr("What the proposal is based on (files read)"),
552
+ }, ["context"]),
553
+ run: async (a) => mcpCall("proposeAppContext", { projectId: a.projectId, context: a.context, summary: a.summary || "" }),
554
+ },
555
+ {
556
+ name: "list_app_context_proposals",
557
+ description: "List App Context proposals (default pending) with what fields each covers, who proposed and who decided.",
558
+ inputSchema: mcpSchema({ status: mcpStr("Filter by status", { enum: ["pending", "approved", "rejected", "superseded"] }) }),
559
+ run: async (a) => mcpCall("listAppContextProposals", { projectId: a.projectId, status: a.status || "pending" }),
560
+ },
561
+ {
562
+ name: "decide_app_context_proposal",
563
+ description: "Approve or reject a pending App Context proposal because a member told you so in this conversation. Always needs the person (onBehalfOf + quote) — an agent never approves the rules it follows itself.",
564
+ inputSchema: mcpSchema({
565
+ proposalId: mcpStr("Proposal ID (from list_app_context_proposals)"),
566
+ decision: mcpStr("approve or reject", { enum: ["approve", "reject"] }),
567
+ ...APPROVAL_PARAMS,
568
+ comment: mcpStr("Reject: why (min 5 chars)"),
569
+ }, ["proposalId", "decision", "onBehalfOf", "quote"]),
570
+ run: async (a) => mcpCall("decideAppContextProposal", { projectId: a.projectId, proposalId: a.proposalId, decision: a.decision, ...(a.comment ? { comment: a.comment } : {}), ...pickApproval(a) }),
571
+ },
572
+ {
573
+ name: "reject_plan_proposal",
574
+ description: "Reject (withdraw) a pending sprint-plan proposal, e.g. one you created that is superseded. Nothing gets planned. To approve one, use approve_plan_proposal.",
575
+ inputSchema: mcpSchema({
576
+ proposalId: mcpStr("Proposal ID (from list_plan_proposals)"),
577
+ comment: mcpStr("Why it is rejected (min 5 chars) — required, kept with the proposal"),
578
+ }, ["proposalId", "comment"]),
579
+ run: async (a) => {
580
+ await mcpCall("decidePlanProposal", { projectId: a.projectId, proposalId: a.proposalId, decision: "reject", comment: a.comment || "" });
581
+ return { rejected: a.proposalId, planned: 0 };
582
+ },
583
+ },
584
+ {
585
+ name: "approve_plan_proposal",
586
+ description: "Approve a pending sprint-plan proposal and apply it, because a member told you so in this conversation (onBehalfOf + quote). Only where the project's \"Who approves\" setting allows it; where it lets agents approve by themselves, give reason instead of a person. Optionally only some rows or swaps.",
587
+ inputSchema: mcpSchema({
588
+ proposalId: mcpStr("Proposal ID (from list_plan_proposals)"),
589
+ ...APPROVAL_PARAMS,
590
+ reason: mcpStr("Only when an agent approves by itself, where the project allows it: why"),
591
+ requirementIds: mcpStrArray("Approve only these rows (requirement IDs); default all"),
592
+ swapInIds: mcpStrArray("Approve only the swaps taking in these requirement IDs; default all (none when requirementIds is given)"),
593
+ comment: mcpStr("Comment kept with the decision"),
594
+ }, ["proposalId"]),
595
+ run: async (a) => mcpCall("decidePlanProposal", { projectId: a.projectId, proposalId: a.proposalId, decision: "approve", ...mcpPick(a, ["requirementIds", "swapInIds", "comment", "reason"]), ...pickApproval(a) }),
596
+ },
597
+ {
598
+ name: "get_sprint_items",
599
+ description: "Everything planned in a sprint: its requirements (the planning unit) and the backlog signals linked to it.",
600
+ inputSchema: mcpSchema({ sprintId: mcpStr("Sprint ID") }, ["sprintId"]),
601
+ run: async (a) => mcpCall("getSprintItems", { projectId: a.projectId, sprintId: a.sprintId }),
602
+ },
603
+ {
604
+ name: "create_sprint",
605
+ description: "Create a sprint. Status derives from dates (planning/active/overdue); without startDate it stays in planning.",
606
+ inputSchema: mcpSchema({
607
+ name: mcpStr("Sprint name"),
608
+ releaseDate: mcpStr("End/release date, YYYY-MM-DD", { pattern: "^\\d{4}-\\d{2}-\\d{2}$" }),
609
+ startDate: mcpStr("Start date, YYYY-MM-DD", { pattern: "^\\d{4}-\\d{2}-\\d{2}$" }),
610
+ }, ["name", "releaseDate"]),
611
+ run: async (a) => (await mcpCall("createSprint", { projectId: a.projectId, name: a.name, startDate: a.startDate || "", releaseDate: a.releaseDate })).sprint,
612
+ },
613
+ {
614
+ name: "list_backlog",
615
+ description: "List backlog signals (AVV/GAP/DEF/IMP).",
616
+ inputSchema: mcpSchema({
617
+ sprintId: mcpStr("Only items in this sprint"),
618
+ status: mcpStrArray("Only these statuses", { type: "string", enum: MCP_BACKLOG_STATUSES }),
619
+ assignedTo: mcpStr("Only items assigned to this email"),
620
+ }),
621
+ run: async (a) => mcpCall("listBacklog", { projectId: a.projectId, ...mcpPick(a, ["sprintId", "assignedTo"]), ...(a.status?.length ? { status: a.status } : {}) }),
622
+ },
623
+ {
624
+ name: "create_backlog_item",
625
+ description: "Report a backlog signal: bug (AVV), requirement_gap (GAP), technical_defect (DEF) or improvement (IMP). Not for planning work — plan with requirements.",
626
+ inputSchema: mcpSchema({
627
+ description: mcpStr("What was observed"),
628
+ type: mcpStr("Signal type: bug = AVV (deviation from a requirement, default), requirement_gap = GAP, technical_defect = DEF, improvement = IMP", { enum: MCP_BACKLOG_TYPES }),
629
+ priority: MCP_PRIORITY,
630
+ assignedTo: mcpStr("Assignee email"),
631
+ developer: mcpStr("Responsible developer email"),
632
+ sprintId: mcpStr("Sprint ID"),
633
+ parentId: mcpStr("Parent item label, e.g. AVV-5"),
634
+ requirementKey: mcpStr("Requirement key it relates to"),
635
+ tags: mcpStrArray("Tags"),
636
+ mailNotify: mcpBool("Enable email notifications on this item (default off)"),
637
+ securitySeverity: mcpStr("Mark as a security item, on any type", { enum: ["critical", "high", "medium", "low"] }),
638
+ }, ["description"]),
639
+ run: async (a) => {
640
+ const r = await mcpCall("createBacklogItem", {
641
+ projectId: a.projectId, type: a.type || "bug", description: a.description, priority: a.priority || 2,
642
+ assignedTo: a.assignedTo || "", developer: a.developer || "", sprintId: a.sprintId || "", parentId: a.parentId || "",
643
+ requirementKey: a.requirementKey || "", tags: (a.tags || []).map(t => t.trim().toLowerCase()), mailNotify: !!a.mailNotify,
644
+ securitySeverity: a.securitySeverity || "",
645
+ });
646
+ return { ...r, label: backlogLabel(r.type, r.bugNumber) };
647
+ },
648
+ },
649
+ {
650
+ name: "update_backlog_item",
651
+ 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.",
652
+ inputSchema: mcpSchema({
653
+ itemId: mcpStr("Backlog item document ID"),
654
+ status: mcpStr("New status", { enum: MCP_BACKLOG_STATUSES }),
655
+ evidence: mcpStr("Required for resolved (min 10 chars): test output, file:line, expected vs actual, or 'no test applies because <reason>'"),
656
+ comment: mcpStr("Comment to add"),
657
+ authorName: mcpStr("Comment author name (default Claude)"),
658
+ assignedTo: mcpStr("Assignee email"),
659
+ developer: mcpStr("Developer email"),
660
+ sprintId: mcpStr("Sprint ID"),
661
+ priority: MCP_PRIORITY,
662
+ requirementKey: mcpStr("Requirement key"),
663
+ tags: mcpStrArray("Tags (replaces existing)"),
664
+ description: mcpStr("New description"),
665
+ mailNotify: mcpBool("Item email notifications on/off"),
666
+ securitySeverity: mcpStr("Security marking; none takes it away", { enum: ["critical", "high", "medium", "low", "none"] }),
667
+ skipTestVerification: mcpBool("Allow resolved without ready_for_test — only when no test applies. Evidence is still required."),
668
+ attachments: mcpStrArray("Local image file paths (png/jpg/webp/gif, max 4 MB) to attach to the evidence, e.g. screenshots"),
669
+ }, ["itemId"]),
670
+ run: async (a) => {
671
+ const u = mcpPick(a, ["status", "evidence", "assignedTo", "developer", "sprintId", "priority", "requirementKey", "description", "mailNotify"]);
672
+ if (a.comment) { u.comment = a.comment; u.authorName = a.authorName || env.agentName || "Claude"; }
673
+ if (a.tags) u.tags = a.tags.map(t => t.trim().toLowerCase());
674
+ if (a.securitySeverity) u.securitySeverity = a.securitySeverity === "none" ? "" : a.securitySeverity;
675
+ if (Object.keys(u).length === 0) throw new McpToolError("No fields to update.");
676
+ 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).");
677
+ const updates = { [a.itemId]: u };
678
+ if (u.status === "resolved") {
679
+ // Fail closed: unlike the interactive CLI, the MCP server refuses when the pre-check can't run.
680
+ let v;
681
+ try {
682
+ v = await backlogResolveViolations(mcpCall, a.projectId, updates, { skipTestVerification: !!a.skipTestVerification });
683
+ } catch (e) {
684
+ throw new McpToolError(`Could not verify the backlog flow before resolving (${e.message}). Nothing was changed.`);
685
+ }
686
+ if (v.evidence.length) throw new McpToolError("Refusing status=resolved without evidence (min 10 chars). Cite the verification, or set ready_for_test instead.");
687
+ 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.`);
688
+ }
689
+ if (a.attachments?.length) {
690
+ if (!a.evidence) throw new McpToolError("attachments need evidence — images belong to an evidence entry");
691
+ u.attachments = await uploadEvidenceFiles(a.projectId, a.attachments);
692
+ }
693
+ const r = await mcpCall("updateBacklogItems", { updates });
694
+ // The backend skips items it can't find or the caller can't access, instead of throwing.
695
+ 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.`);
696
+ return { updated: a.itemId, fields: Object.keys(u) };
697
+ },
698
+ },
699
+ {
700
+ name: "requirement_impact",
701
+ 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).",
702
+ 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") }),
703
+ run: async (a) => runImpact({ projectId: a.projectId || getCredentials()?.projectId, since: a.since, sprint: a.sprint, flag: !!a.flag, main: a.main }),
704
+ },
705
+ {
706
+ name: "list_feature_requests",
707
+ 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).",
708
+ inputSchema: mcpSchema(),
709
+ run: async (a) => (await mcpCall("listFeatureRequests", { projectId: a.projectId })).requests,
710
+ },
711
+ {
712
+ name: "link_feature_request",
713
+ 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.",
714
+ inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)"), requirementKey: mcpStr("Requirement key, e.g. reports.export") }, ["id", "requirementKey"]),
715
+ run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "link", requirementKey: a.requirementKey }),
716
+ },
717
+ {
718
+ name: "unlink_feature_request",
719
+ description: "Undo a link between a request from the app's users and a requirement.",
720
+ inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)") }, ["id"]),
721
+ run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "unlink" }),
722
+ },
723
+ {
724
+ name: "requests_integration_prompt",
725
+ 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.",
726
+ inputSchema: mcpSchema(),
727
+ run: async () => require("./context-sync").requestsIntegrationPrompt(getCredentials()?.projectName || ""),
728
+ },
729
+ {
730
+ name: "new_app_questions",
731
+ 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.",
732
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
733
+ run: async () => mcpCall("getNewAppQuestions", {}),
734
+ },
735
+ {
736
+ name: "create_project",
737
+ description: "projects.claude-proposes-new-project: start a new qa-tools project. Creates nothing: it returns a link with the name and purpose filled in. Give the link to the user, who creates the project there as themselves. Never change ~/.qatools or log in as the user to do it.",
738
+ inputSchema: { type: "object", properties: { name: mcpStr("The app's name"), description: mcpStr("One sentence: what it does") }, required: ["name"], additionalProperties: false },
739
+ run: async (a) => {
740
+ const name = String(a.name).trim().slice(0, 100);
741
+ if (!name) throw new McpToolError("name required");
742
+ const params = new URLSearchParams({ name, description: String(a.description || "").slice(0, 1000) });
743
+ return {
744
+ created: false,
745
+ link: `https://qa-tools.com/new-project?${params}`,
746
+ next: "Give the user this link. They create the project there, signed in as themselves, with Claude switched on. The page shows the project's ID, and for Claude Code the command that gives you your own login for the repo, which they run in their own terminal. In a chat, ask them for the ID.",
747
+ };
748
+ },
749
+ },
750
+ {
751
+ name: "apply_new_app_answers",
752
+ 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.",
753
+ inputSchema: mcpSchema({
754
+ answers: { type: "object", description: "The answers, keyed by question id", additionalProperties: true },
755
+ overwrite: mcpBool("Replace fields that already have content — only after the user confirmed"),
756
+ }, ["answers"]),
757
+ run: async (a) => mcpCall("applyNewAppAnswers", { projectId: a.projectId || getCredentials()?.projectId, answers: a.answers, overwrite: !!a.overwrite }),
758
+ },
759
+ {
760
+ name: "release_notes_prompt",
761
+ 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.",
762
+ inputSchema: mcpSchema({ sprintId: mcpStr("The release: sprint id or name (default: latest completed)") }),
763
+ run: async (a) => (await mcpCall("getReleaseNotesPrompt", { projectId: a.projectId, sprintId: a.sprintId || "" })).prompt,
764
+ },
765
+ {
766
+ name: "save_release_notes_draft",
767
+ 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.",
768
+ inputSchema: mcpSchema({ sprintId: mcpStr("The release: sprint id or name"), text: mcpStr("The notes: short points in the users' language") }, ["sprintId", "text"]),
769
+ run: async (a) => mcpCall("saveReleaseNotesDraft", { projectId: a.projectId, sprintId: a.sprintId, text: a.text }),
770
+ },
771
+ {
772
+ name: "infra_prompt",
773
+ 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.",
774
+ inputSchema: mcpSchema({ platform: mcpStr("azure, gcp, aws or firebase (default: from the App Context)", { enum: ["azure", "gcp", "aws", "firebase"] }) }),
775
+ run: async (a) => (await mcpCall("getInfraPrompt", { projectId: a.projectId, platform: a.platform || "" })).prompt,
776
+ },
777
+ // ---- cli.mcp-parity: the CLI's project-data commands, through the same backend functions ----
778
+ {
779
+ name: "update_project",
780
+ description: "Change the project's name or description (owner).",
781
+ inputSchema: mcpSchema({ name: mcpStr("New name"), description: mcpStr("New description") }),
782
+ run: async (a) => {
783
+ const updates = mcpPick(a, ["name", "description"]);
784
+ if (!Object.keys(updates).length) throw new McpToolError("Give name and/or description.");
785
+ return mcpCall("updateProjectFields", { projectId: a.projectId, updates });
786
+ },
787
+ },
788
+ {
789
+ name: "add_member",
790
+ description: "Add a member to the project by email; they get an invitation email. Owner only.",
791
+ inputSchema: mcpSchema({ email: mcpStr("The member's email") }, ["email"]),
792
+ run: async (a) => mcpCall("addProjectMember", { projectId: a.projectId, email: a.email }),
793
+ },
794
+ {
795
+ name: "remove_member",
796
+ description: "Remove a member from the project (the owner cannot be removed). Destructive: confirm with the user in this conversation before calling.",
797
+ inputSchema: mcpSchema({ email: mcpStr("The member's email") }, ["email"]),
798
+ run: async (a) => mcpCall("removeProjectMember", { projectId: a.projectId, email: a.email }),
799
+ },
800
+ {
801
+ name: "delete_requirement",
802
+ 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.",
803
+ inputSchema: mcpSchema({ requirementId: mcpStr("Requirement document id"), force: mcpBool("Delete even though items or tests reference it — re-point them first") }, ["requirementId"]),
804
+ run: async (a) => mcpCall("deleteRequirement", { projectId: a.projectId, requirementId: a.requirementId, force: !!a.force }),
805
+ },
806
+ {
807
+ name: "delete_epic",
808
+ description: "Delete an epic by key. Refused while requirements belong to it. Destructive: confirm with the user first.",
809
+ inputSchema: mcpSchema({ epicKey: mcpStr("Epic key") }, ["epicKey"]),
810
+ run: async (a) => {
811
+ const epic = ((await mcpCall("listEpics", { projectId: a.projectId })).epics || []).find(e => e.key === a.epicKey);
812
+ if (!epic) throw new McpToolError(`Epic '${a.epicKey}' not found.`);
813
+ return mcpCall("deleteEpic", { projectId: a.projectId, epicId: epic.id });
814
+ },
815
+ },
816
+ {
817
+ name: "requirement_coverage",
818
+ description: "Per requirement: its manual test cases and automated test runs, and which ones verify it.",
819
+ inputSchema: mcpSchema(),
820
+ run: async (a) => mcpCall("requirementCoverage", { projectId: a.projectId }),
821
+ },
822
+ {
823
+ name: "list_requirement_keys",
824
+ description: "Every requirement key in use in the project's test protocols and backlog, with where it is used.",
825
+ inputSchema: mcpSchema(),
826
+ run: async (a) => mcpCall("listRequirementKeys", { projectId: a.projectId }),
827
+ },
828
+ {
829
+ name: "reject_template",
830
+ description: "Reject a test protocol (version) with a reason; it can no longer be started as a session.",
831
+ inputSchema: mcpSchema({ templateId: mcpStr("Test protocol id"), reason: mcpStr("Why — at least a few words") }, ["templateId", "reason"]),
832
+ run: async (a) => mcpCall("rejectTemplate", { projectId: a.projectId, templateId: a.templateId, reason: a.reason }),
833
+ },
834
+ {
835
+ name: "upload_test_report",
836
+ 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.",
837
+ inputSchema: mcpSchema({ file: mcpStr("Path to the results file"), format: mcpStr("junit or json (default: from the file extension)", { enum: ["junit", "json"] }) }, ["file"]),
838
+ run: async (a) => {
839
+ const filePath = path.resolve(a.file);
840
+ if (!fs.existsSync(filePath)) throw new McpToolError(`File not found: ${filePath}`);
841
+ const text = fs.readFileSync(filePath, "utf-8");
842
+ const format = a.format || (/\.json$/i.test(filePath) ? "json" : "junit");
843
+ const results = format === "json" ? parseTestJson(JSON.parse(text)) : parseJUnit(text);
844
+ if (!results.length) throw new McpToolError("No test results found in the file.");
845
+ return mcpCall("uploadTestRun", { projectId: a.projectId, run: ciRunMeta({}), results });
846
+ },
847
+ },
848
+ {
849
+ name: "find_duplicates",
850
+ description: "Find backlog items that look like duplicates of each other (uses the project's Anthropic key on the server).",
851
+ inputSchema: mcpSchema(),
852
+ run: async (a) => mcpCall("findDuplicates", { projectId: a.projectId }),
853
+ },
854
+ {
855
+ name: "import_security_scan",
856
+ 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.",
857
+ inputSchema: mcpSchema({ file: mcpStr("Path to the SARIF file"), source: mcpStr("Scanner name, e.g. codeql") }, ["file"]),
858
+ run: async (a) => {
859
+ const filePath = path.resolve(a.file);
860
+ if (!fs.existsSync(filePath)) throw new McpToolError(`File not found: ${filePath}`);
861
+ return mcpCall("importSecurityScan", { projectId: a.projectId, sarif: JSON.parse(fs.readFileSync(filePath, "utf-8")), source: a.source || "" });
862
+ },
863
+ },
864
+ {
865
+ name: "set_app_context",
866
+ 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.",
867
+ inputSchema: mcpSchema({ context: { type: "object", description: "The whole App Context", additionalProperties: true } }, ["context"]),
868
+ run: async (a) => mcpCall("saveAppContext", { projectId: a.projectId, context: a.context }),
869
+ },
870
+ {
871
+ name: "get_access_model",
872
+ description: "The project's access model: roles and what each may do.",
873
+ inputSchema: mcpSchema(),
874
+ run: async (a) => mcpCall("getAccessModel", { projectId: a.projectId }),
875
+ },
876
+ {
877
+ name: "set_access_model",
878
+ 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.",
879
+ inputSchema: mcpSchema({ model: { type: "object", description: "The whole access model", additionalProperties: true } }, ["model"]),
880
+ run: async (a) => mcpCall("saveAccessModel", { projectId: a.projectId, model: a.model }),
881
+ },
882
+ {
883
+ name: "decline_feature_request",
884
+ 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.",
885
+ inputSchema: mcpSchema({ id: mcpStr("The request's id in the app (externalId)"), reason: mcpStr("Why — shown to the app's users") }, ["id", "reason"]),
886
+ run: async (a) => mcpCall("decideFeatureRequest", { projectId: a.projectId, externalId: a.id, action: "decline", reason: a.reason }),
887
+ },
888
+ {
889
+ name: "list_skill_library",
890
+ description: "The shared skill library: skills that can be added to a project's App Context.",
891
+ inputSchema: mcpSchema(),
892
+ run: async () => mcpCall("listSkillLibrary", {}),
893
+ },
894
+ {
895
+ name: "get_library_skill",
896
+ description: "Read one skill from the shared skill library.",
897
+ inputSchema: mcpSchema({ name: mcpStr("Skill name") }, ["name"]),
898
+ run: async (a) => mcpCall("getLibrarySkill", { name: a.name }),
899
+ },
900
+ {
901
+ name: "save_library_skill",
902
+ description: "Add or update a skill in the shared skill library (superadmin).",
903
+ 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"]),
904
+ run: async (a) => mcpCall("saveLibrarySkill", { name: a.name, title: a.title, description: a.description || "", content: a.content }),
905
+ },
906
+ {
907
+ name: "delete_library_skill",
908
+ description: "Remove a skill from the shared skill library (superadmin). Destructive: confirm with the user first.",
909
+ inputSchema: mcpSchema({ name: mcpStr("Skill name") }, ["name"]),
910
+ run: async (a) => mcpCall("deleteLibrarySkill", { name: a.name }),
911
+ },
912
+ {
913
+ name: "baseline_prompt",
914
+ 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.",
915
+ inputSchema: mcpSchema(),
916
+ run: async (a) => (await mcpCall("getBaselinePrompt", { projectId: a.projectId })).prompt,
917
+ },
918
+ {
919
+ name: "upload_baseline",
920
+ 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, or by telling you (then decide_reconstructed_requirement with their words); never on your own initiative.",
921
+ inputSchema: mcpSchema({
922
+ requirements: {
923
+ type: "array", description: "Reconstructed requirements (at most 100)",
924
+ items: {
925
+ type: "object",
926
+ properties: {
927
+ key: mcpStr("Semantic key, e.g. keys.search"), title: mcpStr("Title"), description: mcpStr("Description"),
928
+ acceptanceCriteria: mcpStr("Given/When/Then scenario(s), newline-separated"), negativeCriteria: mcpStr("Negative scenario(s)"),
929
+ type: mcpStr("functional or non-functional", { enum: ["functional", "non-functional"] }), epicKey: mcpStr("Epic key"),
930
+ files: mcpStrArray("Files where it is built, e.g. src/app/x.ts:40-88"), commits: mcpStrArray("Commits where it was built"),
931
+ },
932
+ required: ["key", "title", "acceptanceCriteria"],
933
+ },
934
+ },
935
+ }, ["requirements"]),
936
+ run: async (a) => mcpCall("uploadBaselineRequirements", { projectId: a.projectId, requirements: a.requirements }),
937
+ },
938
+ {
939
+ name: "decide_reconstructed_requirement",
940
+ description: "Approve as built (sets it implemented, the code as evidence) or reject a requirement reconstructed from code, because a member told you so in this conversation (onBehalfOf + quote). Only where the project's \"Who approves\" setting allows it; where it lets agents approve by themselves, give reason instead of a person.",
941
+ inputSchema: mcpSchema({
942
+ requirementId: mcpStr("Requirement ID of a reconstructed draft (list_requirements status draft)"),
943
+ decision: mcpStr("approve or reject", { enum: ["approve", "reject"] }),
944
+ ...APPROVAL_PARAMS,
945
+ reason: mcpStr("Reject: why (min 5 chars). Approve by an agent itself, where allowed: why"),
946
+ }, ["requirementId", "decision"]),
947
+ run: async (a) => mcpCall("decideBaselineRequirement", { projectId: a.projectId, requirementId: a.requirementId, decision: a.decision, ...(a.reason ? { reason: a.reason } : {}), ...pickApproval(a) }),
948
+ },
949
+ {
950
+ name: "update_library_requirement",
951
+ description: "Change an entry in the account's requirement library (owner only). The new text reaches every requirement in every project that inherits it — confirm with the user first.",
952
+ inputSchema: mcpSchema({
953
+ key: mcpStr("Library key"),
954
+ title: mcpStr("New title"), description: mcpStr("New description"),
955
+ acceptanceCriteria: mcpStr("New acceptance criteria"), negativeCriteria: mcpStr("New negative criteria"), category: mcpStr("New category"),
956
+ }, ["key"]),
957
+ run: async (a) => {
958
+ const updates = mcpPick(a, ["title", "description", "acceptanceCriteria", "negativeCriteria", "category"]);
959
+ if (!Object.keys(updates).length) throw new McpToolError("Give at least one field to change");
960
+ const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
961
+ const entry = entries.find(e => e.key === a.key);
962
+ if (!entry) throw new McpToolError(`Not in the library: ${a.key}`);
963
+ return mcpCall("updateLibraryRequirement", { projectId: a.projectId, libraryId: entry.id, updates });
964
+ },
965
+ },
966
+ {
967
+ name: "list_audit_log",
968
+ description: "The project's security log (security.audit-log): who changed keys, members and other security settings, and when. Owner or superadmin only.",
969
+ inputSchema: mcpSchema({ limit: mcpInt("Number of entries (default 50)") }),
970
+ run: async (a) => (await mcpCall("listAuditLog", { projectId: a.projectId, limit: a.limit || 50 })).entries,
971
+ },
972
+ {
973
+ name: "evidence_backfill",
974
+ description: "Verified requirements without an evidence commit: find the newest commit on main naming the key (runs in the repo on the user's computer). apply: true records them as commit links — not new verifications.",
975
+ inputSchema: mcpSchema({ apply: mcpBool("Record the commits in qa-tools (default: only show them)"), main: mcpStr("The main branch (default: origin/HEAD, else origin/main, origin/master, main, master)") }),
976
+ run: async (a) => runEvidenceBackfill({ projectId: a.projectId, apply: !!a.apply, main: a.main }),
977
+ },
978
+ {
979
+ name: "list_requirement_library",
980
+ 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.",
981
+ inputSchema: mcpSchema({ category: mcpStr("Only this category") }),
982
+ run: async (a) => {
983
+ const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
984
+ return a.category ? entries.filter(e => (e.category || "").toLowerCase() === a.category.toLowerCase()) : entries;
985
+ },
986
+ },
987
+ {
988
+ name: "share_requirement_to_library",
989
+ 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.",
990
+ inputSchema: mcpSchema({
991
+ requirementId: mcpStr("Requirement document ID"),
992
+ 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 },
993
+ applicability: mcpStr("What is specific to this project, e.g. 'Applies to Twilio, SendGrid, Auth0'"),
994
+ }, ["requirementId"]),
995
+ run: async (a) => mcpCall("shareRequirementToLibrary", { projectId: a.projectId, ...mcpPick(a, ["requirementId", "text", "applicability"]) }),
996
+ },
997
+ {
998
+ name: "inherit_library_requirements",
999
+ 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.",
1000
+ inputSchema: mcpSchema({ keys: mcpStrArray("Library keys"), category: mcpStr("Every entry in this category"), applicability: mcpStr("What they apply to in this project") }),
1001
+ run: async (a) => {
1002
+ let libraryIds;
1003
+ if (a.keys?.length) {
1004
+ const { entries } = await mcpCall("listRequirementLibrary", { projectId: a.projectId });
1005
+ libraryIds = entries.filter(e => a.keys.includes(e.key)).map(e => e.id);
1006
+ }
1007
+ return mcpCall("inheritLibraryRequirements", { projectId: a.projectId, libraryIds, category: a.category, applicability: a.applicability });
1008
+ },
1009
+ },
1010
+ {
1011
+ name: "create_test_protocol",
1012
+ 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.",
1013
+ inputSchema: mcpSchema({
1014
+ sprintId: mcpStr("Sprint ID the protocol belongs to"),
1015
+ name: mcpStr("Protocol name, e.g. 'Release 4.1 — manual tests'"),
1016
+ sections: {
1017
+ type: "array",
1018
+ description: "Sections of manual tests",
1019
+ items: {
1020
+ type: "object",
1021
+ properties: {
1022
+ title: mcpStr("Section title"),
1023
+ tests: {
1024
+ type: "array",
1025
+ items: {
1026
+ type: "object",
1027
+ properties: {
1028
+ id: mcpStr("Test id, e.g. M-1"),
1029
+ name: mcpStr("What is tested"),
1030
+ steps: mcpStr("Steps a person follows"),
1031
+ expected: mcpStr("Expected result"),
1032
+ purpose: mcpStr("Why a person must perform this, e.g. 'real phone camera', 'SMS must actually arrive', 'visual check'"),
1033
+ requirementKey: mcpStr("Key of the requirement it verifies"),
1034
+ },
1035
+ required: ["name", "steps", "expected", "purpose", "requirementKey"],
1036
+ additionalProperties: false,
1037
+ },
1038
+ },
1039
+ },
1040
+ required: ["title", "tests"],
1041
+ additionalProperties: false,
1042
+ },
1043
+ },
1044
+ 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"),
1045
+ }, ["sprintId", "name", "sections"]),
1046
+ run: async (a) => {
1047
+ for (const sec of a.sections) for (const t of sec.tests || []) {
1048
+ if (!String(t.purpose || "").trim()) throw new McpToolError(`Test "${t.name}" needs a purpose saying why a person must perform it`);
1049
+ }
1050
+ const r = await mcpCall("uploadTemplate", { projectId: a.projectId, sprintId: a.sprintId, name: a.name, sections: a.sections, ...(a.replaces ? { replaces: a.replaces } : {}) });
1051
+ return { ...r, next: "Pending review. A project member approves it in qa-tools under Test protocols." };
1052
+ },
1053
+ },
1054
+ {
1055
+ name: "list_templates",
1056
+ description: "List test templates (test protocols) and their review status.",
1057
+ inputSchema: mcpSchema({ status: mcpStr("Filter by review status", { enum: ["draft", "pending_review", "approved", "rejected"] }) }),
1058
+ run: async (a) => (await mcpCall("listTemplates", { projectId: a.projectId, status: a.status || null })).templates,
1059
+ },
1060
+ {
1061
+ name: "pending_sessions",
1062
+ description: "Test sessions awaiting Claude analysis.",
1063
+ inputSchema: mcpSchema(),
1064
+ run: async (a) => (await mcpCall("pendingSessions", { projectId: a.projectId })).pending,
1065
+ },
1066
+ {
1067
+ name: "read_session",
1068
+ description: "Read a test session with its template and linked backlog details.",
1069
+ inputSchema: { type: "object", properties: { sessionId: mcpStr("Test session ID") }, required: ["sessionId"], additionalProperties: false },
1070
+ noProject: true,
1071
+ run: async (a) => mcpCall("readSession", { sessionId: a.sessionId }),
1072
+ },
1073
+ {
1074
+ name: "upload_analysis",
1075
+ description: "Upload an analysis of a test session (same format as `qatools upload-analysis`): analysis[] with verdicts, and optional backlogUpdates keyed by item ID.",
1076
+ inputSchema: {
1077
+ type: "object",
1078
+ properties: {
1079
+ sessionId: mcpStr("Test session ID"),
1080
+ analysis: { type: "array", items: { type: "object" }, description: "Analysis entries" },
1081
+ 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." },
1082
+ },
1083
+ required: ["sessionId", "analysis"],
1084
+ additionalProperties: false,
1085
+ },
1086
+ noProject: true,
1087
+ run: async (a) => mcpCall("uploadAnalysis", { sessionId: a.sessionId, analysis: a.analysis, backlogUpdates: a.backlogUpdates || {} }),
1088
+ },
1089
+ ];
1090
+
1091
+
1092
+ // Prompts (sprint.ai-planning): ready-made workflows the user picks in the client, e.g. the "+" menu in Claude Desktop.
1093
+ const mcpPrompts = [
1094
+ {
1095
+ name: "plan_sprints",
1096
+ description: "Plan approved requirements into sprints: Claude proposes, you approve, then it applies.",
1097
+ arguments: [
1098
+ { name: "projectId", description: "Project ID (default: configured project)", required: false },
1099
+ { name: "goal", description: "What to optimise for, e.g. 'release 4.0 by Nov 18' or 'auth first'", required: false },
1100
+ ],
1101
+ text: (a) => `Plan sprints in qa-tools${a.projectId ? ` for project ${a.projectId}` : ""}.${a.goal ? ` Goal: ${a.goal}.` : ""}
1102
+
1103
+ Follow these steps in order:
1104
+
1105
+ 1. Gather facts, don't guess: list_sprints, sprint_velocity, list_epics, list_requirements (status approved, plus anything already planned in open sprints).
1106
+ 2. Draft a plan. Only requirements are planned — never create backlog items as tasks. Rules:
1107
+ - 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).
1108
+ - An epic's requirements never go into an earlier sprint than the requirements of the epics it dependsOn.
1109
+ - Order by priority (1 first), then epic priority.
1110
+ - 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.
1111
+ - 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.
1112
+ - 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.
1113
+ - 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.
1114
+ - If the requirements don't fit in the existing sprints, propose new sprints (name + end date) — don't create them yet.
1115
+ - 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.
1116
+ 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.
1117
+ 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.
1118
+ - 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.
1119
+ 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.
1120
+ 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.
1121
+ 7. End with get_sprint_items for each affected sprint so the user can see the result.`,
1122
+ },
1123
+ {
1124
+ name: "daily_agenda_run",
1125
+ description: "Unattended run (automation.daily-agenda-run): work through the project agenda, propose — never apply — and email the owner a summary.",
1126
+ arguments: [{ name: "projectId", description: "Project ID (default: configured project)", required: false }],
1127
+ text: (a) => dailyAgendaRunPrompt(a.projectId),
1128
+ },
1129
+ {
1130
+ name: "loop_run",
1131
+ description: "Unattended run of the self-playing loop (loop.claude-builds-approved), in the app's repo: answer wishes, draft requirements, build one approved wish on a branch, deploy to the test environment only, never to production.",
1132
+ arguments: [{ name: "projectId", description: "Project ID (default: configured project)", required: false }],
1133
+ text: (a) => loopRunPrompt(a.projectId),
1134
+ },
1135
+ {
1136
+ name: "new_app",
1137
+ 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.",
1138
+ arguments: [{ name: "name", description: "The app's name, if already known", required: false }],
1139
+ text: (a) => `Help the user start a new app in qa-tools${a.name ? ` called "${a.name}"` : ""}.
1140
+
1141
+ 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.
1142
+ 2. When you have the answers and a name, call create_project (name, description = the purpose). It creates nothing and returns a link: give it to the user. They create the project there, signed in as themselves, and the page shows the project's ID. In Claude Code the page also shows the command qatools init --agent claude --project <id>, which they run in their own terminal, in the repo; then they restart Claude Code and resume this conversation. In a chat, ask them for the ID and continue. Never change ~/.qatools, never log in as the user and never use their login to create the project, even if a tool or command refuses you.
1143
+ 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.
1144
+ 4. Propose the first epics from the App Context.`,
1145
+ },
1146
+ ];
1147
+
1148
+ function mcpValidateArgs(tool, args) {
1149
+ for (const k of tool.inputSchema.required || []) {
1150
+ if (args[k] === undefined || args[k] === null || args[k] === "") throw new McpToolError(`Missing required argument: ${k}`);
1151
+ }
1152
+ const known = tool.inputSchema.properties;
1153
+ const unknown = Object.keys(args).filter(k => !(k in known));
1154
+ if (unknown.length) throw new McpToolError(`Unknown argument(s): ${unknown.join(", ")}`);
1155
+ }
1156
+
1157
+ async function mcpHandle(msg, defaultProjectId) {
1158
+ const { method, params } = msg;
1159
+ if (method === "initialize") {
1160
+ const requested = params?.protocolVersion;
1161
+ return {
1162
+ protocolVersion: MCP_PROTOCOL_VERSIONS.includes(requested) ? requested : MCP_PROTOCOL_VERSIONS[0],
1163
+ capabilities: { tools: { listChanged: false }, prompts: { listChanged: false } },
1164
+ serverInfo: { name: "qatools", version: env.version || "" },
1165
+ instructions: instructions + (warnings().length ? "\n- OUT OF DATE: " + warnings().join(" ") + " Upgrade yourself (npm install -g qatools-cli@latest, then qatools init in the repo, commit the .claude changes) and tell the user in one line — unless this is an unattended run, which never upgrades mid-run." : ""),
1166
+ };
1167
+ }
1168
+ if (method === "ping") return {};
1169
+ if (method === "tools/list") {
1170
+ return { tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) };
1171
+ }
1172
+ if (method === "prompts/list") {
1173
+ return { prompts: mcpPrompts.map(({ name, description, arguments: args }) => ({ name, description, arguments: args })) };
1174
+ }
1175
+ if (method === "prompts/get") {
1176
+ const prompt = mcpPrompts.find(p => p.name === params?.name);
1177
+ if (!prompt) throw Object.assign(new Error(`Unknown prompt: ${params?.name}`), { code: -32602 });
1178
+ const args = params.arguments || {};
1179
+ return { description: prompt.description, messages: [{ role: "user", content: { type: "text", text: prompt.text(args) } }] };
1180
+ }
1181
+ if (method === "tools/call") {
1182
+ const tool = tools.find(t => t.name === params?.name);
1183
+ if (!tool) throw Object.assign(new Error(`Unknown tool: ${params?.name}`), { code: -32602 });
1184
+ const args = { ...(params.arguments || {}) };
1185
+ try {
1186
+ mcpValidateArgs(tool, args);
1187
+ if (!tool.noProject) {
1188
+ args.projectId = args.projectId || defaultProjectId;
1189
+ if (!args.projectId) throw new McpToolError(env.noDefaultProject ? "Pass projectId — list_projects shows the projects you are a member of" : "No project configured. Pass projectId, or run: qatools setup");
1190
+ }
1191
+ const data = await tool.run(args);
1192
+ return { content: [{ type: "text", text: typeof data === "string" ? data : JSON.stringify(data ?? null, null, 2) }] };
1193
+ } catch (e) {
1194
+ // Tool failures (refusals, backend permission errors) go back as tool results the model can read.
1195
+ return { content: [{ type: "text", text: e.message || String(e) }], isError: true };
1196
+ }
1197
+ }
1198
+ throw Object.assign(new Error(`Method not found: ${method}`), { code: -32601 });
1199
+ }
1200
+
1201
+
1202
+ tools = env.local ? mcpTools : mcpTools.filter(t => !MCP_LOCAL_ONLY.has(t.name));
1203
+ // agents.brief-without-hook: an agent without Claude Code's session hook reads the brief first
1204
+ instructions = MCP_INSTRUCTIONS + (local.brief ? "\n- Before you start working in a session, call get_brief (unless the qa-tools brief was already shown at session start): what is in progress, what waits, and whether qa-tools is out of date." : "") + (env.noDefaultProject ? "\n- This is the qa-tools connector in Claude: there is no configured project. Call list_projects first and pass projectId to every tool; when it is unclear which project the person means, ask them." : "");
1205
+ return { tools, prompts: mcpPrompts, handle: (msg, defaultProjectId) => mcpHandle(msg, defaultProjectId), instructions };
1206
+ }
1207
+
1208
+ module.exports = { createMcp, dailyAgendaRunPrompt, loopRunPrompt, MCP_LOCAL_ONLY, backlogLabel, requirementEvidenceViolations, backlogResolveViolations };