@agent-tasks/mcp-server 0.12.0 → 0.13.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 task_finish or task_abandon first.\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 }, expectedFinishState, gateExpectations?, gateExpectationsSource?, 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. gateExpectationsSource is set to \"assumed-default-workflow\" when gateExpectations came from the static built-in-default fallback rather than this project's own workflow definition, since a null workflowId can also mean a customized project-default workflow. 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,35 @@ 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 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 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. When a project uses task-template mode, call projects_get_effective_gates first and populate the templateData fields it lists under taskCreation.requiredFields.\n\nprojectSlug (rc-v1-C006) is an alternative to projectId: resolved to a project id mcp-server-side via an internal TTL-cached slug lookup (~15 min, invalidated and retried once if the cached id 404s downstream). Passing both projectId and projectSlug is a project_addressing_conflict teaching error; a projectSlug 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
+ projectId: uuid().optional(),
270
+ projectSlug: z
271
+ .string()
272
+ .trim()
273
+ .min(1)
274
+ .max(255)
275
+ .optional()
276
+ .describe("Alternative to projectId. Resolved mcp-server-side via a TTL-cached slug lookup. Pass exactly one of projectId or projectSlug."),
106
277
  title: z.string().min(1).max(255),
107
278
  description: z.string().optional(),
108
279
  priority: priorityEnum.optional(),
@@ -124,12 +295,46 @@ export function buildTools(client) {
124
295
  .regex(/^[^/\s]+\/[^/\s]+$/, "Expected 'owner/repo'")
125
296
  .optional()
126
297
  .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."),
298
+ include: includeSchema,
299
+ },
300
+ handler: async ({ projectId, projectSlug, include, ...input }) => {
301
+ // rc-v1-C006: projectId/projectSlug validation happens here, before
302
+ // any network call, same pattern as task_respec's own client-side
303
+ // "at least one of" guard below — except CONFLICT is a proper
304
+ // teaching error per the task spec, not a bare thrown message.
305
+ if (projectId !== undefined && projectSlug !== undefined) {
306
+ throw new Error(serializeTeachingError(projectAddressingConflictError("task_create")));
307
+ }
308
+ if (projectId === undefined && projectSlug === undefined) {
309
+ throw new Error(serializeTeachingError(projectAddressingConflictError("task_create", "neither_provided")));
310
+ }
311
+ let response;
312
+ try {
313
+ response =
314
+ projectId !== undefined
315
+ ? await wrap(() => client.createTask(projectId, input))
316
+ : await wrap(() => client.createTaskByProjectSlug(projectSlug, input));
317
+ }
318
+ catch (err) {
319
+ // ProjectSlugNotFoundError is raised by client.ts's resolver on a
320
+ // FRESH 404 (not a stale cache entry — that case is retried
321
+ // internally and never reaches here). wrap() does not translate
322
+ // it (it is not an AgentTasksApiError), so it is caught here and
323
+ // mapped to the specific unknown_project_slug teaching error
324
+ // instead of leaking a raw, non-JSON error message.
325
+ if (err instanceof ProjectSlugNotFoundError) {
326
+ throw new Error(serializeTeachingError(unknownProjectSlugError(err.slug, "task_create")));
327
+ }
328
+ throw err;
329
+ }
330
+ if (include?.includes("task"))
331
+ return response;
332
+ return receiptForCreate(response, input);
127
333
  },
128
- handler: async ({ projectId, ...input }) => wrap(() => client.createTask(projectId, input)),
129
334
  }),
