@agent-tasks/mcp-server 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tools.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import { z } from "zod";
2
- import { AgentTasksApiError } from "./client.js";
2
+ import { AgentTasksApiError, ProjectSlugNotFoundError } from "./client.js";
3
+ import { WORKFLOW_PRIMER } from "./primer.js";
4
+ import { mapBackendError, serializeTeachingError, looksLikeStructuredWrapper, resultMustBePlainStringError, projectAddressingConflictError, unknownProjectSlugError, } from "./errors.js";
5
+ import { receiptForCreate, receiptForRespec, receiptForFinish, receiptForSubmitPr, receiptForMerge, receiptForAbandon, receiptForNote, receiptForStart, projectPickup, } from "./receipt.js";
6
+ import { projectTaskSummary, paginateSignals, TASKS_GET_INCLUDE_VALUES, SIGNALS_DEFAULT_LIMIT, SIGNALS_MAX_LIMIT, SIGNALS_BACKEND_FETCH_LIMIT, } from "./read.js";
3
7
  const transitionStatusEnum = z.enum([
4
8
  "open",
5
9
  "in_progress",
@@ -8,16 +12,80 @@ const transitionStatusEnum = z.enum([
8
12
  ]);
9
13
  const priorityEnum = z.enum(["LOW", "MEDIUM", "HIGH", "CRITICAL"]);
10
14
  const uuid = () => z.string().uuid();
11
- async function wrap(fn) {
15
+ // ── Receipt contract (docs/response-contract-v1.md) ─────────────────────────
16
+ //
17
+ // Write verbs return a receipt by default (see the wrap() choke point below
18
+ // and receipt.ts, which owns the projection logic). `include: ["task"]` is
19
+ // the compatibility valve: it skips the projection and returns the full,
20
+ // pre-contract backend object for that call, unchanged. "task" is the only
21
+ // value this schema accepts today: the richer read-verb vocabulary
22
+ // ("description", "comments", "instructions", "artifacts") belongs to the
23
+ // read verbs (rc-v1-C006, not yet converted) and is deliberately NOT
24
+ // accepted here: passing one of those values on a write verb is a zod
25
+ // validation error, not a silent no-op.
26
+ const includeSchema = z
27
+ .array(z.enum(["task"]))
28
+ .max(1)
29
+ .optional()
30
+ .describe('Receipt v1: pass ["task"] to get the full, pre-contract object back for this call instead of the small receipt (recovery path after context loss, or when you need the whole task in one call). "task" is the only supported value on write verbs today.');
31
+ // task_start's own include enum. Wider than the other write verbs' (which
32
+ // accept only "task") because task_start's default response is a receipt
33
+ // PLUS a small per-task slice (inferredTaskType, expectedFinishState,
34
+ // gateExpectations) rather than the raw full task — description, comments,
35
+ // and the per-state instructions prose are each reachable individually via
36
+ // include, without paying for the whole object. include:["task"] is still
37
+ // the full, pre-contract object valve, same as every other write verb. See
38
+ // receipt.ts's receiptForStart.
39
+ const startIncludeSchema = z
40
+ .array(z.enum(["description", "instructions", "comments", "task"]))
41
+ .max(4)
42
+ .optional()
43
+ .describe('Default response is a receipt + a small per-task slice (inferredTaskType, expectedFinishState, gateExpectations), not the full task. Pass one or more of "description", "instructions" (the state\'s agent-facing prose), "comments" to add just that field back, or "task" for the full, pre-contract object (recovery path after context loss).');
44
+ // task_pickup's include enum. Its default is already the (near-)full task
45
+ // spec per docs/response-contract-v1.md ("full spec, without comments") —
46
+ // the only thing include can add back today is comments; "task" is the
47
+ // uniform full-object escape hatch every other verb has. Both currently
48
+ // resolve to the same content for this verb (see receipt.ts's projectPickup
49
+ // doc comment for why that duplication is deliberate, not a bug).
50
+ const pickupIncludeSchema = z
51
+ .array(z.enum(["comments", "task"]))
52
+ .max(2)
53
+ .optional()
54
+ .describe('Default response is the full task spec WITHOUT comments. Pass ["comments"] or ["task"] to get comments back too (both return the same full, pre-contract object for this verb today).');
55
+ // tasks_get's include enum (rc-v1-C006, the read-verb surface docs/
56
+ // response-contract-v1.md's "include semantics" section reserves the full
57
+ // five-value vocabulary for). Default response is a SUMMARY (id, title,
58
+ // status, priority, labels, claims, blockedBy, prUrl), not the full task —
59
+ // see read.ts's projectTaskSummary. "instructions" is deliberately not in
60
+ // this enum: it is task_start's own per-state prose, not a field a plain
61
+ // task object carries.
62
+ const readIncludeSchema = z
63
+ .array(z.enum(TASKS_GET_INCLUDE_VALUES))
64
+ .max(TASKS_GET_INCLUDE_VALUES.length)
65
+ .optional()
66
+ .describe('Default response is a summary (id, title, status, priority, labels, claims, blockedBy, prUrl), not the full task. Pass one or more of "description", "comments", "artifacts" to add just that field back, or "task" for the full, pre-contract object (recovery path after context loss).');
67
+ // Choke point for every backend call: maps a thrown AgentTasksApiError to
68
+ // the teaching-error shape (docs/response-contract-v1.md's "Error shape
69
+ // (block tier)" section; see errors.ts) and throws it as an Error whose
70
+ // message IS the serialized shape (serializeTeachingError, which produces
71
+ // the same JSON.stringify(x, null, 2) text server.ts's serializeResult
72
+ // would for the same object). server.ts's tool-call catch block reads
73
+ // `err.message` straight into the isError text block, so this is the one
74
+ // place that decides the wire format for every verb's failure path;
75
+ // tests/errors.test.ts pins the equality with serializeResult directly.
76
+ //
77
+ // `verbContext`, forwarded to mapBackendError, is this call's own tool name
78
+ // — passed only at the handful of call sites where the resulting recipe
79
+ // actually depends on it (see errors.ts's precondition_failed entry);
80
+ // every other call site omits it and gets the verb-independent catalog
81
+ // entries (or the generic degrade path) unaffected.
82
+ async function wrap(fn, verbContext) {
12
83
  try {
13
84
  return await fn();
14
85
  }
15
86
  catch (err) {
16
87
  if (err instanceof AgentTasksApiError) {
17
- const detail = err.body
18
- ? ` — ${typeof err.body === "string" ? err.body : JSON.stringify(err.body)}`
19
- : "";
20
- throw new Error(`agent-tasks API ${err.status}: ${err.message}${detail}`);
88
+ throw new Error(serializeTeachingError(mapBackendError(err.status, err.body, verbContext)));
21
89
  }
22
90
  throw err;
23
91
  }
@@ -25,30 +93,100 @@ async function wrap(fn) {
25
93
  function def(d) {
26
94
  return d;
27
95
  }
28
- // ── v1 deprecation notice ────────────────────────────────────────────────────
96
+ // ── v1 deprecation notice, and the rc-v1-C007 pruning ───────────────────────
29
97
  //
30
- // The v1 tools below are being phased out in favor of the v2 verb-oriented
98
+ // The v1 tools below were phased out in favor of the v2 verb-oriented
31
99
  // surface (task_pickup / task_start / task_note / task_finish / task_create /
32
- // task_abandon). LLM clients that see both should prefer the non-deprecated
33
- // variant. v1 tools will be removed 4 weeks after the v2 release. See ADR 0008.
100
+ // task_abandon). See ADR 0008.
101
+ //
102
+ // rc-v1-C007: every verb still carrying this DEPRECATED prefix is
103
+ // registered only when buildTools is called with { legacy: true } -- see
104
+ // the filter at the bottom of buildTools. server.ts's createServer takes
105
+ // the same optional { legacy?: boolean } and passes it straight through;
106
+ // index.ts reads AGENT_TASKS_MCP_LEGACY from the process environment and
107
+ // forwards it as that option. Handler code is untouched by this change: it
108
+ // is a registration-time filter, not a deletion, so AGENT_TASKS_MCP_LEGACY=1
109
+ // is a genuine escape hatch for a caller still depending on a pruned verb's
110
+ // name, and buildTools stays testable in both modes without env stubbing.
111
+ //
112
+ // A few DEPRECATED-marked-in-spirit verbs stay in the DEFAULT registration
113
+ // regardless, because the work that produced them is still active: tasks_get
114
+ // (upgraded by rc-v1-C006 into the modern summary+include read verb, no
115
+ // longer actually deprecated, its DEPRECATED prefix removed below),
116
+ // tasks_comment (the receipt-converted v1 alias named in the primers'
117
+ // converted-verb sentence; pruning it would break their truth guards, and
118
+ // its own DEPRECATED prefix -- stale, since it is kept permanently, not
119
+ // sunsetting -- is removed below too), and signals_poll / signals_ack
120
+ // (signals_poll carries the rc-v1-C006 cap semantics, and acking is
121
+ // required for progress at the fetch ceiling). See mcp-server/README.md's
122
+ // replacement table for the verb-by-verb migration guidance, and
123
+ // docs/response-contract-v1.md for the legacy-flag verbs' exemption from
124
+ // this package's response-shape rules.
34
125
  const DEPRECATED = "[DEPRECATED, use v2 tools] ";
35
- export function buildTools(client) {
36
- return [
126
+ // Verb names pruned from the DEFAULT registration by rc-v1-C007. This is a
127
+ // deliberate, hand-typed pin of that exact set, not a value mechanically
128
+ // derived from the DEPRECATED prefix at build time: tests/tools.test.ts's
129
+ // own "[DEPRECATED marker set equals LEGACY_VERB_NAMES, both directions"
130
+ // test is the mechanical guard that keeps the two in sync, so a future verb
131
+ // marked DEPRECATED above without a matching entry here (or vice versa)
132
+ // fails that test, not just this comment's word. Every verb below still
133
+ // carries the DEPRECATED prefix on its description; registering one at all
134
+ // is now opt-in via { legacy: true } (or, at the process entrypoint,
135
+ // AGENT_TASKS_MCP_LEGACY=1), kept for compatibility only.
136
+ const LEGACY_VERB_NAMES = new Set([
137
+ "projects_list",
138
+ "projects_get",
139
+ "tasks_list",
140
+ "tasks_instructions",
141
+ "tasks_create",
142
+ "tasks_claim",
143
+ "tasks_release",
144
+ "tasks_transition",
145
+ "tasks_update",
146
+ "review_approve",
147
+ "review_request_changes",
148
+ "review_claim",
149
+ "review_release",
150
+ "pull_requests_comment",
151
+ ]);
152
+ export function buildTools(client, options) {
153
+ const tools = [
154
+ // ── Onboarding (docs/response-contract-v1.md's "Onboarding channels by
155
+ // rate of change" table, rc-v1-C004) ────────────────────────────────
156
+ //
157
+ // System/lifecycle/verb-order knowledge that "effectively never"
158
+ // changes gets its own two channels instead of being replayed on every
159
+ // task_start call (see receipt.ts's receiptForStart and rc-v1-C003):
160
+ // the MCP `initialize.instructions` field (server.ts, sent once per
161
+ // session) and this parameterless verb, callable on demand for the
162
+ // fuller reference. Both texts live in primer.ts, single-sourced
163
+ // against default-workflow.ts so the lifecycle prose never grows a
164
+ // third hand-copied version.
165
+ def({
166
+ name: "workflow_primer",
167
+ description: "Full onboarding reference: per-state lifecycle detail, canonical flows, the claim model, receipt/include defaults per verb, and today's error behavior. Parameterless, deterministic, no per-task data (call task_pickup or task_start for that). Complements the shorter `initialize.instructions` text sent once at session start; call this on demand whenever you need the fuller text again, or a fresh session skipped the handshake.",
168
+ inputShape: {},
169
+ handler: async () => WORKFLOW_PRIMER,
170
+ }),
37
171
  // ── v2 surface (ADR 0008) ────────────────────────────────────────────
38
172
  def({
39
173
  name: "task_pickup",
40
- description: "Get the next piece of work. Returns one of: a pending signal, a task ready for review, a claimable task, or idle. The response is tagged with `kind: \"signal\" | \"review\" | \"work\" | \"idle\"`. Signals are delivered at-most-once and acked atomically. Review tasks are filtered by the distinct-reviewer rule (you cannot review tasks you authored). Fails with 409 if you already hold an active claim — call task_finish or task_abandon first.\n\nOptional `reclassify`: opt-in flag that re-runs the debugFlavor classifier past the isFresh guard and overwrites debugFlavor with the new result; on a true-to-false flip it also deletes the now-stale grounding-session metadata. Forwarded as `?reclassify=true` in the query string (the backend compares with `=== \"true\"`, so only the literal lowercase string `true` is honoured; any other truthy representation is a no-op).",
174
+ description: "Get the next piece of work. Returns one of: a pending signal, a task ready for review, a claimable task, or idle. The response is tagged with `kind: \"signal\" | \"review\" | \"work\" | \"idle\"`. Signals are delivered at-most-once and acked atomically. Review tasks are filtered by the distinct-reviewer rule (you cannot review tasks you authored). Fails with 409 if you already hold an active claim; call tasks_get on it to see its state, then task_finish, task_abandon, or task_merge as appropriate (see the already_claimed entry in workflow_primer for the exact cases).\n\nOn a review/work `kind`, returns the full task spec by default — description, templateData, acceptance criteria, everything you need to do the work — WITHOUT `comments` (docs/response-contract-v1.md: task_pickup is the one write verb whose default is the full spec, not a receipt). Pass include:[\"comments\"] or include:[\"task\"] to get comments back too.\n\nOptional `reclassify`: opt-in flag that re-runs the debugFlavor classifier past the isFresh guard and overwrites debugFlavor with the new result; on a true-to-false flip it also deletes the now-stale grounding-session metadata. Forwarded as `?reclassify=true` in the query string (the backend compares with `=== \"true\"`, so only the literal lowercase string `true` is honoured; any other truthy representation is a no-op).",
41
175
  inputShape: {
42
176
  reclassify: z
43
177
  .boolean()
44
178
  .optional()
45
179
  .describe("Opt-in flag. When true, re-runs the debugFlavor classifier past the isFresh guard and overwrites debugFlavor with the new result; on a true-to-false flip it also deletes the now-stale grounding-session metadata. Sent as the literal query string `?reclassify=true` — only lowercase `true` is honoured by the backend; other truthy values are no-ops."),
180
+ include: pickupIncludeSchema,
181
+ },
182
+ handler: async ({ reclassify, include }) => {
183
+ const response = await wrap(() => client.pickupWork(reclassify !== undefined ? { reclassify } : undefined));
184
+ return projectPickup(response, include);
46
185
  },
47
- handler: async ({ reclassify }) => wrap(() => client.pickupWork(reclassify !== undefined ? { reclassify } : undefined)),
48
186
  }),
49
187
  def({
50
188
  name: "task_start",
51
- description: "Begin work on a task. Polymorphic by task status: an `open` task is author-claimed and transitioned to in_progress; a `review` task is review-claimed without state change. Response includes the task data, project info, and `expectedFinishState` (the state task_finish will target for a work claim). Fails with 409 if you already hold an active claim.\n\nOptional `branchName`: for projects that enforce the `branchPresent` workflow gate on the start edge, pass the branch you intend to work on and the server folds it into the same atomic claim write. Single round-trip, no separate tasks_update needed. Ignored when the task already has a branchName (idempotent, never overwrites). Only meaningful on the open→in_progress branch; on a review-claim start the value is accepted but ignored.\n\nOptional `reclassify`: opt-in flag that re-runs the debugFlavor classifier past the isFresh guard and overwrites debugFlavor with the new result; on a true-to-false flip it also deletes the now-stale grounding-session metadata. Forwarded as a strict JSON boolean in the request body (unlike task_pickup where only the literal query string `true` is honoured).",
189
+ description: "Begin work on a task. Polymorphic by task status: an `open` task is author-claimed and transitioned to in_progress; a `review` task is review-claimed without state change. Fails with 409 if you already hold an active claim.\n\nOptional `branchName`: for projects that enforce the `branchPresent` workflow gate on the start edge, pass the branch you intend to work on and the server folds it into the same atomic claim write, no follow-up call required. Ignored when the task already has a branchName (idempotent, never overwrites). Only meaningful on the open→in_progress branch; on a review-claim start the value is accepted but ignored.\n\nOptional `reclassify`: opt-in flag that re-runs the debugFlavor classifier past the isFresh guard and overwrites debugFlavor with the new result; on a true-to-false flip it also deletes the now-stale grounding-session metadata. Forwarded as a strict JSON boolean in the request body (unlike task_pickup where only the literal query string `true` is honoured).\n\nReturns a receipt by default ({ ok, task: { id, status }, transition?, expectedFinishState, gateExpectations?, gateExpectationsSource?, requestChangesGateExpectations?, inferredTaskType? }) — no description, no per-state instructions prose, no comments, and no project object; a compact grounding-session recipe replaces the debugFlavor hint's verbose fields when the task is debug-flavored, and the large metadata.groundingSessionState blob never appears. `transition` (from/to) appears only on an actual state change (a work claim; a review claim does not itself transition status). `gateExpectations` is the gate list for the edge task_finish will hit next (on a review claim: the approve outcome); `requestChangesGateExpectations` is the review claim's other outcome. Either can be `null`, meaning the edge itself does not exist and that finish call will 400, distinct from an omitted field, which means nothing is required (or, on an old backend, nothing could be derived). gateExpectationsSource is set to \"assumed-default-workflow\" only when the backend predates the authoritative gate fields and gateExpectations came from the static built-in-default fallback instead, since a null workflowId can also mean a customized project-default workflow; unset on a current backend. Pass include:[\"description\" | \"instructions\" | \"comments\"] to add one field back, or include:[\"task\"] for the full, pre-contract object (recovery path after context loss).",
52
190
  inputShape: {
53
191
  taskId: uuid(),
54
192
  branchName: z
@@ -62,28 +200,40 @@ export function buildTools(client) {
62
200
  .boolean()
63
201
  .optional()
64
202
  .describe("Opt-in flag. When true, re-runs the debugFlavor classifier past the isFresh guard and overwrites debugFlavor with the new result; on a true-to-false flip it also deletes the now-stale grounding-session metadata. Forwarded as a strict JSON boolean in the request body (unlike task_pickup where the backend compares the query string with === \"true\")."),
203
+ include: startIncludeSchema,
65
204
  },
66
- handler: async ({ taskId, branchName, reclassify }) => {
205
+ handler: async ({ taskId, branchName, reclassify, include }) => {
67
206
  const body = {};
68
207
  if (branchName)
69
208
  body.branchName = branchName;
70
209
  if (reclassify !== undefined)
71
210
  body.reclassify = reclassify;
72
- return wrap(() => client.startTask(taskId, Object.keys(body).length > 0 ? body : undefined));
211
+ const response = await wrap(() => client.startTask(taskId, Object.keys(body).length > 0 ? body : undefined), "task_start");
212
+ // include:["task"] valve is handled inside receiptForStart itself
213
+ // (same layer as projectPickup handles it for task_pickup), not
214
+ // here, since task_start's include vocabulary is wider than the
215
+ // single "task" value the other write verbs accept.
216
+ return receiptForStart(response, include);
73
217
  },
74
218
  }),
75
219
  def({
76
220
  name: "task_note",
77
- description: "Comment on a task. Works for both work and review claims — use this to record progress, ask questions, or leave review feedback. Requires taskId today; a future revision may infer it from the active claim.",
221
+ description: "Comment on a task. Works for both work and review claims — use this to record progress, ask questions, or leave review feedback. Requires taskId today; a future revision may infer it from the active claim.\n\nReturns a receipt by default ({ ok, task: { id } }, no status — the backend comment endpoint does not report task status). Pass include:[\"task\"] for the full { comment } object.",
78
222
  inputShape: {
79
223
  taskId: uuid(),
80
224
  content: z.string().min(1).max(5000),
225
+ include: includeSchema,
226
+ },
227
+ handler: async ({ taskId, content, include }) => {
228
+ const response = await wrap(() => client.addTaskComment(taskId, content));
229
+ if (include?.includes("task"))
230
+ return response;
231
+ return receiptForNote(taskId, response);
81
232
  },
82
- handler: async ({ taskId, content }) => wrap(() => client.addTaskComment(taskId, content)),
83
233
  }),
84
234
  def({
85
235
  name: "task_finish",
86
- description: "Finish a task. Requires an active work or review claim on this specific task; call task_start first to claim it (task_pickup alone returns a candidate but does not claim). The claim of any prior task you just finished does NOT carry over. Polymorphic based on the claim you hold.\n\nWork claim: pass { result?, prUrl?, autoMerge?, mergeMethod? }. prUrl must be a github.com pull-request URL if provided. The task transitions to its expectedFinishState (review or done depending on the workflow). The work claim is cleared when going to done and kept when going to review.\n\nautoMerge (Mode A — work claim): requires project.soloMode=true. Overrides targetStatus to 'done', evaluates gates (skipping prMerged pre-check), merges the PR via GitHub API, then transitions the task to done atomically. Sets autoMergeSha on success.\n\nReview claim: pass { result?, outcome, autoMerge?, mergeMethod? }. approve → task to done, both claims cleared. request_changes → task back to in_progress, review claim cleared, work claim kept so the author resumes, changes_requested signal emitted.\n\nautoMerge (Mode B — review claim + approve): does NOT require soloMode. Merges the PR and transitions to done atomically. outcome 'request_changes' + autoMerge is rejected.\n\nTransitions may be blocked by workflow gates (branchPresent, prPresent, ciGreen, prMerged). A 422 `precondition_failed` response lists the failing rules. See ADR-0010.",
236
+ description: "Finish a task. Requires an active work or review claim on this specific task; call task_start first to claim it (task_pickup alone returns a candidate but does not claim). The claim of any prior task you just finished does NOT carry over. Polymorphic based on the claim you hold.\n\nWork claim: pass { result?, prUrl?, autoMerge?, mergeMethod? }. prUrl must be a github.com pull-request URL if provided. The task transitions to its expectedFinishState (review or done depending on the workflow). The work claim is cleared when going to done and kept when going to review.\n\nautoMerge (Mode A — work claim): requires project.soloMode=true. Overrides targetStatus to 'done', evaluates gates (skipping prMerged pre-check), merges the PR via GitHub API, then transitions the task to done atomically. Sets autoMergeSha on success.\n\nReview claim: pass { result?, outcome, autoMerge?, mergeMethod? }. approve → task to done, both claims cleared. request_changes → task back to in_progress, review claim cleared, work claim kept so the author resumes, changes_requested signal emitted.\n\nautoMerge (Mode B — review claim + approve): does NOT require soloMode. Merges the PR and transitions to done atomically. outcome 'request_changes' + autoMerge is rejected.\n\nTransitions may be blocked by workflow gates (branchPresent, prPresent, ciGreen, prMerged). A 422 `precondition_failed` response lists the failing rules. See ADR-0010.\n\nReturns a receipt by default ({ ok, task: { id, status }, deviations? }) — a WORKFLOW_GATE_SKIPPED deviation appears when autoMerge bypassed a normally-required gate. Pass include:[\"task\"] for the full backend object.",
87
237
  inputShape: {
88
238
  taskId: uuid(),
89
239
  result: z
@@ -95,14 +245,42 @@ export function buildTools(client) {
95
245
  outcome: z.enum(["approve", "request_changes"]).optional(),
96
246
  autoMerge: z.boolean().optional(),
97
247
  mergeMethod: z.enum(["squash", "merge", "rebase"]).optional(),
248
+ include: includeSchema,
249
+ },
250
+ handler: async ({ taskId, include, ...body }) => {
251
+ // Catalog entry #8 (errors.ts): `result` is stored verbatim as free
252
+ // text by the backend, which performs no validation of its shape —
253
+ // this guard exists only at this layer, checked BEFORE any request
254
+ // is sent, so an XML/JSON-wrapped result never round-trips into
255
+ // mis-stored structured input in the first place.
256
+ if (body.result !== undefined && looksLikeStructuredWrapper(body.result)) {
257
+ throw new Error(serializeTeachingError(resultMustBePlainStringError("task_finish")));
258
+ }
259
+ const response = await wrap(() => client.finishTask(taskId, body), "task_finish");
260
+ if (include?.includes("task"))
261
+ return response;
262
+ return receiptForFinish(response);
98
263
  },
99
- handler: async ({ taskId, ...body }) => wrap(() => client.finishTask(taskId, body)),
100
264
  }),
101
265
  def({
102
266
  name: "task_create",
103
- description: "Create a new task in a project. Only title is required. Use externalRef as an idempotency key for bulk imports — the backend dedupes on (projectId, externalRef). Pass dependsOn=[taskId, ...] to declare blocking task IDs (same project); task_pickup will skip the new task until all listed blockers reach status=done. Note: dependsOn is a CREATE-time field only — there is no v2 verb to add or remove blockers post-create; use the REST /tasks/:id/dependencies endpoints (currently human-only) for that. Pass debugFlavor=true/false to explicitly classify the task: true forces the grounding hint at pickup, false suppresses it. When omitted, the backend runs the title/label heuristic lazily at task_pickup instead. The response carries a non-blocking `confidence` object ({score, threshold, enforcementMode, blocking, missing[], findings[], nextActions[]}) so you see what's missing immediately — a low score does NOT block creation; `enforcementMode` tells you whether the hard gate at task_pickup/task_start (BLOCK) will reject it or it is advisory (OFF/WARN). When a project uses task-template mode, call projects_get_effective_gates first and populate the templateData fields it lists under taskCreation.requiredFields.",
267
+ description: "Create a new task in a project. Only title is required (plus exactly one of project, projectId, or projectSlug). Use externalRef as an idempotency key for bulk imports — the backend dedupes on (projectId, externalRef). Pass dependsOn=[taskId, ...] to declare blocking task IDs (same project); task_pickup will skip the new task until every listed blocker reaches a resolved status (done or abandoned). Note: dependsOn is a CREATE-time field only — there is no v2 verb to add or remove blockers post-create; use the REST /tasks/:id/dependencies endpoints (currently human-only) for that. Pass debugFlavor=true/false to explicitly classify the task: true forces the grounding hint at pickup, false suppresses it. When omitted, the backend runs the title/label heuristic lazily at task_pickup instead. When a project uses task-template mode, call projects_get_effective_gates first and populate the templateData fields it lists under taskCreation.requiredFields.\n\nproject is a slug-or-UUID alternative to projectId/projectSlug, matching project_tasks's own `project` param: pass a slug ('agent-tasks') or a UUID in one field instead of choosing between the other two. projectSlug (rc-v1-C006) remains a slug-only alternative to projectId. All three resolve through the same mcp-server-side, TTL-cached slug lookup (~15 min, invalidated and retried once if the cached id 404s downstream) when a slug is given. Passing project together with projectId, project together with projectSlug, or projectId together with projectSlug is a project_addressing_conflict teaching error; passing none of the three is the same error in the other direction. A slug that resolves to nothing is an unknown_project_slug teaching error whose recipe asks the operator for the correct slug or id (or, with AGENT_TASKS_MCP_LEGACY=1 set, call projects_list).\n\nReturns a receipt by default ({ ok, task: { id, status }, confidence: <score>, deviations? }) — description/templateData are NOT echoed back. A CONFIDENCE_BELOW_THRESHOLD deviation appears when score < threshold, with detail ({score, threshold, enforcementMode, missing[] clamped to the first 5, totalMissing}) and a task_respec hint; low confidence never blocks creation itself, only the hard gate at task_pickup/task_start (when enforcementMode=BLOCK) does. Pass include:[\"task\"] for the full { task, confidence } object.",
104
268
  inputShape: {
105
- projectId: uuid(),
269
+ project: z
270
+ .string()
271
+ .trim()
272
+ .min(1)
273
+ .max(255)
274
+ .optional()
275
+ .describe("Slug or UUID, same polymorphic addressing as project_tasks's `project`. Alternative to projectId/projectSlug. Pass exactly one of project, projectId, or projectSlug. Trimmed and length-capped (max 255) like projectSlug, so the two slug-accepting fields share the same input hygiene. A UUID-shaped value is routed straight to the id endpoint and never treated as a slug -- if this project's slug is itself UUID-shaped, pass it via projectSlug instead, which is always resolved as a slug."),
276
+ projectId: uuid().optional(),
277
+ projectSlug: z
278
+ .string()
279
+ .trim()
280
+ .min(1)
281
+ .max(255)
282
+ .optional()
283
+ .describe("Slug-only alternative to projectId. Resolved mcp-server-side via a TTL-cached slug lookup. Pass exactly one of project, projectId, or projectSlug."),
106
284
  title: z.string().min(1).max(255),
107
285
  description: z.string().optional(),
108
286
  priority: priorityEnum.optional(),
@@ -124,12 +302,56 @@ export function buildTools(client) {
124
302
  .regex(/^[^/\s]+\/[^/\s]+$/, "Expected 'owner/repo'")
125
303
  .optional()
126
304
  .describe("Cross-repo deliverable override ('owner/repo'). Set only when this task's legitimate deliverable is a PR in a DIFFERENT GitHub repo than the project's linked githubRepo (benchmark/measurement/docs tasks) — the cross-repo PR guard and merge automation then key off this repo instead. Post-create changes are project-admin-only (human, PATCH); agents cannot retarget it later."),
305
+ include: includeSchema,
306
+ },
307
+ handler: async ({ project, projectId, projectSlug, include, ...input }) => {
308
+ // rc-v1-C006 (extended for the unified `project` field): addressing
309
+ // validation happens here, before any network call, same pattern as
310
+ // task_respec's own client-side "at least one of" guard below —
311
+ // except CONFLICT is a proper teaching error per the task spec, not
312
+ // a bare thrown message. Checked pairwise so the message names the
313
+ // two fields that actually collided, not a generic "more than one".
314
+ if (project !== undefined && projectId !== undefined) {
315
+ throw new Error(serializeTeachingError(projectAddressingConflictError("task_create", "project_and_projectId")));
316
+ }
317
+ if (project !== undefined && projectSlug !== undefined) {
318
+ throw new Error(serializeTeachingError(projectAddressingConflictError("task_create", "project_and_projectSlug")));
319
+ }
320
+ if (projectId !== undefined && projectSlug !== undefined) {
321
+ throw new Error(serializeTeachingError(projectAddressingConflictError("task_create")));
322
+ }
323
+ if (project === undefined && projectId === undefined && projectSlug === undefined) {
324
+ throw new Error(serializeTeachingError(projectAddressingConflictError("task_create", "neither_provided")));
325
+ }
326
+ let response;
327
+ try {
328
+ response =
329
+ project !== undefined
330
+ ? await wrap(() => client.createTaskByProject(project, input))
331
+ : projectId !== undefined
332
+ ? await wrap(() => client.createTask(projectId, input))
333
+ : await wrap(() => client.createTaskByProjectSlug(projectSlug, input));
334
+ }
335
+ catch (err) {
336
+ // ProjectSlugNotFoundError is raised by client.ts's resolver on a
337
+ // FRESH 404 (not a stale cache entry — that case is retried
338
+ // internally and never reaches here). wrap() does not translate
339
+ // it (it is not an AgentTasksApiError), so it is caught here and
340
+ // mapped to the specific unknown_project_slug teaching error
341
+ // instead of leaking a raw, non-JSON error message.
342
+ if (err instanceof ProjectSlugNotFoundError) {
343
+ throw new Error(serializeTeachingError(unknownProjectSlugError(err.slug, "task_create")));
344
+ }
345
+ throw err;
346
+ }
347
+ if (include?.includes("task"))
348
+ return response;
349
+ return receiptForCreate(response, input);
127
350
  },
128
- handler: async ({ projectId, ...input }) => wrap(() => client.createTask(projectId, input)),
129
351
  }),
130
352
  def({
131
353
  name: "task_respec",
132
- description: "Edit an OPEN, UNCLAIMED task's description and/or structured templateData in place — fix a low-confidence or under-specified spec instead of abandoning and recreating the task. Wraps POST /api/tasks/:id/respec. Requires at least one of description or templateData (checked client-side before the request, and enforced authoritatively by the backend with 400 — the backend also rejects empty values: a blank/whitespace-only description, or an empty templateData object). templateData is a WHOLESALE REPLACE of the task's stored templateData, not a merge — send the full object you want stored. By default only the task's creator may respec it; a project admin can relax this via project.allowNonCreatorRespec (403 otherwise; missing tasks:update scope for agent callers is also 403). Any task that is claimed (work or review) or not status=open is rejected with 409 'Task must be open and unclaimed to respec'. 404 if the task does not exist. Response is { task, confidence } — confidence is freshly re-scored by the backend on the STORED (new) values and uses the same shape as task_create's create-time confidence: { score, threshold, enforcementMode, blocking, missing, findings, nextActions }. A call that would not actually change anything (same values resubmitted) is a no-op: no write, no audit entry, current task + confidence returned.",
354
+ description: "Edit an OPEN, UNCLAIMED task's description and/or structured templateData in place — fix a low-confidence or under-specified spec instead of abandoning and recreating the task. Wraps POST /api/tasks/:id/respec. Requires at least one of description or templateData (checked client-side before the request, and enforced authoritatively by the backend with 400 — the backend also rejects empty values: a blank/whitespace-only description, or an empty templateData object). templateData is a WHOLESALE REPLACE of the task's stored templateData, not a merge — send the full object you want stored. By default only the task's creator may respec it; a project admin can relax this via project.allowNonCreatorRespec (403 otherwise; missing tasks:update scope for agent callers is also 403). Any task that is claimed (work or review) or not status=open is rejected with 409 'Task must be open and unclaimed to respec'. 404 if the task does not exist. A call that would not actually change anything (same values resubmitted) is a no-op: no write, no audit entry.\n\nReturns a receipt by default ({ ok, task: { id, status }, confidence: <score>, deviations? }) — description/templateData are NOT echoed back. confidence is freshly re-scored on the STORED (new) values; a CONFIDENCE_BELOW_THRESHOLD deviation appears when the new score is still below threshold. Pass include:[\"task\"] for the full { task, confidence } object (confidence there keeps its detailed shape: { score, threshold, enforcementMode, blocking, missing, findings, nextActions }).",
133
355
  inputShape: {
134
356
  taskId: uuid(),
135
357
  description: z
@@ -140,8 +362,9 @@ export function buildTools(client) {
140
362
  .record(z.string(), z.unknown())
141
363
  .optional()
142
364
  .describe("Replacement structured spec fields (same shape as task_create's templateData: goal, acceptanceCriteria, context, constraints, scope, outOfScope, dependencies, risk, agentPrompt, taskType, prefers). This WHOLESALE REPLACES the task's stored templateData — it is not merged with the existing value. Backend rejects an empty object with 400. At least one of description or templateData is required."),
365
+ include: includeSchema,
143
366
  },
144
- handler: async ({ taskId, description, templateData }) => {
367
+ handler: async ({ taskId, description, templateData, include }) => {
145
368
  if (description === undefined && templateData === undefined) {
146
369
  throw new Error("task_respec requires at least one of description or templateData");
147
370
  }
@@ -150,18 +373,47 @@ export function buildTools(client) {
150
373
  body.description = description;
151
374
  if (templateData !== undefined)
152
375
  body.templateData = templateData;
153
- return wrap(() => client.respecTask(taskId, body));
376
+ const response = await wrap(() => client.respecTask(taskId, body));
377
+ if (include?.includes("task"))
378
+ return response;
379
+ return receiptForRespec(response);
154
380
  },
155
381
  }),
156
382
  def({
157
383
  name: "task_abandon",
158
- description: "Explicit bail-out: release the active claim on a task without finishing. A work claim on an in_progress task returns it to open; a review claim simply releases the review lock. Use this sparingly — task_finish is the normal path. Separate intent from finish so audit trails distinguish abandonment from completion.",
159
- inputShape: { taskId: uuid() },
160
- handler: async ({ taskId }) => wrap(() => client.abandonTask(taskId)),
384
+ description: "Explicit bail-out: release the active claim on a task without finishing. A work claim on an in_progress task returns it to open; a review claim simply releases the review lock. Use this sparingly — task_finish is the normal path. Separate intent from finish so audit trails distinguish abandonment from completion.\n\nReturns a receipt by default ({ ok, task: { id, status } }). Pass include:[\"task\"] for the full backend object.",
385
+ inputShape: { taskId: uuid(), include: includeSchema },
386
+ handler: async ({ taskId, include }) => {
387
+ const response = await wrap(() => client.abandonTask(taskId));
388
+ if (include?.includes("task"))
389
+ return response;
390
+ return receiptForAbandon(response);
391
+ },
392
+ }),
393
+ def({
394
+ name: "task_creator_abandon",
395
+ description: "Retire an OPEN, UNCLAIMED task you created into status=abandoned, for the case where the task itself was a mistake (e.g. filed in the wrong project) rather than work you started and gave up on. Distinct from task_abandon: that verb releases a CLAIM (work or review) you currently hold; this verb never requires a claim and instead ends the task's lifecycle outright. Typical use: you filed a task in the wrong project, re-filed the correct one, and now need to retire the original so it stops showing up as an open duplicate. Wraps POST /api/tasks/:id/creator-abandon.\n\nNarrow authz, no relaxation and no force: only the task's own creator may call this (403 otherwise), and the task must still be status=open with no work or review claim held by anyone (409 'Task must be open and unclaimed to creator-abandon' otherwise). Agent-only, requires the tasks:update scope; humans have DELETE for this case instead. 404 if the task does not exist. Optional `reason` is recorded on the audit trail but not required.\n\nNot a dead end: abandoned is recoverable only by a project admin, via a status PATCH to the workflow's initial state (no agent path, and no other target status is allowed).\n\nReturns a receipt by default ({ ok, task: { id, status } }). Pass include:[\"task\"] for the full backend object.",
396
+ inputShape: {
397
+ taskId: uuid(),
398
+ reason: z
399
+ .string()
400
+ .trim()
401
+ .min(1)
402
+ .max(2000)
403
+ .optional()
404
+ .describe("Optional free-text reason, recorded on the audit trail (e.g. 'refiled as <taskId> in the correct project')."),
405
+ include: includeSchema,
406
+ },
407
+ handler: async ({ taskId, reason, include }) => {
408
+ const response = await wrap(() => client.creatorAbandonTask(taskId, reason !== undefined ? { reason } : undefined));
409
+ if (include?.includes("task"))
410
+ return response;
411
+ return receiptForAbandon(response);
412
+ },
161
413
  }),
162
414
  def({
163
415
  name: "task_submit_pr",
164
- description: "Record the branch + pull request metadata on a work-claimed task. Atomic metadata write, not a state transition. Use this after `gh pr create` to satisfy the `branchPresent` / `prPresent` workflow gates before calling task_finish. The canonical v2 flow for projects that enforce branch gates is: task_start → (work + gh pr create) → task_submit_pr → task_finish. For projects that only need prPresent, the shorthand `task_finish { prUrl }` still works and this verb is optional. This is the v2-native replacement for the deprecated v1 `tasks_update { branchName, prUrl, prNumber }` path, which is being sunset 4 weeks after 2026-04-15. Re-submission is allowed and overwrites the prior values (supports the request_changes rework loop). Caller must hold the work claim; task must be in a non-terminal state and not `open`. Cross-repo hardening: prUrl must point at the same repo as project.githubRepo; mismatches are rejected with 400 cross_repo_pr_rejected. Authorship verification: the PR must be authored by the delegation user; mismatches are rejected with 403 pr_author_mismatch (fails open on GitHub API errors).",
416
+ description: "Record the branch + pull request metadata on a work-claimed task. Atomic metadata write, not a state transition. Use this after `gh pr create` to satisfy the `branchPresent` / `prPresent` workflow gates before calling task_finish. The canonical v2 flow for projects that enforce branch gates is: task_start → (work + gh pr create) → task_submit_pr → task_finish. For projects that only need prPresent, the shorthand `task_finish { prUrl }` still works and this verb is optional. This is the v2-native replacement for the v1 `tasks_update { branchName, prUrl, prNumber }` path, pruned from the default tool registration by rc-v1-C007 and reachable only with AGENT_TASKS_MCP_LEGACY=1 set. Re-submission is allowed and overwrites the prior values (supports the request_changes rework loop). Caller must hold the work claim; task must be in a non-terminal state and not `open`. Cross-repo hardening: prUrl must point at the same repo as project.githubRepo; mismatches are rejected with 400 cross_repo_pr_rejected. Authorship verification: the PR must be authored by the delegation user; mismatches are rejected with 403 pr_author_mismatch (fails open on GitHub API errors).\n\nReturns a receipt by default ({ ok, task: { id, status }, next: [\"task_finish once CI is green\"] }). Not a state transition, so no `transition` field. Pass include:[\"task\"] for the full backend object.",
165
417
  inputShape: {
166
418
  taskId: uuid(),
167
419
  branchName: z.string().trim().min(1).max(255),
@@ -169,8 +421,14 @@ export function buildTools(client) {
169
421
  .string()
170
422
  .regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+(?:[/?#].*)?$/, "prUrl must be a github.com pull request URL"),
171
423
  prNumber: z.number().int().positive(),
424
+ include: includeSchema,
425
+ },
426
+ handler: async ({ taskId, include, ...input }) => {
427
+ const response = await wrap(() => client.submitPr(taskId, input));
428
+ if (include?.includes("task"))
429
+ return response;
430
+ return receiptForSubmitPr(response);
172
431
  },
173
- handler: async ({ taskId, ...input }) => wrap(() => client.submitPr(taskId, input)),
174
432
  }),
175
433
  // ── Artifacts (v2) ───────────────────────────────────────────────────
176
434
  //
@@ -257,12 +515,18 @@ export function buildTools(client) {
257
515
  // `requireDistinctReviewer` unless `soloMode` is on — see task_merge.
258
516
  def({
259
517
  name: "task_merge",
260
- description: "Merge the PR attached to a task. Task-scoped verb (not a GitHub-identifier verb): derives owner/repo/PR number from the task/project metadata and uses the team's GitHub delegation. Requires `github:pr_merge` scope for agent callers, and — when `project.requireDistinctReviewer` is enabled and the project is not in `soloMode` — refuses with 403 `self_merge_blocked` if the caller also holds the work claim. Idempotent on an already-merged PR (task stays at `done`).",
518
+ description: "Merge the PR attached to a task. Task-scoped verb (not a GitHub-identifier verb): derives owner/repo/PR number from the task/project metadata and uses the team's GitHub delegation. Requires `github:pr_merge` scope for agent callers, and, when `project.requireDistinctReviewer` is enabled and the project is not in `soloMode`, refuses with 403 `self_merge_blocked` if the caller also holds the work claim. Idempotent on an already-merged PR (task stays at `done`).\n\nReturns a receipt by default ({ ok, task: { id, status } }), no `transition` field: the route accepts both `review` and an idempotent `done` retry as valid starting states, and the backend's `alreadyMerged` flag describes the GitHub PR's own merge state, not whether a DB transition happened on this call, so the receipt reports the outcome via `task.status` alone. Pass include:[\"task\"] for the full { task, merged, sha, alreadyMerged } object.",
261
519
  inputShape: {
262
520
  taskId: uuid(),
263
521
  mergeMethod: z.enum(["squash", "merge", "rebase"]).optional(),
522
+ include: includeSchema,
523
+ },
524
+ handler: async ({ taskId, mergeMethod, include }) => {
525
+ const response = await wrap(() => client.mergeTask(taskId, mergeMethod));
526
+ if (include?.includes("task"))
527
+ return response;
528
+ return receiptForMerge(response);
264
529
  },
265
- handler: async ({ taskId, mergeMethod }) => wrap(() => client.mergeTask(taskId, mergeMethod)),
266
530
  }),
267
531
  // ── v1 surface (deprecated) ──────────────────────────────────────────
268
532
  def({
@@ -275,28 +539,35 @@ export function buildTools(client) {
275
539
  def({
276
540
  name: "projects_get",
277
541
  description: DEPRECATED +
278
- "Fetch a single project by slug or id. Project browsing is not an agent concern under v2. The non-deprecated use is the `effectiveGates` and `taskCreation` fields in the response — call `projects_get_effective_gates` for a leaner payload that carries both.",
542
+ "Fetch a single project by slug or id. Project browsing is not an agent concern under v2. The non-deprecated use is the `effectiveGates` and `taskCreation` fields in the response (taskCreation includes a per-task-type `taskTypeThresholds` summary with { effectiveThreshold, thresholdSource }) — call `projects_get_effective_gates` for a leaner payload that carries both.",
279
543
  inputShape: { slugOrId: z.string().min(1) },
280
544
  handler: async ({ slugOrId }) => wrap(() => client.getProject(slugOrId)),
281
545
  }),
282
546
  def({
283
547
  name: "projects_get_effective_gates",
284
- description: "Return the gate map for a project. Each entry is keyed by `GateCode` (e.g. `distinct_reviewer`, `self_merge`, `task_status_for_merge`, `pr_repo_matches_project`) and carries `active` (whether this gate would evaluate on this project), `because` (why — e.g. governance mode, project binding), and `appliesTo` (the verb names the gate can reject). Use it to answer 'will this verb be blocked?' BEFORE making the call, instead of discovering preconditions by tripping a 4xx. The response also carries a `taskCreation` block ({ enforcementMode, confidenceThreshold, templateModeEnabled, requiredFields[] }): call it BEFORE task_create to learn whether task-template mode is on and which structured templateData fields this project requires.",
548
+ description: "Return the gate map for a project. Each entry is keyed by `GateCode` (e.g. `distinct_reviewer`, `self_merge`, `task_status_for_merge`, `pr_repo_matches_project`) and carries `active` (whether this gate would evaluate on this project), `because` (why — e.g. governance mode, project binding), and `appliesTo` (the verb names the gate can reject). Use it to answer 'will this verb be blocked?' BEFORE making the call, instead of discovering preconditions by tripping a 4xx. The response also carries a `taskCreation` block ({ enforcementMode, confidenceThreshold, templateModeEnabled, requiredFields[], taskTypeThresholds }): call it BEFORE task_create to learn whether task-template mode is on, which structured templateData fields this project requires, and the effective per-task-type confidence threshold ({ effectiveThreshold, thresholdSource } per type) so the per-type gate value is visible BEFORE the create, not only after.",
285
549
  inputShape: { projectId: uuid() },
286
550
  handler: async ({ projectId }) => wrap(() => client.getProjectEffectiveGates(projectId)),
287
551
  }),
288
552
  def({
289
553
  name: "project_tasks",
290
- description: "Browse tasks scoped to a single project. Use this when you want to answer 'what is open in project X?' (the question task_pickup and the deprecated tasks_list cannot reliably answer — pickup returns one item, tasks_list returns only the claimable slice). " +
291
- "`project` accepts a slug ('agent-tasks') or a UUID; slugs are resolved server-side so you do not need to chain projects_get first. " +
292
- "Filters (status, priority, labels, unclaimed) combine with AND semantics; status and priority accept either a single value or an array. limit defaults to unbounded on the backend, but clamps to 500 if supplied — pass an explicit limit when calling from an LLM harness so the response stays inside the tool-result token cap.",
554
+ description: "Browse tasks scoped to a single project. Use this when you want to answer 'what is open in project X?' (a question task_pickup cannot answer on its own, since it returns one prioritized item, not a browsable list). " +
555
+ "`project` accepts a slug ('agent-tasks') or a UUID; slugs are resolved mcp-server-side (TTL-cached, ~15 min, rc-v1-C006), no separate lookup call needed. An unresolvable slug is an unknown_project_slug teaching error whose recipe asks the operator for the correct slug or id (or, with AGENT_TASKS_MCP_LEGACY=1 set, call projects_list). " +
556
+ "Filters (status, priority, labels, unclaimed) combine with AND semantics; status and priority accept either a single value or an array. limit defaults to unbounded on the backend, but clamps to 500 if supplied — pass an explicit limit when calling from an LLM harness so the response stays inside the tool-result token cap. " +
557
+ "DEFAULT sort is `createdAt:desc` (newest tasks first) — pass `sort: \"createdAt:asc\"` to reverse it. Combined with a small `limit`, the default lets you fetch the N newest open tasks in a single call without blowing the tool-result token cap. " +
558
+ "The response carries `nextCursor` (a task id, or null once the last page is reached) — pass it back as `cursor` to page forward; combined with `sort` + `id` as a tiebreaker, page order is stable even when many tasks share the same createdAt timestamp.",
293
559
  inputShape: {
294
- project: z.string().min(1),
560
+ project: z
561
+ .string()
562
+ .trim()
563
+ .min(1)
564
+ .max(255)
565
+ .describe("Slug or UUID; trimmed and length-capped (max 255), same input hygiene as task_create's project/projectSlug fields. A UUID-shaped value is routed straight to the id endpoint and never treated as a slug -- if this project's slug is itself UUID-shaped, it cannot be addressed via this field."),
295
566
  status: z
296
567
  .union([
297
- z.enum(["open", "in_progress", "review", "done", "abandoned"]),
568
+ z.enum(["open", "in_progress", "review", "done", "abandoned", "backlog"]),
298
569
  z
299
- .array(z.enum(["open", "in_progress", "review", "done", "abandoned"]))
570
+ .array(z.enum(["open", "in_progress", "review", "done", "abandoned", "backlog"]))
300
571
  .min(1),
301
572
  ])
302
573
  .optional(),
@@ -306,14 +577,39 @@ export function buildTools(client) {
306
577
  labels: z.array(z.string().min(1).max(100)).min(1).max(20).optional(),
307
578
  unclaimed: z.boolean().optional(),
308
579
  limit: z.number().int().positive().max(500).optional(),
580
+ sort: z
581
+ .enum(["createdAt:asc", "createdAt:desc"])
582
+ .default("createdAt:desc")
583
+ .describe("Only `createdAt` is sortable. Default `createdAt:desc` (newest first) — matches this route's backend default, and is the recommended setting for browsing recently-triaged tasks under the token cap."),
584
+ cursor: z
585
+ .string()
586
+ .min(1)
587
+ .optional()
588
+ .describe("Task id to page forward from — pass the previous call's `nextCursor`. Omit for the first page."),
589
+ },
590
+ handler: async ({ project, status, priority, labels, unclaimed, limit, sort, cursor }) => {
591
+ try {
592
+ return await wrap(() => client.listProjectTasks(project, {
593
+ status,
594
+ priority,
595
+ labels,
596
+ unclaimed,
597
+ limit,
598
+ sort,
599
+ cursor,
600
+ }));
601
+ }
602
+ catch (err) {
603
+ // Same rc-v1-C006 mapping as task_create's own projectSlug path:
604
+ // client.ts's resolver throws ProjectSlugNotFoundError (not an
605
+ // AgentTasksApiError, so wrap() does not touch it) on a fresh
606
+ // 404, translated here to the specific teaching error.
607
+ if (err instanceof ProjectSlugNotFoundError) {
608
+ throw new Error(serializeTeachingError(unknownProjectSlugError(err.slug, "project_tasks")));
609
+ }
610
+ throw err;
611
+ }
309
612
  },
310
- handler: async ({ project, status, priority, labels, unclaimed, limit }) => wrap(() => client.listProjectTasks(project, {
311
- status,
312
- priority,
313
- labels,
314
- unclaimed,
315
- limit,
316
- })),
317
613
  }),
318
614
  def({
319
615
  name: "tasks_list",
@@ -322,14 +618,16 @@ export function buildTools(client) {
322
618
  "For 'what is open in project X' use project_tasks (the browse-scoped verb). " +
323
619
  "Pass status/priority/labels/claimedByAgentId/projectId to broaden the search; verbose=true switches to the full task payload " +
324
620
  "(default returns a summary projection without descriptions/comments to stay inside the harness's tool-result token cap). " +
325
- "claimedByAgentId='me' resolves to the calling agent's tokenId. Default limit 25.",
621
+ "claimedByAgentId='me' resolves to the calling agent's tokenId. Default limit 25. " +
622
+ "DEFAULT sort is `createdAt:desc` (newest tasks first) — the backend API itself still defaults to `createdAt:asc` for backward compatibility, but this tool overrides that at the tool layer so calling with no `sort` returns the N most-recently-created tasks, not the oldest. Pass `sort: \"createdAt:asc\"` to get the old behavior back. " +
623
+ "The response carries `nextCursor` (a task id, or null once the last page is reached) — pass it back as `cursor` to page forward through more results than fit in one call, instead of raising `limit` past the token cap.",
326
624
  inputShape: {
327
625
  limit: z.number().int().positive().max(200).optional(),
328
626
  projectId: uuid().optional(),
329
627
  status: z
330
628
  .union([
331
- z.enum(["open", "in_progress", "review", "done", "abandoned"]),
332
- z.array(z.enum(["open", "in_progress", "review", "done", "abandoned"])).min(1),
629
+ z.enum(["open", "in_progress", "review", "done", "abandoned", "backlog"]),
630
+ z.array(z.enum(["open", "in_progress", "review", "done", "abandoned", "backlog"])).min(1),
333
631
  ])
334
632
  .optional(),
335
633
  priority: z
@@ -338,15 +636,26 @@ export function buildTools(client) {
338
636
  labels: z.array(z.string().min(1).max(100)).min(1).max(20).optional(),
339
637
  claimedByAgentId: z.union([uuid(), z.literal("me")]).optional(),
340
638
  verbose: z.boolean().optional(),
639
+ sort: z
640
+ .enum(["createdAt:asc", "createdAt:desc"])
641
+ .default("createdAt:desc")
642
+ .describe("Only `createdAt` is sortable. Default `createdAt:desc` (newest first) — a tool-layer override of the backend's `createdAt:asc` API default, so the N newest tasks are reachable in one call under the token cap."),
643
+ cursor: z
644
+ .string()
645
+ .min(1)
646
+ .optional()
647
+ .describe("Task id to page forward from — pass the previous call's `nextCursor`. Omit for the first page."),
341
648
  },
342
649
  handler: async (args) => wrap(() => client.listClaimableTasks(args)),
343
650
  }),
344
651
  def({
345
652
  name: "tasks_get",
346
- description: DEPRECATED +
347
- "Fetch a task by id. v2 folds this into the task_start response.",
348
- inputShape: { taskId: uuid() },
349
- handler: async ({ taskId }) => wrap(() => client.getTask(taskId)),
653
+ description: "Fetch a task by id. The modern read-verb surface (rc-v1-C006): task_start folds its own task-scoped slice of this into its receipt, but this is the general-purpose read. Returns a summary projection by default (id, title, status, priority, labels, claims, blockedBy, prUrl), pass include:[\"description\" | \"comments\" | \"artifacts\"] to add one field back, or include:[\"task\"] for the full, pre-contract object.",
654
+ inputShape: { taskId: uuid(), include: readIncludeSchema },
655
+ handler: async ({ taskId, include }) => {
656
+ const response = await wrap(() => client.getTask(taskId));
657
+ return projectTaskSummary(response, include);
658
+ },
350
659
  }),
351
660
  def({
352
661
  name: "tasks_instructions",
@@ -380,7 +689,7 @@ export function buildTools(client) {
380
689
  description: DEPRECATED +
381
690
  "Use task_start instead (atomic claim + in_progress + instructions).",
382
691
  inputShape: { taskId: uuid() },
383
- handler: async ({ taskId }) => wrap(() => client.claimTask(taskId)),
692
+ handler: async ({ taskId }) => wrap(() => client.claimTask(taskId), "tasks_claim"),
384
693
  }),
385
694
  def({
386
695
  name: "tasks_release",
@@ -399,7 +708,7 @@ export function buildTools(client) {
399
708
  force: z.boolean().optional(),
400
709
  forceReason: z.string().max(500).optional(),
401
710
  },
402
- handler: async ({ taskId, ...input }) => wrap(() => client.transitionTask(taskId, input)),
711
+ handler: async ({ taskId, ...input }) => wrap(() => client.transitionTask(taskId, input), "tasks_transition"),
403
712
  }),
404
713
  def({
405
714
  name: "tasks_update",
@@ -410,19 +719,38 @@ export function buildTools(client) {
410
719
  branchName: z.string().max(255).nullable().optional(),
411
720
  prUrl: z.string().url().nullable().optional(),
412
721
  prNumber: z.number().int().positive().nullable().optional(),
413
- result: z.string().nullable().optional(),
722
+ // Symmetry with task_finish's own result field (same field, same
723
+ // storage): uncapped here let a caller feed an arbitrarily large
724
+ // string straight into looksLikeStructuredWrapper's tag-pair scan
725
+ // before this cap was added (measured: 18,395ms on a 400k-char
726
+ // adversarial input against the pre-cap guard alone).
727
+ result: z.string().max(5000).nullable().optional(),
728
+ },
729
+ handler: async ({ taskId, ...input }) => {
730
+ // Same pre-network guard as task_finish's own result field
731
+ // (errors.ts catalog entry #8): tasks_update writes `result` the
732
+ // same way the backend stores it, so the same XML/JSON-wrapper
733
+ // mistake needs the same check here, not just on the v2 verb.
734
+ if (typeof input.result === "string" && looksLikeStructuredWrapper(input.result)) {
735
+ throw new Error(serializeTeachingError(resultMustBePlainStringError("tasks_update")));
736
+ }
737
+ return wrap(() => client.updateTask(taskId, input), "tasks_update");
414
738
  },
415
- handler: async ({ taskId, ...input }) => wrap(() => client.updateTask(taskId, input)),
416
739
  }),
417
740
  def({
418
741
  name: "tasks_comment",
419
- description: DEPRECATED +
420
- "Use task_note instead (same behavior, v2 naming).",
742
+ description: "First-class alias of task_note (same behavior, v2 naming, including the receipt default). Kept in the default registration permanently for naming-convention compatibility; not part of rc-v1-C007's pruned legacy set.",
421
743
  inputShape: {
422
744
  taskId: uuid(),
423
745
  content: z.string().min(1).max(5000),
746
+ include: includeSchema,
747
+ },
748
+ handler: async ({ taskId, content, include }) => {
749
+ const response = await wrap(() => client.addTaskComment(taskId, content));
750
+ if (include?.includes("task"))
751
+ return response;
752
+ return receiptForNote(taskId, response);
424
753
  },
425
- handler: async ({ taskId, content }) => wrap(() => client.addTaskComment(taskId, content)),
426
754
  }),
427
755
  def({
428
756
  name: "review_approve",
@@ -460,15 +788,30 @@ export function buildTools(client) {
460
788
  }),
461
789
  def({
462
790
  name: "signals_poll",
463
- description: DEPRECATED +
464
- "Signals are delivered inline by task_pickup under v2.",
465
- inputShape: {},
466
- handler: async () => wrap(() => client.pollSignals()),
791
+ description: `Signals are also delivered inline by task_pickup under v2; call this verb directly when you want to check the signal inbox without also claiming a task. Default limit ${SIGNALS_DEFAULT_LIMIT} (max ${SIGNALS_MAX_LIMIT}); when more are pending within the fetched batch the response carries truncated:true and a cursor (the last delivered signal's id). Pass it back as cursor on the next call to fetch the remainder. mcp-server always fetches up to ${SIGNALS_BACKEND_FETCH_LIMIT} pending signals from the backend per call (its own hard max; the backend has no cursor of its own). When the backend backlog is at or above that ceiling, the response also carries atBackendFetchCeiling:true: more signals may exist beyond what this call could see, even once truncated stops appearing, so ack what you have and poll again rather than assuming the backlog is drained. A cursor whose signal was acked or aged out of the backend's fetch window restarts from the oldest pending signal, so an occasional duplicate delivery is possible; treat acking as idempotent.`,
792
+ inputShape: {
793
+ limit: z
794
+ .number()
795
+ .int()
796
+ .positive()
797
+ .max(SIGNALS_MAX_LIMIT)
798
+ .optional()
799
+ .describe(`Max signals to return this call. Default ${SIGNALS_DEFAULT_LIMIT}.`),
800
+ cursor: z
801
+ .string()
802
+ .min(1)
803
+ .optional()
804
+ .describe("Signal id to resume after — pass the previous call's cursor. Omit for the first page."),
805
+ },
806
+ handler: async ({ limit, cursor }) => {
807
+ const response = await wrap(() => client.pollSignals(SIGNALS_BACKEND_FETCH_LIMIT));
808
+ const all = response?.signals ?? [];
809
+ return paginateSignals(all, { cursor, limit });
810
+ },
467
811
  }),
468
812
  def({
469
813
  name: "signals_ack",
470
- description: DEPRECATED +
471
- "Signals are acked atomically when delivered by task_pickup under v2.",
814
+ description: "Acknowledge a signal fetched via signals_poll (signals delivered inline by task_pickup under v2 are acked atomically instead, no separate call needed).",
472
815
  inputShape: { signalId: uuid() },
473
816
  handler: async ({ signalId }) => wrap(() => client.ackSignal(signalId)),
474
817
  }),
@@ -485,7 +828,7 @@ export function buildTools(client) {
485
828
  body: z.string().optional(),
486
829
  idempotencyKey: z.string().trim().min(1).max(255).optional(),
487
830
  },
488
- handler: async (input) => wrap(() => client.createPullRequest(input)),
831
+ handler: async (input) => wrap(() => client.createPullRequest(input), "pull_requests_create"),
489
832
  }),
490
833
  def({
491
834
  name: "pull_requests_merge",
@@ -522,5 +865,9 @@ export function buildTools(client) {
522
865
  handler: async (input) => wrap(() => client.commentOnPullRequest(input)),
523
866
  }),
524
867
  ];
868
+ // rc-v1-C007: registration-time filter only. Every handler above stays
869
+ // fully defined regardless of `options.legacy`; { legacy: true } is the
870
+ // only thing that changes which of them end up in the returned array.
871
+ return options?.legacy ? tools : tools.filter((t) => !LEGACY_VERB_NAMES.has(t.name));
525
872
  }
526
873
  //# sourceMappingURL=tools.js.map