kanban-zone-mcp-server 0.3.6 → 0.5.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [Model Context Protocol](https://modelcontextprotocol.io/) server that lets AI assistants (Claude Desktop, Claude Code, Cursor, VS Code, Windsurf, and any MCP client) drive your [Kanban Zone](https://kanbanzone.com) workspace via the public API.
4
4
 
5
- 27 tools across boards, cards, comments, checklists, tasks, and labels. No delete operations.
5
+ 33 tools across boards, cards, comments, links, attachments, checklists, tasks, and labels. The only delete is unlinking two cards.
6
6
 
7
7
  **Two ways to connect.** The **hosted server** at `https://mcp.kanbanzone.io/mcp` is the recommended option for every client, Claude Desktop included — paste the URL, sign in with your Kanban Zone account, done. Nothing to install, no API key to manage, and you always get the current tool set. The **local install** (this npm package) runs the same server on your own machine over stdio — for stdio-only clients, unattended setups like CI where a browser sign-in isn't possible, restricted networks, or developing against a fork.
8
8
 
@@ -13,6 +13,8 @@
13
13
  - Inspect a card's history and time-in-column metrics.
14
14
  - Create, get, and update labels.
15
15
  - Add comments.
16
+ - Link cards as parent and child or predecessor and successor, change a link's type, and unlink them.
17
+ - List a card's attachments and get a download link for one.
16
18
  - Create, update, and list checklists — including bulk task creation in a single call.
17
19
  - Create, update, and move tasks.
18
20
 
@@ -78,7 +80,7 @@ The server validates the key on startup. A missing or malformed value (no `:` se
78
80
 
79
81
  ## Tools
80
82
 
81
- 27 tools, all prefixed with `kanbanzone_`:
83
+ 33 tools, all prefixed with `kanbanzone_`:
82
84
 
83
85
  | Group | Tools |
84
86
  | --- | --- |
@@ -86,6 +88,8 @@ The server validates the key on startup. A missing or malformed value (no `:` se
86
88
  | **Boards** | `list_boards`, `get_board`, `list_board_columns`, `list_board_labels`, `list_board_members`, `list_board_custom_fields` |
87
89
  | **Cards** | `create_card`, `list_cards`, `get_card`, `update_card`, `move_card`, `get_card_history`, `get_card_metrics`, `search_cards` |
88
90
  | **Comments** | `create_comment`, `list_card_comments` |
91
+ | **Links** | `list_card_links`, `create_card_link`, `update_card_link`, `delete_card_link` |
92
+ | **Attachments** | `list_card_attachments`, `get_card_attachment` |
89
93
  | **Checklists** | `create_checklist`, `update_checklist`, `list_card_checklists` |
90
94
  | **Tasks** | `create_task`, `update_task`, `move_task` |
91
95
  | **Labels** | `create_label`, `get_label`, `update_label` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kanban-zone-mcp-server",
3
- "version": "0.3.6",
3
+ "version": "0.5.0",
4
4
  "description": "Model Context Protocol server for the Kanban Zone public API",
5
5
  "license": "MIT",
6
6
  "homepage": "https://docs.kanbanzone.io/mcp",
package/src/client.js CHANGED
@@ -90,6 +90,8 @@ const makeApiRequest = async (endpoint, { method = 'GET', body, query } = {}) =>
90
90
  return response.data;
91
91
  };
92
92
 
93
+ const secondsText = seconds => (String(seconds) === '1' ? '1 second' : `${seconds} seconds`);
94
+
93
95
  const handleApiError = error => {
94
96
  if (axios.isAxiosError(error)) {
95
97
  const status = error.response && error.response.status;
@@ -113,6 +115,10 @@ const handleApiError = error => {
113
115
  : 'Not found. Double-check the ID — and for mirror cards, pass the `board` (publicId) parameter.';
114
116
  }
115
117
  if (status === 429) {
118
+ const retryAfterSeconds = error.response.headers && error.response.headers['retry-after'];
119
+ if (/^\d+$/.test(retryAfterSeconds)) {
120
+ return `Rate limit reached. Try again in ${secondsText(retryAfterSeconds)}.`;
121
+ }
116
122
  return 'Rate limit exceeded. Wait a moment before retrying.';
117
123
  }
118
124
  if (status && status >= 500) {
package/src/constants.js CHANGED
@@ -1,3 +1,5 @@
1
+ const { version: SERVER_VERSION } = require('../package.json');
2
+
1
3
  const DEFAULT_BASE_URL = 'https://integrations.kanbanzone.io/v1';
2
4
 
3
5
  // List tools that exceed this halve their results and return a `truncated` note,
@@ -8,7 +10,6 @@ const DEFAULT_PAGE_SIZE = 20;
8
10
  const MAX_PAGE_SIZE = 100;
9
11
 
10
12
  const SERVER_NAME = 'kanban-zone-mcp-server';
11
- const SERVER_VERSION = '0.3.4';
12
13
 
13
14
  const REQUEST_TIMEOUT_MS = 30000;
14
15
 
package/src/format.js CHANGED
@@ -20,6 +20,9 @@ const RICH_TEXT_HELP =
20
20
 
21
21
  const toJsonString = value => JSON.stringify(value, null, 2);
22
22
 
23
+ // A card number reads as "#302", an ObjectId as itself.
24
+ const cardLabel = ref => (/^\d+$/.test(ref) ? `#${ref}` : ref);
25
+
23
26
  // Caller passes the full rendered string and a `rerender(items)` callback so we can
24
27
  // shrink the items array and re-render until we're under CHARACTER_LIMIT.
25
28
  const truncateIfNeeded = ({ items, rendered, rerender }) => {
@@ -45,5 +48,6 @@ module.exports = {
45
48
  ResponseFormat,
46
49
  responseFormatField,
47
50
  toJsonString,
51
+ cardLabel,
48
52
  truncateIfNeeded,
49
53
  };
package/src/schemas.js CHANGED
@@ -20,10 +20,43 @@ const isoDateField = z.string().refine(value => !Number.isNaN(Date.parse(value))
20
20
  message: 'Must be an ISO-8601 date or datetime string',
21
21
  });
22
22
 
23
+ // The link and attachment endpoints name a card by its number as well as its ObjectId.
24
+ const CARD_REF_HELP = 'card number (e.g. 302) or card ObjectId';
25
+ const CARD_REF_PATTERN = /^#?(\d+|[a-f0-9]{24})$/i;
26
+ const CARD_REF_MESSAGE = 'Must be a card number (e.g. 302) or a 24-character ObjectId';
27
+
28
+ // A card's link: …/b/<board publicId>/c/<number>, optionally followed by a slug of its title.
29
+ const CARD_LINK_PATTERN = /\/b\/([A-Za-z0-9]{6,12})\/c\/(\d+)/;
30
+
31
+ const cardRefField = z
32
+ .union([z.number().int().min(1), z.string().regex(CARD_REF_PATTERN, CARD_REF_MESSAGE)])
33
+ .describe(`The ${CARD_REF_HELP}.`);
34
+
35
+ const cardLocatorField = z
36
+ .union([
37
+ z.number().int().min(1),
38
+ z.string().regex(CARD_REF_PATTERN, CARD_REF_MESSAGE),
39
+ z.string().regex(CARD_LINK_PATTERN, 'Must be a card link ending in /b/<board>/c/<number>'),
40
+ ])
41
+ .describe(`The ${CARD_REF_HELP}, or the card's link.`);
42
+
43
+ const cardRef = value => String(value).replace(/^#/, '');
44
+
45
+ // A link also names the board it was opened on, which picks the copy of a mirrored card.
46
+ const resolveCardLocator = value => {
47
+ const link = typeof value === 'string' && value.match(CARD_LINK_PATTERN);
48
+ return link ? { ref: link[2], board: link[1] } : { ref: cardRef(value), board: undefined };
49
+ };
50
+
23
51
  module.exports = {
24
52
  objectIdField,
25
53
  boardPublicIdField,
26
54
  pageField,
27
55
  countField,
28
56
  isoDateField,
57
+ CARD_REF_HELP,
58
+ cardRefField,
59
+ cardLocatorField,
60
+ cardRef,
61
+ resolveCardLocator,
29
62
  };
@@ -0,0 +1,126 @@
1
+ const { makeApiRequest, safeRun } = require('../client');
2
+ const { responseFormatField, ResponseFormat, toJsonString, truncateIfNeeded, cardLabel } = require('../format');
3
+ const { CARD_REF_HELP, cardRefField, cardRef, objectIdField } = require('../schemas');
4
+
5
+ const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
6
+
7
+ const LINK_SOURCES = { GOOGLE: 'Google Drive', DROPBOX: 'Dropbox', ONEDRIVE: 'OneDrive', BOX: 'Box', URL: 'web' };
8
+
9
+ const MB = 1024 * 1024;
10
+ const formatSize = bytes => (bytes < MB ? `${Math.max(1, Math.round(bytes / 1024))} KB` : `${(bytes / MB).toFixed(1)} MB`);
11
+
12
+ // "PDF file, 2.3 MB" for an uploaded file, "Google Drive link" for a linked one.
13
+ const describeKind = attachment => {
14
+ if (attachment.source !== 'S3') return `${LINK_SOURCES[attachment.source] || attachment.source} link`;
15
+ return attachment.fileSize ? `${attachment.type} file, ${formatSize(attachment.fileSize)}` : `${attachment.type} file`;
16
+ };
17
+
18
+ // Signed download links are long and expire within the hour, so lists leave them out.
19
+ const withoutLinks = ({ url, thumbnail, ...attachment }) => attachment;
20
+
21
+ const renderAttachmentLine = attachment => {
22
+ const added = attachment.createdAt ? `, added ${attachment.createdAt.slice(0, 10)}` : '';
23
+ const by = attachment.owner ? ` by ${attachment.owner}` : '';
24
+ return `- **${attachment.name}** — ${describeKind(attachment)}${added}${by} (\`${attachment._id}\`)`;
25
+ };
26
+
27
+ const registerAttachmentsTools = server => {
28
+ server.registerTool(
29
+ 'kanbanzone_list_card_attachments',
30
+ {
31
+ title: "List a card's attachments",
32
+ description: [
33
+ "List the files and links in a card's Attachments section, oldest first: name, kind, size, who",
34
+ 'added it and when, and its id. Download links are left out; get one with',
35
+ 'kanbanzone_get_card_attachment.',
36
+ '',
37
+ 'Args:',
38
+ ` - card (string | number, required): ${CARD_REF_HELP}.`,
39
+ ' - response_format ("markdown" | "json").',
40
+ '',
41
+ 'Examples:',
42
+ ' - "What files are attached to card 302?"',
43
+ ].join('\n'),
44
+ inputSchema: {
45
+ card: cardRefField,
46
+ response_format: responseFormatField,
47
+ },
48
+ annotations: READ,
49
+ },
50
+ async ({ card, response_format }) =>
51
+ safeRun(async () => {
52
+ const ref = cardRef(card);
53
+ const data = await makeApiRequest(`/cards/${ref}/attachments`);
54
+ const attachments = (data.attachments || []).map(withoutLinks);
55
+
56
+ if (response_format === ResponseFormat.JSON) {
57
+ return {
58
+ content: [{ type: 'text', text: toJsonString(attachments) }],
59
+ structuredContent: { attachments },
60
+ };
61
+ }
62
+ if (!attachments.length) {
63
+ return {
64
+ content: [{ type: 'text', text: `Card ${cardLabel(ref)} has no attachments.` }],
65
+ structuredContent: { attachments },
66
+ };
67
+ }
68
+
69
+ const rerender = list =>
70
+ [
71
+ `# Attachments on card ${cardLabel(ref)} (${list.length})`,
72
+ '',
73
+ ...list.map(renderAttachmentLine),
74
+ ].join('\n');
75
+ const { text } = truncateIfNeeded({ items: attachments, rendered: rerender(attachments), rerender });
76
+ return { content: [{ type: 'text', text }], structuredContent: { attachments } };
77
+ })
78
+ );
79
+
80
+ server.registerTool(
81
+ 'kanbanzone_get_card_attachment',
82
+ {
83
+ title: 'Get a download link for an attachment',
84
+ description: [
85
+ "Get the download link of one of a card's attachments. An uploaded file gets a signed link that",
86
+ 'works for about an hour; Google Drive, Dropbox, Box, OneDrive and web links come back as they',
87
+ 'are. The file itself is not returned.',
88
+ '',
89
+ 'Args:',
90
+ ` - card (string | number, required): ${CARD_REF_HELP}.`,
91
+ ' - attachment (string, required): attachment ObjectId, as listed by kanbanzone_list_card_attachments.',
92
+ '',
93
+ 'Examples:',
94
+ ' - "Give me a link to the contract on card 302"',
95
+ ].join('\n'),
96
+ inputSchema: {
97
+ card: cardRefField,
98
+ attachment: objectIdField,
99
+ },
100
+ annotations: READ,
101
+ },
102
+ async ({ card, attachment }) =>
103
+ safeRun(async () => {
104
+ const ref = cardRef(card);
105
+ const data = await makeApiRequest(`/cards/${ref}/attachments`);
106
+ const found = (data.attachments || []).find(item => item._id === attachment.toLowerCase());
107
+ if (!found) {
108
+ return {
109
+ isError: true,
110
+ content: [
111
+ { type: 'text', text: `Not found: card ${cardLabel(ref)} has no attachment ${attachment}.` },
112
+ ],
113
+ };
114
+ }
115
+
116
+ const expiry =
117
+ found.source === 'S3' ? '\n\nThe link works for about an hour; get a new one when it expires.' : '';
118
+ return {
119
+ content: [{ type: 'text', text: `**${found.name}** (${describeKind(found)}): ${found.url}${expiry}` }],
120
+ structuredContent: found,
121
+ };
122
+ })
123
+ );
124
+ };
125
+
126
+ module.exports = { registerAttachmentsTools };
@@ -2,7 +2,16 @@ const { z } = require('zod');
2
2
  const { makeApiRequest, safeRun } = require('../client');
3
3
  const { responseFormatField, ResponseFormat, toJsonString, truncateIfNeeded, RICH_TEXT_HELP } = require('../format');
4
4
  const { richTextBody } = require('../markdown');
5
- const { objectIdField, boardPublicIdField, pageField, countField, isoDateField } = require('../schemas');
5
+ const {
6
+ objectIdField,
7
+ boardPublicIdField,
8
+ pageField,
9
+ countField,
10
+ isoDateField,
11
+ CARD_REF_HELP,
12
+ cardLocatorField,
13
+ resolveCardLocator,
14
+ } = require('../schemas');
6
15
 
7
16
  const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
8
17
  const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
@@ -18,6 +27,14 @@ const renderCardLine = card => {
18
27
  return `- ${number}**${c.title}** (\`${id}\`)${owner}`;
19
28
  };
20
29
 
30
+ // GET /cards/{id} nests the card under CardItem.
31
+ const renderCard = data => {
32
+ const c = data.CardItem || data;
33
+ const number = c.number !== undefined ? `#${c.number} ` : '';
34
+ const description = c.description ? `\n- **description**: ${c.description}` : '';
35
+ return `# ${number}${c.title}\n- **id**: ${data._id}${description}`;
36
+ };
37
+
21
38
  // History events are `type` (entity.verb) plus the changed `field`; `action` is the deprecated pair
22
39
  // still sent by older backends.
23
40
  const renderHistoryLine = ev => {
@@ -113,7 +130,7 @@ const registerCardsTools = server => {
113
130
  ' - columns (string, optional): comma-separated column ObjectIds to restrict to.',
114
131
  ' - owner (string, optional): account ObjectId or email — only cards owned by this person.',
115
132
  ' - label (string, optional): label ObjectId or description string.',
116
- ' - days_since_last_update (number, optional): only cards untouched for N+ days.',
133
+ ' - days_since_last_update (number, optional): only cards updated within the last N days.',
117
134
  ' - include_archived (boolean, optional): include archived cards.',
118
135
  ' - number (number, optional): fetch a single card by its #N number.',
119
136
  ' - page (number, optional, default 1).',
@@ -198,18 +215,19 @@ const registerCardsTools = server => {
198
215
  {
199
216
  title: 'Get a card',
200
217
  description: [
201
- 'Fetch one card by its ObjectId.',
218
+ 'Fetch one card by its number, ObjectId or link.',
202
219
  '',
203
220
  'Args:',
204
- ' - id (string, required): card ObjectId.',
205
- ' - board (string, optional): board publicId — required for mirror cards to disambiguate.',
221
+ ` - id (string | number, required): ${CARD_REF_HELP}, or the card's link, which ends in /b/<board>/c/<number>.`,
222
+ ' - board (string, optional): board publicId — required for mirror cards to disambiguate. A link already names it.',
206
223
  ' - response_format ("markdown" | "json").',
207
224
  '',
208
225
  'Examples:',
209
- ' - "Show me card 6700aabbccddeeff00112233"',
226
+ ' - "Show me card 28407"',
227
+ ' - "Review this card: <a card link>"',
210
228
  ].join('\n'),
211
229
  inputSchema: {
212
- id: objectIdField,
230
+ id: cardLocatorField,
213
231
  board: boardPublicIdField.optional(),
214
232
  response_format: responseFormatField,
215
233
  },
@@ -217,11 +235,9 @@ const registerCardsTools = server => {
217
235
  },
218
236
  async ({ id, board, response_format }) =>
219
237
  safeRun(async () => {
220
- const data = await makeApiRequest(`/cards/${id}`, { query: { board } });
221
- const text =
222
- response_format === ResponseFormat.JSON
223
- ? toJsonString(data)
224
- : `# ${data.title}\n- **id**: ${data._id}${data.description ? `\n- **description**: ${data.description}` : ''}`;
238
+ const card = resolveCardLocator(id);
239
+ const data = await makeApiRequest(`/cards/${card.ref}`, { query: { board: board || card.board } });
240
+ const text = response_format === ResponseFormat.JSON ? toJsonString(data) : renderCard(data);
225
241
  return { content: [{ type: 'text', text }], structuredContent: data };
226
242
  })
227
243
  );
@@ -235,7 +251,7 @@ const registerCardsTools = server => {
235
251
  '',
236
252
  'Args:',
237
253
  ' - id (string, required): card ObjectId.',
238
- ' - board (string, optional): board publicId — required for mirror cards to disambiguate.',
254
+ " - board (string, optional): for a mirrored card, the board publicId of the copy whose owner, watchers and label change. Without it, the copy on the board the card was made on changes, or else the card's oldest copy.",
239
255
  ' - title (string, optional)',
240
256
  ` - description (string, optional): ${RICH_TEXT_HELP}`,
241
257
  ' - owner (string, optional): account email or ObjectId.',
@@ -294,30 +310,32 @@ const registerCardsTools = server => {
294
310
  title: 'Move a card',
295
311
  description: [
296
312
  'Move a card to a different column (and optionally a different board).',
313
+ 'The card goes to the board that owns the column.',
297
314
  '',
298
315
  'Args:',
299
316
  ' - id (string, required): card ObjectId.',
300
- ' - board (string, required): destination board publicId.',
301
317
  ' - column (string, required): destination column ObjectId.',
302
- ' - position (number, optional): 0-based position within the destination column.',
318
+ " - from_board (string, optional): for a mirrored card, the board publicId of the copy to move. Without it, the copy already on the column's board moves, or, to another board, the card's newest copy.",
319
+ ' - add_to_top (boolean, optional): false puts the card last in the column; by default it goes on top. A column that sorts itself places the card by its sort.',
303
320
  '',
304
321
  'Examples:',
305
322
  ' - "Move card 670... to the In Progress column"',
323
+ ' - "Move the copy of card 670... that is on board Hds5Zuks to the Done column of board OeMrbG8g"',
306
324
  ].join('\n'),
307
325
  inputSchema: {
308
326
  id: objectIdField,
309
- board: boardPublicIdField,
310
327
  column: objectIdField,
311
- position: z.number().int().min(0).optional(),
328
+ from_board: boardPublicIdField.optional(),
329
+ add_to_top: z.boolean().optional(),
312
330
  },
313
331
  annotations: IDEMPOTENT_WRITE,
314
332
  },
315
- async ({ id, board, column, position }) =>
333
+ async ({ id, column, from_board: fromBoard, add_to_top: addToTop }) =>
316
334
  safeRun(async () => {
317
- const data = await makeApiRequest(`/cards/${id}/move`, {
318
- method: 'POST',
319
- body: { board, columnId: column, position },
320
- });
335
+ const body = { columnId: column };
336
+ if (fromBoard) body.board = fromBoard;
337
+ if (addToTop !== undefined) body.addToTop = addToTop;
338
+ const data = await makeApiRequest(`/cards/${id}/move`, { method: 'POST', body });
321
339
  return {
322
340
  content: [{ type: 'text', text: `Moved card to column ${column}.` }],
323
341
  structuredContent: data,
@@ -74,29 +74,33 @@ const registerChecklistsTools = server => {
74
74
  {
75
75
  title: 'Update a checklist',
76
76
  description: [
77
- 'Update title or position of a checklist on a card.',
77
+ 'Update the title or position of a checklist on a card, or hide or show it.',
78
78
  '',
79
79
  'Args:',
80
80
  ' - id (string, required): checklist ObjectId.',
81
81
  ' - title (string, optional)',
82
82
  ' - position (number, optional, ≥0)',
83
+ " - is_hidden (boolean, optional): true leaves the checklist off the card in the web and mobile apps, its tasks still counted in the card's totals; false shows it again.",
83
84
  '',
84
85
  'Examples:',
85
86
  ' - "Rename checklist 670... to \'QA tasks\'"',
86
87
  ' - "Move checklist 670... to position 0"',
88
+ ' - "Hide checklist 670... on its card"',
87
89
  ].join('\n'),
88
90
  inputSchema: {
89
91
  id: objectIdField,
90
92
  title: z.string().max(200).optional(),
91
93
  position: z.number().int().min(0).optional(),
94
+ is_hidden: z.boolean().optional(),
92
95
  },
93
96
  annotations: IDEMPOTENT_WRITE,
94
97
  },
95
- async ({ id, title, position }) =>
98
+ async ({ id, title, position, is_hidden }) =>
96
99
  safeRun(async () => {
97
100
  const updates = {};
98
101
  if (title !== undefined) updates.title = title;
99
102
  if (position !== undefined) updates.position = position;
103
+ if (is_hidden !== undefined) updates.isHidden = is_hidden;
100
104
  const data = await makeApiRequest(`/checklists/${id}`, { method: 'PATCH', body: updates });
101
105
  return {
102
106
  content: [{ type: 'text', text: `Updated checklist ${id}.` }],
@@ -139,7 +143,8 @@ const registerChecklistsTools = server => {
139
143
 
140
144
  const renderChecklist = checklist => {
141
145
  const tasks = Array.isArray(checklist.tasks) ? checklist.tasks : [];
142
- const lines = [`## ${checklist.title || '(untitled)'} (\`${checklist._id}\`)`];
146
+ const hidden = checklist.isHidden ? ' (hidden)' : '';
147
+ const lines = [`## ${checklist.title || '(untitled)'} (\`${checklist._id}\`)${hidden}`];
143
148
  for (const task of tasks) {
144
149
  const box = task.completed ? '[x]' : '[ ]';
145
150
  lines.push(`- ${box} ${task.description} (\`${task._id}\`)`);
@@ -2,6 +2,8 @@ const { registerOrganizationTools } = require('./organization');
2
2
  const { registerBoardsTools } = require('./boards');
3
3
  const { registerCardsTools } = require('./cards');
4
4
  const { registerCommentsTools } = require('./comments');
5
+ const { registerLinksTools } = require('./links');
6
+ const { registerAttachmentsTools } = require('./attachments');
5
7
  const { registerChecklistsTools } = require('./checklists');
6
8
  const { registerTasksTools } = require('./tasks');
7
9
  const { registerLabelsTools } = require('./labels');
@@ -11,6 +13,8 @@ const registerAllTools = server => {
11
13
  registerBoardsTools(server);
12
14
  registerCardsTools(server);
13
15
  registerCommentsTools(server);
16
+ registerLinksTools(server);
17
+ registerAttachmentsTools(server);
14
18
  registerChecklistsTools(server);
15
19
  registerTasksTools(server);
16
20
  registerLabelsTools(server);
@@ -0,0 +1,171 @@
1
+ const { z } = require('zod');
2
+ const { makeApiRequest, safeRun } = require('../client');
3
+ const { responseFormatField, ResponseFormat, toJsonString, truncateIfNeeded, cardLabel } = require('../format');
4
+ const { CARD_REF_HELP, cardRefField, cardRef } = require('../schemas');
5
+
6
+ const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
7
+ const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
8
+ const IDEMPOTENT_WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true };
9
+ const DESTRUCTIVE = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true };
10
+
11
+ const linkTypeField = z
12
+ .enum(['parent', 'child', 'predecessor', 'successor'])
13
+ .describe("What to_card becomes to card: 'parent' makes it card's parent, 'predecessor' puts it before card.");
14
+
15
+ const TYPE_ARG = " - type (string, required): what to_card becomes to card: 'parent', 'child', 'predecessor' or 'successor'.";
16
+
17
+ const describeLink = (ref, link) => `Card #${link.card} is now the ${link.type} of card ${cardLabel(ref)}.`;
18
+
19
+ const registerLinksTools = server => {
20
+ server.registerTool(
21
+ 'kanbanzone_list_card_links',
22
+ {
23
+ title: "List a card's links to other cards",
24
+ description: [
25
+ 'List the cards a card is linked to, by number, with the type of each link: what the other card',
26
+ 'is to this one (parent, child, predecessor or successor). Links to web pages are not included.',
27
+ '',
28
+ 'Args:',
29
+ ` - card (string | number, required): ${CARD_REF_HELP}.`,
30
+ ' - response_format ("markdown" | "json").',
31
+ '',
32
+ 'Examples:',
33
+ ' - "What is card 302 linked to?"',
34
+ ' - "Which cards have to be done before card 302?"',
35
+ ].join('\n'),
36
+ inputSchema: {
37
+ card: cardRefField,
38
+ response_format: responseFormatField,
39
+ },
40
+ annotations: READ,
41
+ },
42
+ async ({ card, response_format }) =>
43
+ safeRun(async () => {
44
+ const ref = cardRef(card);
45
+ const data = await makeApiRequest(`/cards/${ref}/links`);
46
+ const links = data.links || [];
47
+
48
+ if (response_format === ResponseFormat.JSON) {
49
+ return { content: [{ type: 'text', text: toJsonString(links) }], structuredContent: { links } };
50
+ }
51
+ if (!links.length) {
52
+ return {
53
+ content: [{ type: 'text', text: `Card ${cardLabel(ref)} has no links to other cards.` }],
54
+ structuredContent: { links },
55
+ };
56
+ }
57
+
58
+ const rerender = list =>
59
+ [
60
+ `# Links on card ${cardLabel(ref)} (${list.length})`,
61
+ '',
62
+ ...list.map(link => `- ${link.type}: #${link.card}`),
63
+ ].join('\n');
64
+ const { text } = truncateIfNeeded({ items: links, rendered: rerender(links), rerender });
65
+ return { content: [{ type: 'text', text }], structuredContent: { links } };
66
+ })
67
+ );
68
+
69
+ server.registerTool(
70
+ 'kanbanzone_create_card_link',
71
+ {
72
+ title: 'Link two cards',
73
+ description: [
74
+ 'Link a card to another card in the organization, on the same board or another one. The other card',
75
+ "gets the opposite link: parent and child, predecessor and successor. Needs edit access to both cards'",
76
+ 'boards. Two cards can be linked only once; change the type with kanbanzone_update_card_link.',
77
+ '',
78
+ 'Args:',
79
+ ` - card (string | number, required): ${CARD_REF_HELP}.`,
80
+ ` - to_card (string | number, required): the card to link to, as a ${CARD_REF_HELP}.`,
81
+ TYPE_ARG,
82
+ '',
83
+ 'Examples:',
84
+ ' - "Make card 305 the parent of card 302" (card 302, to_card 305, type parent)',
85
+ ' - "Card 410 has to be done before card 412" (card 412, to_card 410, type predecessor)',
86
+ ].join('\n'),
87
+ inputSchema: {
88
+ card: cardRefField,
89
+ to_card: cardRefField,
90
+ type: linkTypeField,
91
+ },
92
+ annotations: WRITE,
93
+ },
94
+ async ({ card, to_card, type }) =>
95
+ safeRun(async () => {
96
+ const ref = cardRef(card);
97
+ const data = await makeApiRequest(`/cards/${ref}/links`, {
98
+ method: 'POST',
99
+ body: { toCard: cardRef(to_card), type },
100
+ });
101
+ return { content: [{ type: 'text', text: describeLink(ref, data) }], structuredContent: data };
102
+ })
103
+ );
104
+
105
+ server.registerTool(
106
+ 'kanbanzone_update_card_link',
107
+ {
108
+ title: 'Change the type of a card link',
109
+ description: [
110
+ "Change what a linked card is to this card. The other card's side of the link changes to the",
111
+ 'opposite type.',
112
+ '',
113
+ 'Args:',
114
+ ` - card (string | number, required): ${CARD_REF_HELP}.`,
115
+ ` - to_card (string | number, required): the linked card, as a ${CARD_REF_HELP}.`,
116
+ TYPE_ARG,
117
+ '',
118
+ 'Examples:',
119
+ ' - "Card 305 should be a child of card 302, not its parent" (card 302, to_card 305, type child)',
120
+ ].join('\n'),
121
+ inputSchema: {
122
+ card: cardRefField,
123
+ to_card: cardRefField,
124
+ type: linkTypeField,
125
+ },
126
+ annotations: IDEMPOTENT_WRITE,
127
+ },
128
+ async ({ card, to_card, type }) =>
129
+ safeRun(async () => {
130
+ const ref = cardRef(card);
131
+ const data = await makeApiRequest(`/cards/${ref}/links/${cardRef(to_card)}`, {
132
+ method: 'PATCH',
133
+ body: { type },
134
+ });
135
+ return { content: [{ type: 'text', text: describeLink(ref, data) }], structuredContent: data };
136
+ })
137
+ );
138
+
139
+ server.registerTool(
140
+ 'kanbanzone_delete_card_link',
141
+ {
142
+ title: 'Unlink two cards',
143
+ description: [
144
+ 'Remove the link between two cards, from both of them. Only the link goes; both cards stay.',
145
+ '',
146
+ 'Args:',
147
+ ` - card (string | number, required): ${CARD_REF_HELP}.`,
148
+ ` - to_card (string | number, required): the linked card, as a ${CARD_REF_HELP}.`,
149
+ '',
150
+ 'Examples:',
151
+ ' - "Card 305 no longer has anything to do with card 302"',
152
+ ].join('\n'),
153
+ inputSchema: {
154
+ card: cardRefField,
155
+ to_card: cardRefField,
156
+ },
157
+ annotations: DESTRUCTIVE,
158
+ },
159
+ async ({ card, to_card }) =>
160
+ safeRun(async () => {
161
+ const ref = cardRef(card);
162
+ const toRef = cardRef(to_card);
163
+ await makeApiRequest(`/cards/${ref}/links/${toRef}`, { method: 'DELETE' });
164
+ return {
165
+ content: [{ type: 'text', text: `Unlinked card ${cardLabel(ref)} and card ${cardLabel(toRef)}.` }],
166
+ };
167
+ })
168
+ );
169
+ };
170
+
171
+ module.exports = { registerLinksTools };