planko-mcp-server 0.6.0 → 0.8.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/src/tools.js ADDED
@@ -0,0 +1,913 @@
1
+ import { z } from 'zod';
2
+
3
+ import {
4
+ TYPE_TASK,
5
+ TYPE_NOTE,
6
+ TYPE_STICKY,
7
+ resolveBoardFilters,
8
+ renderList,
9
+ renderItem,
10
+ mergeAllLists,
11
+ renderAll,
12
+ } from './listing.js';
13
+ import { isBlankValue, applyDueDateFallback } from './sanitize.js';
14
+ import {
15
+ buildRecommendationBody,
16
+ renderRecommendation,
17
+ describeLockError,
18
+ } from './recommend.js';
19
+ import {
20
+ lockProjectId,
21
+ sanitizeFilters,
22
+ assertProjectAllowed,
23
+ stripHallucinatedListFilters,
24
+ matchesAssignee,
25
+ hasOwnerInfo,
26
+ } from './projectLock.js';
27
+ import { markdownToDescription } from './converters.js';
28
+
29
+ export function toolOk(text) {
30
+ return { content: [{ type: 'text', text }] };
31
+ }
32
+
33
+ export function toolError(text) {
34
+ return { content: [{ type: 'text', text }], isError: true };
35
+ }
36
+
37
+ const ANNOTATIONS = {
38
+ READ_ONLY: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
39
+ WRITE: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },
40
+ IDEMPOTENT_WRITE: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
41
+ DESTRUCTIVE: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
42
+ };
43
+
44
+ export function registerStandaloneTools(server, { api, projectLock = null, wrapHandler = (name, fn) => fn }) {
45
+ const PROJECT_LOCK = projectLock;
46
+
47
+ // --- Standalone CRUD tools (Part B) ---
48
+ // These operate directly via the user-scoped API key and do NOT require any
49
+ // folder to be configured with planko_setup. Notes are Task docs with type=2,
50
+ // sticky notes type=3, tasks type=1. Edit/Delete/View work on any of them;
51
+ // Complete is task-oriented but accepts any id.
52
+
53
+ const editableType = z
54
+ .union([z.literal(1), z.literal(2), z.literal(3)])
55
+ .optional()
56
+ .describe('Change type: 1=task, 2=note, 3=sticky note');
57
+
58
+ const objectId = z
59
+ .string()
60
+ .regex(/^[a-fA-F\d]{24}$/, 'Must be a 24-character hex ObjectId');
61
+
62
+ const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
63
+
64
+ // Shared editable task/note properties (all optional). `description` is Markdown
65
+ // here and is converted to BlockNote JSON before being sent to the backend.
66
+ const taskProps = {
67
+ description: z
68
+ .string()
69
+ .optional()
70
+ .describe('Body as Markdown (converted to BlockNote JSON before saving)'),
71
+ dueDate: z
72
+ .string()
73
+ .optional()
74
+ .describe(
75
+ 'Execution date (ISO 8601 string): when the task appears on the agenda/day view. ' +
76
+ 'Independent of deadline (the final deadline, when supported).'
77
+ ),
78
+ datePlain: z
79
+ .string()
80
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'Must be YYYY-MM-DD')
81
+ .optional()
82
+ .describe(
83
+ 'Execution date, plain YYYY-MM-DD: when the task appears on the agenda/day view. ' +
84
+ 'Independent of deadline (the final deadline, when supported).'
85
+ ),
86
+ time: z.string().regex(timeRegex, 'Must be HH:MM').optional().describe('Start time, HH:MM'),
87
+ endTime: z.string().regex(timeRegex, 'Must be HH:MM').optional().describe('End time, HH:MM'),
88
+ alert: z.boolean().optional().describe('Whether an alert/reminder is enabled'),
89
+ alertLeadTime: z
90
+ .enum(['ontime', '15min', '30min', '1hour', '1day'])
91
+ .nullable()
92
+ .optional()
93
+ .describe('Reminder lead time (null or one of ontime/15min/30min/1hour/1day)'),
94
+ priority: z
95
+ .union([z.literal(1), z.literal(2), z.literal(3)])
96
+ .optional()
97
+ .describe('Priority: 1, 2, or 3'),
98
+ repeat: z
99
+ .enum(['daily', 'workdays', 'weekly', 'biweekly', 'monthly', 'custom_weekly', 'yearly'])
100
+ .nullable()
101
+ .optional()
102
+ .describe('Recurrence rule (null or one of the recurrence keywords)'),
103
+ // The backend stores an integer here (Joi.number().integer()), NOT a date:
104
+ // the weekday (1-7) for weekly repeats or the day of month (1-31) for monthly.
105
+ repeatDate: z
106
+ .number()
107
+ .int()
108
+ .nullable()
109
+ .optional()
110
+ .describe('Recurrence day (integer, not a date): weekday 1-7 for weekly, day of month 1-31 for monthly'),
111
+ selectedWeekdays: z
112
+ .array(z.number().int().min(0).max(6))
113
+ .optional()
114
+ .describe('Weekdays for custom_weekly repeat (0=Sunday..6=Saturday)'),
115
+ parentId: objectId.optional().describe('Parent task id (for subtasks)'),
116
+ tags: z.array(objectId).optional().describe('Array of tag ids'),
117
+ kanbanColumnId: objectId.optional().describe('Kanban column id'),
118
+ boardId: objectId.optional().describe('Board id'),
119
+ };
120
+
121
+ // Task-only properties (PL328): never offered on note/sticky-note tools.
122
+ // `deadline` is independent of dueDate/datePlain (the execution date) — it is
123
+ // the day by which the task must be done. `null` clears it; omitted leaves it
124
+ // unchanged.
125
+ const deadlineProps = {
126
+ deadline: z
127
+ .string()
128
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'Must be YYYY-MM-DD')
129
+ .nullable()
130
+ .optional()
131
+ .describe(
132
+ 'Prazo final (YYYY-MM-DD): até quando a tarefa precisa estar pronta. ' +
133
+ 'É independente de dueDate/datePlain (data de execução, quando a tarefa aparece na agenda). ' +
134
+ 'null remove o prazo. Só para tarefas (type=1) — nunca para notas ou sticky notes.'
135
+ ),
136
+ };
137
+
138
+ // Fields that support an explicit null to clear a value on edit (as opposed to
139
+ // isBlankValue's "omitted" semantics, which would otherwise drop the null).
140
+ // '' is treated the same as null so a model that sends an empty string still
141
+ // clears the field.
142
+ const NULLABLE_CLEAR_FIELDS = new Set(['deadline']);
143
+
144
+ /**
145
+ * Build a request body from tool params: drop undefined values and convert the
146
+ * Markdown `description` into BlockNote JSON. Fields in NULLABLE_CLEAR_FIELDS
147
+ * keep an explicit null (and treat '' as null) so the model can clear them;
148
+ * omitted stays omitted.
149
+ */
150
+ function buildTaskBody(params) {
151
+ const body = {};
152
+ for (const [key, value] of Object.entries(params)) {
153
+ if (NULLABLE_CLEAR_FIELDS.has(key)) {
154
+ if (value === undefined) continue;
155
+ body[key] = value === '' ? null : value;
156
+ continue;
157
+ }
158
+ if (isBlankValue(value)) continue;
159
+ body[key] = value;
160
+ }
161
+ applyDueDateFallback(body);
162
+ if ('description' in body) {
163
+ body.description = markdownToDescription(body.description);
164
+ }
165
+ return body;
166
+ }
167
+
168
+ /**
169
+ * Resolve a project name to a project id via the user's accessible projects
170
+ * (NOT the local folder config), so create tools work without any setup.
171
+ */
172
+ async function resolveProjectId(projectName) {
173
+ const { projects } = await api.projects();
174
+ const match = projects.find(
175
+ (p) => p.name.toLowerCase() === projectName.toLowerCase()
176
+ );
177
+ if (!match) {
178
+ const available = projects.map((p) => ` - ${p.name}`).join('\n');
179
+ throw new Error(
180
+ `Project "${projectName}" not found.\n\nAvailable projects:\n${available}`
181
+ );
182
+ }
183
+ return match._id;
184
+ }
185
+
186
+ /** Extract { id, name } from a create/edit response (shape-tolerant). */
187
+ function describeTask(res) {
188
+ const t = (res && (res.task || res.data)) || res || {};
189
+ return {
190
+ id: t._id || t.id || 'unknown',
191
+ name: t.name != null ? t.name : 'unknown',
192
+ };
193
+ }
194
+
195
+ /**
196
+ * When PROJECT_LOCK is set, fetch a by-id task and refuse the operation unless
197
+ * it belongs to the locked project. No-op when the lock is null.
198
+ */
199
+ async function assertTaskInLock(taskId) {
200
+ if (!PROJECT_LOCK) return;
201
+ const res = await api.getTask(taskId);
202
+ assertProjectAllowed(PROJECT_LOCK, unwrapItem(res));
203
+ }
204
+
205
+ /**
206
+ * Shared create handler for tasks (type=1) and notes (type=2).
207
+ */
208
+ async function handleCreate(type, params, kindLabel) {
209
+ const { name, projectName, ...rest } = params;
210
+ const body = buildTaskBody(rest);
211
+ body.name = name;
212
+ body.type = type;
213
+
214
+ if (PROJECT_LOCK) {
215
+ // Hard override: always the locked project; ignore any caller project field
216
+ // and do NOT resolve projectName.
217
+ body.projectId = lockProjectId(PROJECT_LOCK, body.projectId);
218
+ } else if (!isBlankValue(projectName)) {
219
+ // Resolve projectName -> projectId via the API. When omitted, OMIT the key
220
+ // entirely so the backend applies the user's default project.
221
+ body.projectId = await resolveProjectId(projectName);
222
+ }
223
+
224
+ const res = await api.createTask(body);
225
+ const { id, name: savedName } = describeTask(res);
226
+ const where = body.projectId
227
+ ? ` in project ${body.projectId}`
228
+ : ' in your default project';
229
+ return toolOk(`Created ${kindLabel} "${savedName}" (id: ${id})${where}.`);
230
+ }
231
+
232
+ /**
233
+ * Shared edit handler for tasks and notes (same endpoint).
234
+ */
235
+ async function handleEdit(params, kindLabel) {
236
+ const { taskId, ...rest } = params;
237
+ const body = buildTaskBody(rest);
238
+ const changed = Object.keys(body);
239
+ if (changed.length === 0) {
240
+ return toolError('Nothing to update: provide at least one field to change.');
241
+ }
242
+ if (PROJECT_LOCK) {
243
+ // Refuse to touch a task outside the locked project.
244
+ await assertTaskInLock(taskId);
245
+ // If the caller tried to move the task to another project, force it back to
246
+ // the lock (never let an edit move a task OUT of the locked project). If no
247
+ // project field was passed, leave the project unchanged.
248
+ if ('projectId' in body) {
249
+ body.projectId = lockProjectId(PROJECT_LOCK, body.projectId);
250
+ }
251
+ }
252
+ const res = await api.updateTask(taskId, body);
253
+ const { id, name: savedName } = describeTask(res);
254
+ return toolOk(
255
+ `Updated ${kindLabel} "${savedName}" (id: ${id}). Changed: ${changed.join(', ')}.`
256
+ );
257
+ }
258
+
259
+ // ---- planko_create_task ----
260
+ server.registerTool(
261
+ 'planko_create_task',
262
+ {
263
+ title: 'Create task',
264
+ description: 'Create a Planko task (type=1) directly, immediately and without approval. Works without any folder setup. Provide a name (required); all other properties are optional. Optionally target a project by name (otherwise your default project is used). To propose a task for the account owner to accept or reject instead, use planko_recommend_task.',
265
+ inputSchema: {
266
+ name: z.string().describe('Task name (required)'),
267
+ projectName: z
268
+ .string()
269
+ .optional()
270
+ .describe('Project name to create the task in (optional — omit for your default project)'),
271
+ ...taskProps,
272
+ ...deadlineProps,
273
+ },
274
+ annotations: ANNOTATIONS.WRITE,
275
+ },
276
+ wrapHandler('planko_create_task', async (params) => {
277
+ try {
278
+ return await handleCreate(TYPE_TASK, params, 'task');
279
+ } catch (err) {
280
+ return toolError(`Create task failed: ${err.message}`);
281
+ }
282
+ })
283
+ );
284
+
285
+ // ---- planko_create_note ----
286
+ server.registerTool(
287
+ 'planko_create_note',
288
+ {
289
+ title: 'Create note',
290
+ description: 'Create a Planko note (type=2) directly. Works without any folder setup. Provide a name (required); all other properties are optional. Optionally target a project by name (otherwise your default project is used).',
291
+ inputSchema: {
292
+ name: z.string().describe('Note name (required)'),
293
+ projectName: z
294
+ .string()
295
+ .optional()
296
+ .describe('Project name to create the note in (optional — omit for your default project)'),
297
+ ...taskProps,
298
+ },
299
+ annotations: ANNOTATIONS.WRITE,
300
+ },
301
+ wrapHandler('planko_create_note', async (params) => {
302
+ try {
303
+ return await handleCreate(TYPE_NOTE, params, 'note');
304
+ } catch (err) {
305
+ return toolError(`Create note failed: ${err.message}`);
306
+ }
307
+ })
308
+ );
309
+
310
+ // ---- planko_create_sticky_note ----
311
+ server.registerTool(
312
+ 'planko_create_sticky_note',
313
+ {
314
+ title: 'Create sticky note',
315
+ description: 'Create a Planko sticky note (type=3) directly. A sticky note is a task-page item with every task property (dates, priority, tags, kanban column). Provide a name (required); all other properties are optional. Optionally target a project by name (otherwise your default project is used).',
316
+ inputSchema: {
317
+ name: z.string().describe('Sticky note name (required)'),
318
+ projectName: z
319
+ .string()
320
+ .optional()
321
+ .describe('Project name to create the sticky note in (optional — omit for your default project)'),
322
+ ...taskProps,
323
+ },
324
+ annotations: ANNOTATIONS.WRITE,
325
+ },
326
+ wrapHandler('planko_create_sticky_note', async (params) => {
327
+ try {
328
+ return await handleCreate(TYPE_STICKY, params, 'sticky note');
329
+ } catch (err) {
330
+ return toolError(`Create sticky note failed: ${err.message}`);
331
+ }
332
+ })
333
+ );
334
+
335
+ // ---- planko_recommend_task ----
336
+ // PL274: a SUGGESTION, not a write. The backend stores it as a pending
337
+ // recommendation addressed to the API key's owner and notifies them; the task is
338
+ // created only if they accept it in Planko. There is no read-back endpoint.
339
+ server.registerTool(
340
+ 'planko_recommend_task',
341
+ {
342
+ title: 'Recommend task',
343
+ description: 'Suggest a new task to the Planko account owner instead of creating it. The owner gets a notification (notification centre + push) with Accept/Reject buttons; the task is created only when they accept. Use this when a human should approve before anything is written, or when you must not create tasks directly; use planko_create_task to create immediately. The recipient is always the owner of the API key (never other project members). Provide a title (required); all other task properties are optional and are applied to the task on accept. The outcome cannot be read back afterwards and re-sending creates a duplicate suggestion, so send each suggestion once.',
344
+ inputSchema: {
345
+ title: z.string().trim().min(1).max(500).describe('Suggested task name (required, up to 500 characters)'),
346
+ projectName: z
347
+ .string()
348
+ .optional()
349
+ .describe('Project name the task would be created in (optional — omit for the owner\'s default project)'),
350
+ ...taskProps,
351
+ ...deadlineProps,
352
+ },
353
+ annotations: ANNOTATIONS.WRITE,
354
+ },
355
+ wrapHandler('planko_recommend_task', async (params) => {
356
+ try {
357
+ const { title, projectName, ...rest } = params;
358
+ const body = buildTaskBody(rest);
359
+ let projectNameIgnored = false;
360
+
361
+ if (PROJECT_LOCK) {
362
+ // Same hard override as handleCreate: the suggestion can only target
363
+ // the locked project; projectName is neither resolved nor honoured.
364
+ body.projectId = lockProjectId(PROJECT_LOCK, body.projectId);
365
+ projectNameIgnored = !isBlankValue(projectName);
366
+ } else if (!isBlankValue(projectName)) {
367
+ body.projectId = await resolveProjectId(projectName);
368
+ }
369
+
370
+ let res;
371
+ try {
372
+ res = await api.createRecommendation(buildRecommendationBody(title, body));
373
+ } catch (err) {
374
+ throw describeLockError(err, PROJECT_LOCK);
375
+ }
376
+ return toolOk(
377
+ renderRecommendation(res, {
378
+ projectId: body.projectId,
379
+ lock: PROJECT_LOCK,
380
+ projectNameIgnored,
381
+ })
382
+ );
383
+ } catch (err) {
384
+ return toolError(`Recommend task failed: ${err.message}`);
385
+ }
386
+ })
387
+ );
388
+
389
+ // ---- planko_edit_task ----
390
+ server.registerTool(
391
+ 'planko_edit_task',
392
+ {
393
+ title: 'Edit task',
394
+ description: 'Edit an existing Planko task by id. Provide the taskId and any properties to change. The Markdown description is converted to BlockNote JSON.',
395
+ inputSchema: {
396
+ taskId: objectId.describe('Id of the task to edit (required)'),
397
+ name: z.string().optional().describe('New task name'),
398
+ type: editableType,
399
+ projectId: objectId.optional().describe('Move to a different project by id'),
400
+ ...taskProps,
401
+ ...deadlineProps,
402
+ },
403
+ annotations: ANNOTATIONS.IDEMPOTENT_WRITE,
404
+ },
405
+ wrapHandler('planko_edit_task', async (params) => {
406
+ try {
407
+ return await handleEdit(params, 'task');
408
+ } catch (err) {
409
+ return toolError(`Edit task failed: ${err.message}`);
410
+ }
411
+ })
412
+ );
413
+
414
+ // ---- planko_edit_note ----
415
+ server.registerTool(
416
+ 'planko_edit_note',
417
+ {
418
+ title: 'Edit note',
419
+ description: 'Edit an existing Planko note by id (shares the task edit endpoint). Provide the taskId and any properties to change. The Markdown description is converted to BlockNote JSON.',
420
+ inputSchema: {
421
+ taskId: objectId.describe('Id of the note to edit (required)'),
422
+ name: z.string().optional().describe('New note name'),
423
+ type: editableType,
424
+ projectId: objectId.optional().describe('Move to a different project by id'),
425
+ ...taskProps,
426
+ },
427
+ annotations: ANNOTATIONS.IDEMPOTENT_WRITE,
428
+ },
429
+ wrapHandler('planko_edit_note', async (params) => {
430
+ try {
431
+ return await handleEdit(params, 'note');
432
+ } catch (err) {
433
+ return toolError(`Edit note failed: ${err.message}`);
434
+ }
435
+ })
436
+ );
437
+
438
+ // ---- planko_edit_sticky_note ----
439
+ server.registerTool(
440
+ 'planko_edit_sticky_note',
441
+ {
442
+ title: 'Edit sticky note',
443
+ description: 'Edit an existing Planko sticky note by id (shares the task edit endpoint). Provide the taskId and any properties to change. The Markdown description is converted to BlockNote JSON.',
444
+ inputSchema: {
445
+ taskId: objectId.describe('Id of the sticky note to edit (required)'),
446
+ name: z.string().optional().describe('New sticky note name'),
447
+ type: editableType,
448
+ projectId: objectId.optional().describe('Move to a different project by id'),
449
+ ...taskProps,
450
+ },
451
+ annotations: ANNOTATIONS.IDEMPOTENT_WRITE,
452
+ },
453
+ wrapHandler('planko_edit_sticky_note', async (params) => {
454
+ try {
455
+ return await handleEdit(params, 'sticky note');
456
+ } catch (err) {
457
+ return toolError(`Edit sticky note failed: ${err.message}`);
458
+ }
459
+ })
460
+ );
461
+
462
+ // ---- planko_complete_task ----
463
+ server.registerTool(
464
+ 'planko_complete_task',
465
+ {
466
+ title: 'Complete task',
467
+ description: 'Mark a Planko task complete (status=2) by id. Also works on a sticky note id (sticky notes have the same status field).',
468
+ inputSchema: {
469
+ taskId: objectId.describe('Id of the task to complete (required)'),
470
+ },
471
+ annotations: ANNOTATIONS.DESTRUCTIVE,
472
+ },
473
+ wrapHandler('planko_complete_task', async ({ taskId }) => {
474
+ try {
475
+ await assertTaskInLock(taskId);
476
+ const res = await api.completeTask(taskId);
477
+ const { id, name } = describeTask(res);
478
+ return toolOk(`Completed task "${name}" (id: ${id}).`);
479
+ } catch (err) {
480
+ return toolError(`Complete task failed: ${err.message}`);
481
+ }
482
+ })
483
+ );
484
+
485
+ // ---- planko_delete_task ----
486
+ server.registerTool(
487
+ 'planko_delete_task',
488
+ {
489
+ title: 'Delete task',
490
+ description: 'Delete a Planko task by id.',
491
+ inputSchema: {
492
+ taskId: objectId.describe('Id of the task to delete (required)'),
493
+ },
494
+ annotations: ANNOTATIONS.DESTRUCTIVE,
495
+ },
496
+ wrapHandler('planko_delete_task', async ({ taskId }) => {
497
+ try {
498
+ await assertTaskInLock(taskId);
499
+ await api.deleteTask(taskId);
500
+ return toolOk(`Deleted task (id: ${taskId}).`);
501
+ } catch (err) {
502
+ return toolError(`Delete task failed: ${err.message}`);
503
+ }
504
+ })
505
+ );
506
+
507
+ // ---- planko_delete_note ----
508
+ server.registerTool(
509
+ 'planko_delete_note',
510
+ {
511
+ title: 'Delete note',
512
+ description: 'Delete a Planko note by id (shares the task delete endpoint).',
513
+ inputSchema: {
514
+ taskId: objectId.describe('Id of the note to delete (required)'),
515
+ },
516
+ annotations: ANNOTATIONS.DESTRUCTIVE,
517
+ },
518
+ wrapHandler('planko_delete_note', async ({ taskId }) => {
519
+ try {
520
+ await assertTaskInLock(taskId);
521
+ await api.deleteTask(taskId);
522
+ return toolOk(`Deleted note (id: ${taskId}).`);
523
+ } catch (err) {
524
+ return toolError(`Delete note failed: ${err.message}`);
525
+ }
526
+ })
527
+ );
528
+
529
+ // ---- planko_delete_sticky_note ----
530
+ server.registerTool(
531
+ 'planko_delete_sticky_note',
532
+ {
533
+ title: 'Delete sticky note',
534
+ description: 'Delete a Planko sticky note by id (shares the task delete endpoint).',
535
+ inputSchema: {
536
+ taskId: objectId.describe('Id of the sticky note to delete (required)'),
537
+ },
538
+ annotations: ANNOTATIONS.DESTRUCTIVE,
539
+ },
540
+ wrapHandler('planko_delete_sticky_note', async ({ taskId }) => {
541
+ try {
542
+ await assertTaskInLock(taskId);
543
+ await api.deleteTask(taskId);
544
+ return toolOk(`Deleted sticky note (id: ${taskId}).`);
545
+ } catch (err) {
546
+ return toolError(`Delete sticky note failed: ${err.message}`);
547
+ }
548
+ })
549
+ );
550
+
551
+ // --- Standalone READ tools (Part C) ---
552
+ // Read-only, user-scoped via API key; no folder setup required. List tools send
553
+ // `type` (1=tasks, 2=notes, 3=sticky notes; omitted = tasks + sticky notes) and
554
+ // parametrized filters; view tools fetch one item by id and render its
555
+ // BlockNote description as Markdown. No mutation.
556
+
557
+ const datePlain = z
558
+ .string()
559
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'Must be YYYY-MM-DD');
560
+
561
+ const sortBySchema = z
562
+ .string()
563
+ .describe(
564
+ "Sort as 'field:asc' or 'field:desc'. Allowed fields: dueDate, deadline, createdAt, updatedAt, priority, position, name. Default updatedAt:desc."
565
+ );
566
+
567
+ /**
568
+ * Build the API filter params from tool params, resolving projectName and the
569
+ * kanban board/column names. `type` may be undefined (backend: tasks + sticky).
570
+ */
571
+ async function buildListParams(type, params) {
572
+ // assigneeName / boardName / kanbanColumnName are resolved client-side and
573
+ // must never reach the backend, which rejects unknown query keys.
574
+ const { projectName, assigneeName, boardName, kanbanColumnName, ...rest } = params;
575
+ // Sanitize scalar filters (drops blank/placeholder values, incl. a blank
576
+ // assigneeId => "all members").
577
+ const out = { ...sanitizeFilters(rest) };
578
+ if (type != null) out.type = type;
579
+ if (PROJECT_LOCK) {
580
+ // Drop the id narrowers this class of agent fabricates with non-blank
581
+ // garbage (parentId=projectId, assigneeId from a chat id, guessed priority,
582
+ // a boardId copied from somewhere) that would silently zero the "list the
583
+ // whole team" result. Board/column narrowing under lock is by NAME below.
584
+ stripHallucinatedListFilters(out);
585
+ // Hard override: force the project regardless of caller input. Do NOT
586
+ // resolve projectName here — the override wins unconditionally, so an
587
+ // invalid projectName must not be able to fail an otherwise-locked list.
588
+ out.projectId = lockProjectId(PROJECT_LOCK, out.projectId);
589
+ } else if (!isBlankValue(projectName)) {
590
+ // Unlocked (default) path: unchanged behavior.
591
+ out.projectId = await resolveProjectId(projectName);
592
+ }
593
+ if (!isBlankValue(boardName) || !isBlankValue(kanbanColumnName)) {
594
+ const boards = await api.boards();
595
+ Object.assign(
596
+ out,
597
+ resolveBoardFilters(
598
+ { boardName, kanbanColumnName, boardId: out.boardId, kanbanColumnId: out.kanbanColumnId },
599
+ boards
600
+ )
601
+ );
602
+ }
603
+ return out;
604
+ }
605
+
606
+ /** Extract a single item from a view response (shape-tolerant). */
607
+ function unwrapItem(res) {
608
+ return (res && (res.task || res.data)) || res || {};
609
+ }
610
+
611
+ // Shared list filter surface (task tools use all; note tools use the applicable subset).
612
+ const listStatus = z
613
+ .union([z.literal(1), z.literal(2)])
614
+ .optional()
615
+ .describe('Filter by status: 1=open, 2=complete');
616
+ const listShowCompleted = z
617
+ .boolean()
618
+ .optional()
619
+ .describe('When false/omitted (and no explicit status), completed items are excluded');
620
+ const listProjectName = z
621
+ .string()
622
+ .optional()
623
+ .describe('Filter to a project by name (resolved to its id)');
624
+ const listProjectId = objectId.optional().describe('Filter to a project by id');
625
+ const listAssigneeId = objectId
626
+ .optional()
627
+ .describe('Filter to a single project member by their user id (omit for all members)');
628
+ const listTags = z.array(objectId).optional().describe('Filter by tag ids (AND — item must have all)');
629
+ const listSearch = z.string().optional().describe('Case-insensitive search on the name');
630
+ const listSortBy = sortBySchema.optional();
631
+ const listLimit = z
632
+ .number()
633
+ .int()
634
+ .min(1)
635
+ .max(200)
636
+ .optional()
637
+ .describe('Max items to return (default 50, max 200)');
638
+ const listPage = z.number().int().min(1).optional().describe('Page number (default 1)');
639
+ const listPriority = z
640
+ .union([z.literal(1), z.literal(2), z.literal(3)])
641
+ .optional()
642
+ .describe('Filter by priority: 1, 2, or 3');
643
+ const listParentId = objectId.optional().describe('List subtasks of this parent task id');
644
+ const listAssigneeName = z
645
+ .string()
646
+ .optional()
647
+ .describe(
648
+ 'Narrow to ONE team member by their NAME or email (case-insensitive). ' +
649
+ 'Omit to list the WHOLE team (all members). Only set this when the user ' +
650
+ 'explicitly names a person; never guess.'
651
+ );
652
+ const listBoardName = z
653
+ .string()
654
+ .optional()
655
+ .describe(
656
+ 'Filter by kanban board NAME (case-insensitive, resolved against your own and workspace boards). ' +
657
+ 'Only set this when the user explicitly names a board; never guess.'
658
+ );
659
+ const listKanbanColumnName = z
660
+ .string()
661
+ .optional()
662
+ .describe(
663
+ 'Filter by kanban column NAME (e.g. "To Do", "Done"). Resolved inside boardName when given; ' +
664
+ 'without a board the name must be unique across your boards. Only set this when the user ' +
665
+ 'explicitly names a column; never guess.'
666
+ );
667
+ const listBoardId = objectId.optional().describe('Filter by kanban board id');
668
+ const listKanbanColumnId = objectId.optional().describe('Filter by kanban column id');
669
+
670
+ // Build the list-filter schema. Under PROJECT_LOCK the project is forced and the
671
+ // caller is a bespoke, project-scoped agent whose model fabricates id/priority
672
+ // narrowers (parentId/assigneeId/priority/boardId/kanbanColumnId) that silently
673
+ // zero the result — so those fields are NOT offered; member and board/column
674
+ // narrowing is by NAME instead. Unlocked (default, e.g. clawis) keeps the full
675
+ // surface. `kind`: 'task' | 'note' | 'sticky' | 'all' — status/due-date filters
676
+ // are offered for every task-page kind (sticky notes carry the same fields).
677
+ function listSchema(kind) {
678
+ const taskLike = kind !== 'note';
679
+ const deadlineLike = kind === 'task' || kind === 'all';
680
+ const base = { showCompleted: listShowCompleted };
681
+ if (taskLike) base.status = listStatus;
682
+ const tail = {
683
+ tags: listTags,
684
+ search: listSearch,
685
+ boardName: listBoardName,
686
+ kanbanColumnName: listKanbanColumnName,
687
+ ...(taskLike
688
+ ? {
689
+ dueDateFrom: datePlain.optional().describe('Inclusive lower bound on due date (YYYY-MM-DD)'),
690
+ dueDateTo: datePlain.optional().describe('Inclusive upper bound on due date (YYYY-MM-DD)'),
691
+ }
692
+ : {}),
693
+ ...(deadlineLike
694
+ ? {
695
+ deadlineFrom: datePlain
696
+ .optional()
697
+ .describe(
698
+ 'Inclusive lower bound on deadline/prazo final (YYYY-MM-DD). Tasks only (type=1): never matches ' +
699
+ 'notes or sticky notes. A recurring series appears as one item.'
700
+ ),
701
+ deadlineTo: datePlain
702
+ .optional()
703
+ .describe(
704
+ 'Inclusive upper bound on deadline/prazo final (YYYY-MM-DD). Tasks only (type=1): never matches ' +
705
+ 'notes or sticky notes. A recurring series appears as one item.'
706
+ ),
707
+ }
708
+ : {}),
709
+ sortBy: listSortBy,
710
+ limit: listLimit,
711
+ ...(kind === 'all' ? {} : { page: listPage }),
712
+ };
713
+ if (PROJECT_LOCK) {
714
+ return { ...base, assigneeName: listAssigneeName, ...tail };
715
+ }
716
+ return {
717
+ ...base,
718
+ priority: listPriority,
719
+ projectName: listProjectName,
720
+ projectId: listProjectId,
721
+ assigneeId: listAssigneeId,
722
+ ...(taskLike ? { parentId: listParentId } : {}),
723
+ boardId: listBoardId,
724
+ kanbanColumnId: listKanbanColumnId,
725
+ ...tail,
726
+ };
727
+ }
728
+
729
+ const BOARD_SCOPE_NOTE =
730
+ ' Board/column filters match items on your own and workspace boards; with a project scope, teammates’ items on their personal boards are not matched.';
731
+
732
+ /**
733
+ * Client-side member narrowing by NAME (used under PROJECT_LOCK, where the
734
+ * agent narrows by a person's name instead of a fabricated user id). Returns
735
+ * { result, note }. When assigneeName is blank, the result is unchanged. When
736
+ * items lack populated owner info (backend owner-populate not deployed yet),
737
+ * the filter can't be applied — the full list is returned with an explanatory
738
+ * note rather than a misleading empty result.
739
+ */
740
+ function applyAssigneeName(result, assigneeName) {
741
+ if (isBlankValue(assigneeName)) return { result, note: null };
742
+ const tasks = Array.isArray(result?.tasks) ? result.tasks : [];
743
+ if (!hasOwnerInfo(tasks)) {
744
+ return {
745
+ result,
746
+ note: `Could not narrow to "${assigneeName}" — owner info is not available yet; showing all members.`,
747
+ };
748
+ }
749
+ const filtered = tasks.filter((t) => matchesAssignee(t.userId, assigneeName));
750
+ return { result: { ...result, tasks: filtered, total: filtered.length }, note: null };
751
+ }
752
+
753
+ /** Shared list handler: one backend call for a single type. */
754
+ async function handleList(type, params, kindLabelPlural) {
755
+ const apiParams = await buildListParams(type, params);
756
+ const result = await api.listTasks(apiParams);
757
+ const { result: filtered, note } = applyAssigneeName(result, params.assigneeName);
758
+ const out = renderList(filtered, kindLabelPlural);
759
+ return toolOk(note ? `${out}\n\nNote: ${note}` : out);
760
+ }
761
+
762
+ // ---- planko_list_tasks ----
763
+ server.registerTool(
764
+ 'planko_list_tasks',
765
+ {
766
+ title: 'List tasks',
767
+ description: 'List Planko tasks (type=1) directly, no folder setup required. All filters are optional; omit any the user did not explicitly ask for. Recurring tasks appear as separate dated occurrences. Returns a concise summary, not raw JSON.' +
768
+ BOARD_SCOPE_NOTE,
769
+ inputSchema: listSchema('task'),
770
+ annotations: ANNOTATIONS.READ_ONLY,
771
+ },
772
+ wrapHandler('planko_list_tasks', async (params) => {
773
+ try {
774
+ return await handleList(TYPE_TASK, params, 'tasks');
775
+ } catch (err) {
776
+ return toolError(`List tasks failed: ${err.message}`);
777
+ }
778
+ })
779
+ );
780
+
781
+ // ---- planko_list_notes ----
782
+ server.registerTool(
783
+ 'planko_list_notes',
784
+ {
785
+ title: 'List notes',
786
+ description: 'List Planko notes (type=2) directly, no folder setup required. All filters are optional; omit any the user did not explicitly ask for. Deleted and recurring-copy notes are excluded. Returns a concise summary, not raw JSON.' +
787
+ BOARD_SCOPE_NOTE,
788
+ inputSchema: listSchema('note'),
789
+ annotations: ANNOTATIONS.READ_ONLY,
790
+ },
791
+ wrapHandler('planko_list_notes', async (params) => {
792
+ try {
793
+ return await handleList(TYPE_NOTE, params, 'notes');
794
+ } catch (err) {
795
+ return toolError(`List notes failed: ${err.message}`);
796
+ }
797
+ })
798
+ );
799
+
800
+ // ---- planko_list_sticky_notes ----
801
+ server.registerTool(
802
+ 'planko_list_sticky_notes',
803
+ {
804
+ title: 'List sticky notes',
805
+ description: 'List Planko sticky notes (type=3) directly, no folder setup required. Sticky notes are task-page items, so the same filters as planko_list_tasks apply. All filters are optional; omit any the user did not explicitly ask for. Returns a concise summary, not raw JSON.' +
806
+ BOARD_SCOPE_NOTE,
807
+ inputSchema: listSchema('sticky'),
808
+ annotations: ANNOTATIONS.READ_ONLY,
809
+ },
810
+ wrapHandler('planko_list_sticky_notes', async (params) => {
811
+ try {
812
+ return await handleList(TYPE_STICKY, params, 'sticky notes');
813
+ } catch (err) {
814
+ return toolError(`List sticky notes failed: ${err.message}`);
815
+ }
816
+ })
817
+ );
818
+
819
+ // ---- planko_list_all ----
820
+ server.registerTool(
821
+ 'planko_list_all',
822
+ {
823
+ title: 'List all items',
824
+ description: 'List Planko tasks, sticky notes AND notes together in one result. Runs two backend queries (tasks + sticky notes; notes) with the same filters and merges them by sortBy (default updatedAt:desc), cut to `limit`; there is no page parameter. All filters are optional; omit any the user did not explicitly ask for. Returns a concise summary, not raw JSON.' +
825
+ BOARD_SCOPE_NOTE,
826
+ inputSchema: listSchema('all'),
827
+ annotations: ANNOTATIONS.READ_ONLY,
828
+ },
829
+ wrapHandler('planko_list_all', async (params) => {
830
+ try {
831
+ const limit = params.limit || 50;
832
+ const taskParams = await buildListParams(undefined, { ...params, limit, page: 1 });
833
+ const noteParams = { ...taskParams, type: TYPE_NOTE };
834
+ const [taskRes, noteRes] = await Promise.all([api.listTasks(taskParams), api.listTasks(noteParams)]);
835
+ const t = applyAssigneeName(taskRes, params.assigneeName);
836
+ const n = applyAssigneeName(noteRes, params.assigneeName);
837
+ const out = renderAll(mergeAllLists(t.result, n.result, limit, params.sortBy));
838
+ const notes = [t.note, n.note].filter(Boolean);
839
+ return toolOk(notes.length ? `${out}\n\nNote: ${notes.join(' ')}` : out);
840
+ } catch (err) {
841
+ return toolError(`List all failed: ${err.message}`);
842
+ }
843
+ })
844
+ );
845
+
846
+ /** Shared view handler: the type shown comes from the item itself. */
847
+ async function handleView(taskId) {
848
+ const res = await api.getTask(taskId);
849
+ const item = unwrapItem(res);
850
+ assertProjectAllowed(PROJECT_LOCK, item);
851
+ return toolOk(renderItem(item));
852
+ }
853
+
854
+ // ---- planko_view_task ----
855
+ server.registerTool(
856
+ 'planko_view_task',
857
+ {
858
+ title: 'View task',
859
+ description: 'View one Planko task by id, with its description rendered as Markdown. The type is informational — this endpoint returns the item regardless of task/note/sticky-note type.',
860
+ inputSchema: {
861
+ taskId: objectId.describe('Id of the task to view (required)'),
862
+ },
863
+ annotations: ANNOTATIONS.READ_ONLY,
864
+ },
865
+ wrapHandler('planko_view_task', async ({ taskId }) => {
866
+ try {
867
+ return await handleView(taskId);
868
+ } catch (err) {
869
+ return toolError(`View task failed: ${err.message}`);
870
+ }
871
+ })
872
+ );
873
+
874
+ // ---- planko_view_note ----
875
+ server.registerTool(
876
+ 'planko_view_note',
877
+ {
878
+ title: 'View note',
879
+ description: 'View one Planko note by id, with its description rendered as Markdown. The type is informational — this endpoint returns the item regardless of task/note/sticky-note type.',
880
+ inputSchema: {
881
+ taskId: objectId.describe('Id of the note to view (required)'),
882
+ },
883
+ annotations: ANNOTATIONS.READ_ONLY,
884
+ },
885
+ wrapHandler('planko_view_note', async ({ taskId }) => {
886
+ try {
887
+ return await handleView(taskId);
888
+ } catch (err) {
889
+ return toolError(`View note failed: ${err.message}`);
890
+ }
891
+ })
892
+ );
893
+
894
+ // ---- planko_view_sticky_note ----
895
+ server.registerTool(
896
+ 'planko_view_sticky_note',
897
+ {
898
+ title: 'View sticky note',
899
+ description: 'View one Planko sticky note by id, with its description rendered as Markdown. The type is informational — this endpoint returns the item regardless of task/note/sticky-note type.',
900
+ inputSchema: {
901
+ taskId: objectId.describe('Id of the sticky note to view (required)'),
902
+ },
903
+ annotations: ANNOTATIONS.READ_ONLY,
904
+ },
905
+ wrapHandler('planko_view_sticky_note', async ({ taskId }) => {
906
+ try {
907
+ return await handleView(taskId);
908
+ } catch (err) {
909
+ return toolError(`View sticky note failed: ${err.message}`);
910
+ }
911
+ })
912
+ );
913
+ }