130
335
  def({
131
336
  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.",
337
+ 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
338
  inputShape: {
134
339
  taskId: uuid(),
135
340
  description: z
@@ -140,8 +345,9 @@ export function buildTools(client) {
140
345
  .record(z.string(), z.unknown())
141
346
  .optional()
142
347
  .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."),
348
+ include: includeSchema,
143
349
  },
144
- handler: async ({ taskId, description, templateData }) => {
350
+ handler: async ({ taskId, description, templateData, include }) => {
145
351
  if (description === undefined && templateData === undefined) {
146
352
  throw new Error("task_respec requires at least one of description or templateData");
147
353
  }
@@ -150,18 +356,26 @@ export function buildTools(client) {
150
356
  body.description = description;
151
357
  if (templateData !== undefined)
152
358
  body.templateData = templateData;
153
- return wrap(() => client.respecTask(taskId, body));
359
+ const response = await wrap(() => client.respecTask(taskId, body));
360
+ if (include?.includes("task"))
361
+ return response;
362
+ return receiptForRespec(response);
154
363
  },
155
364
  }),
156
365
  def({
157
366
  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)),
367
+ 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.",
368
+ inputShape: { taskId: uuid(), include: includeSchema },
369
+ handler: async ({ taskId, include }) => {
370
+ const response = await wrap(() => client.abandonTask(taskId));
371
+ if (include?.includes("task"))
372
+ return response;
373
+ return receiptForAbandon(response);
374
+ },
161
375
  }),
162
376
  def({
163
377
  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).",
378
+ 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
379
  inputShape: {
166
380
  taskId: uuid(),
167
381
  branchName: z.string().trim().min(1).max(255),
@@ -169,8 +383,14 @@ export function buildTools(client) {
169
383
  .string()
170
384
  .regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+(?:[/?#].*)?$/, "prUrl must be a github.com pull request URL"),
171
385
  prNumber: z.number().int().positive(),
386
+ include: includeSchema,
387
+ },
388
+ handler: async ({ taskId, include, ...input }) => {
389
+ const response = await wrap(() => client.submitPr(taskId, input));
390
+ if (include?.includes("task"))
391
+ return response;
392
+ return receiptForSubmitPr(response);
172
393
  },
173
- handler: async ({ taskId, ...input }) => wrap(() => client.submitPr(taskId, input)),
174
394
  }),
175
395
  // ── Artifacts (v2) ───────────────────────────────────────────────────
176
396
  //
@@ -257,12 +477,18 @@ export function buildTools(client) {
257
477
  // `requireDistinctReviewer` unless `soloMode` is on — see task_merge.
258
478
  def({
259
479
  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`).",
480
+ 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
481
  inputShape: {
262
482
  taskId: uuid(),
263
483
  mergeMethod: z.enum(["squash", "merge", "rebase"]).optional(),
484
+ include: includeSchema,
485
+ },
486
+ handler: async ({ taskId, mergeMethod, include }) => {
487
+ const response = await wrap(() => client.mergeTask(taskId, mergeMethod));
488
+ if (include?.includes("task"))
489
+ return response;
490
+ return receiptForMerge(response);
264
491
  },
265
- handler: async ({ taskId, mergeMethod }) => wrap(() => client.mergeTask(taskId, mergeMethod)),
266
492
  }),
267
493
  // ── v1 surface (deprecated) ──────────────────────────────────────────
268
494
  def({
@@ -287,9 +513,11 @@ export function buildTools(client) {
287
513
  }),
288
514
  def({
289
515
  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.",
516
+ 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). " +
517
+ "`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). " +
518
+ "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. " +
519
+ "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. " +
520
+ "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
521
  inputShape: {
294
522
  project: z.string().min(1),
295
523
  status: z
@@ -306,14 +534,39 @@ export function buildTools(client) {
306
534
  labels: z.array(z.string().min(1).max(100)).min(1).max(20).optional(),
307
535
  unclaimed: z.boolean().optional(),
308
536
  limit: z.number().int().positive().max(500).optional(),
537
+ sort: z
538
+ .enum(["createdAt:asc", "createdAt:desc"])
539
+ .default("createdAt:desc")
540
+ .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."),
541
+ cursor: z
542
+ .string()
543
+ .min(1)
544
+ .optional()
545
+ .describe("Task id to page forward from — pass the previous call's `nextCursor`. Omit for the first page."),
546
+ },
547
+ handler: async ({ project, status, priority, labels, unclaimed, limit, sort, cursor }) => {
548
+ try {
549
+ return await wrap(() => client.listProjectTasks(project, {
550
+ status,
551
+ priority,
552
+ labels,
553
+ unclaimed,
554
+ limit,
555
+ sort,
556
+ cursor,
557
+ }));
558
+ }
559
+ catch (err) {
560
+ // Same rc-v1-C006 mapping as task_create's own projectSlug path:
561
+ // client.ts's resolver throws ProjectSlugNotFoundError (not an
562
+ // AgentTasksApiError, so wrap() does not touch it) on a fresh
563
+ // 404, translated here to the specific teaching error.
564
+ if (err instanceof ProjectSlugNotFoundError) {
565
+ throw new Error(serializeTeachingError(unknownProjectSlugError(err.slug, "project_tasks")));
566
+ }
567
+ throw err;
568
+ }
309
569
  },
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
570
  }),
318
571
  def({
319
572
  name: "tasks_list",
@@ -322,7 +575,9 @@ export function buildTools(client) {
322
575
  "For 'what is open in project X' use project_tasks (the browse-scoped verb). " +
323
576
  "Pass status/priority/labels/claimedByAgentId/projectId to broaden the search; verbose=true switches to the full task payload " +
324
577
  "(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.",
578
+ "claimedByAgentId='me' resolves to the calling agent's tokenId. Default limit 25. " +
579
+ "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. " +
580
+ "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
581
  inputShape: {
327
582
  limit: z.number().int().positive().max(200).optional(),
328
583
  projectId: uuid().optional(),
@@ -338,15 +593,26 @@ export function buildTools(client) {
338
593
  labels: z.array(z.string().min(1).max(100)).min(1).max(20).optional(),
339
594
  claimedByAgentId: z.union([uuid(), z.literal("me")]).optional(),
340
595
  verbose: z.boolean().optional(),
596
+ sort: z
597
+ .enum(["createdAt:asc", "createdAt:desc"])
598
+ .default("createdAt:desc")
599
+ .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."),
600
+ cursor: z
601
+ .string()
602
+ .min(1)
603
+ .optional()
604
+ .describe("Task id to page forward from — pass the previous call's `nextCursor`. Omit for the first page."),
341
605
  },
342
606
  handler: async (args) => wrap(() => client.listClaimableTasks(args)),
343
607
  }),
344
608
  def({
345
609
  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)),
610
+ 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.",
611
+ inputShape: { taskId: uuid(), include: readIncludeSchema },
612
+ handler: async ({ taskId, include }) => {
613
+ const response = await wrap(() => client.getTask(taskId));
614
+ return projectTaskSummary(response, include);
615
+ },
350
616
  }),
351
617
  def({
352
618
  name: "tasks_instructions",
@@ -380,7 +646,7 @@ export function buildTools(client) {
380
646
  description: DEPRECATED +
381
647
  "Use task_start instead (atomic claim + in_progress + instructions).",
382
648
  inputShape: { taskId: uuid() },
383
- handler: async ({ taskId }) => wrap(() => client.claimTask(taskId)),
649
+ handler: async ({ taskId }) => wrap(() => client.claimTask(taskId), "tasks_claim"),
384
650
  }),
385
651
  def({
386
652
  name: "tasks_release",
@@ -399,7 +665,7 @@ export function buildTools(client) {
399
665
  force: z.boolean().optional(),
400
666
  forceReason: z.string().max(500).optional(),
401
667
  },
402
- handler: async ({ taskId, ...input }) => wrap(() => client.transitionTask(taskId, input)),
668
+ handler: async ({ taskId, ...input }) => wrap(() => client.transitionTask(taskId, input), "tasks_transition"),
403
669
  }),
404
670
  def({
405
671
  name: "tasks_update",
@@ -410,19 +676,38 @@ export function buildTools(client) {
410
676
  branchName: z.string().max(255).nullable().optional(),
411
677
  prUrl: z.string().url().nullable().optional(),
412
678
  prNumber: z.number().int().positive().nullable().optional(),
413
- result: z.string().nullable().optional(),
679
+ // Symmetry with task_finish's own result field (same field, same
680
+ // storage): uncapped here let a caller feed an arbitrarily large
681
+ // string straight into looksLikeStructuredWrapper's tag-pair scan
682
+ // before this cap was added (measured: 18,395ms on a 400k-char
683
+ // adversarial input against the pre-cap guard alone).
684
+ result: z.string().max(5000).nullable().optional(),
685
+ },
686
+ handler: async ({ taskId, ...input }) => {
687
+ // Same pre-network guard as task_finish's own result field
688
+ // (errors.ts catalog entry #8): tasks_update writes `result` the
689
+ // same way the backend stores it, so the same XML/JSON-wrapper
690
+ // mistake needs the same check here, not just on the v2 verb.
691
+ if (typeof input.result === "string" && looksLikeStructuredWrapper(input.result)) {
692
+ throw new Error(serializeTeachingError(resultMustBePlainStringError("tasks_update")));
693
+ }
694
+ return wrap(() => client.updateTask(taskId, input), "tasks_update");
414
695
  },
415
- handler: async ({ taskId, ...input }) => wrap(() => client.updateTask(taskId, input)),
416
696
  }),
417
697
  def({
418
698
  name: "tasks_comment",
419
- description: DEPRECATED +
420
- "Use task_note instead (same behavior, v2 naming).",
699
+ 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
700
  inputShape: {
422
701
  taskId: uuid(),
423
702
  content: z.string().min(1).max(5000),
703
+ include: includeSchema,
704
+ },
705
+ handler: async ({ taskId, content, include }) => {
706
+ const response = await wrap(() => client.addTaskComment(taskId, content));
707
+ if (include?.includes("task"))
708
+ return response;
709
+ return receiptForNote(taskId, response);
424
710
  },
425
- handler: async ({ taskId, content }) => wrap(() => client.addTaskComment(taskId, content)),
426
711
  }),
427
712
  def({
428
713
  name: "review_approve",
@@ -460,15 +745,30 @@ export function buildTools(client) {
460
745
  }),
461
746
  def({
462
747
  name: "signals_poll",
463
- description: DEPRECATED +
464
- "Signals are delivered inline by task_pickup under v2.",
465
- inputShape: {},
466
- handler: async () => wrap(() => client.pollSignals()),
748
+ 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.`,
749
+ inputShape: {
750
+ limit: z
751
+ .number()
752
+ .int()
753
+ .positive()
754
+ .max(SIGNALS_MAX_LIMIT)
755
+ .optional()
756
+ .describe(`Max signals to return this call. Default ${SIGNALS_DEFAULT_LIMIT}.`),
757
+ cursor: z
758
+ .string()
759
+ .min(1)
760
+ .optional()
761
+ .describe("Signal id to resume after — pass the previous call's cursor. Omit for the first page."),
762
+ },
763
+ handler: async ({ limit, cursor }) => {
764
+ const response = await wrap(() => client.pollSignals(SIGNALS_BACKEND_FETCH_LIMIT));
765
+ const all = response?.signals ?? [];
766
+ return paginateSignals(all, { cursor, limit });
767
+ },
467
768
  }),
468
769
  def({
469
770
  name: "signals_ack",
470
- description: DEPRECATED +
471
- "Signals are acked atomically when delivered by task_pickup under v2.",
771
+ 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
772
  inputShape: { signalId: uuid() },
473
773
  handler: async ({ signalId }) => wrap(() => client.ackSignal(signalId)),
474
774
  }),
@@ -485,7 +785,7 @@ export function buildTools(client) {
485
785
  body: z.string().optional(),
486
786
  idempotencyKey: z.string().trim().min(1).max(255).optional(),
487
787
  },
488
- handler: async (input) => wrap(() => client.createPullRequest(input)),
788
+ handler: async (input) => wrap(() => client.createPullRequest(input), "pull_requests_create"),
489
789
  }),
490
790
  def({
491
791
  name: "pull_requests_merge",
@@ -522,5 +822,9 @@ export function buildTools(client) {
522
822
  handler: async (input) => wrap(() => client.commentOnPullRequest(input)),
523
823
  }),
524
824
  ];
825
+ // rc-v1-C007: registration-time filter only. Every handler above stays
826
+ // fully defined regardless of `options.legacy`; { legacy: true } is the
827
+ // only thing that changes which of them end up in the returned array.
828
+ return options?.legacy ? tools : tools.filter((t) => !LEGACY_VERB_NAMES.has(t.name));
525
829
  }
526
830
  //# sourceMappingURL=tools.js.map