@monadsag/productive-mcp 1.2.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +190 -0
  2. package/NOTICE +6 -0
  3. package/README.md +353 -0
  4. package/build/api/bookings-client.js +249 -0
  5. package/build/api/capacity.js +279 -0
  6. package/build/api/client.js +1296 -0
  7. package/build/api/errors.js +50 -0
  8. package/build/api/invoice-time-entries.js +256 -0
  9. package/build/api/pages-tree.js +106 -0
  10. package/build/api/time-entry-notes.js +75 -0
  11. package/build/api/types.js +1 -0
  12. package/build/auth/logo.js +21 -0
  13. package/build/auth/self-resolver.js +61 -0
  14. package/build/config/index.js +24 -0
  15. package/build/index.js +15 -0
  16. package/build/prompts/timesheet.js +285 -0
  17. package/build/server.js +55 -0
  18. package/build/tools/absences.js +502 -0
  19. package/build/tools/activities.js +140 -0
  20. package/build/tools/bookings.js +531 -0
  21. package/build/tools/budget-services.js +168 -0
  22. package/build/tools/budgets.js +276 -0
  23. package/build/tools/capacity.js +281 -0
  24. package/build/tools/changeset.js +41 -0
  25. package/build/tools/comments.js +469 -0
  26. package/build/tools/companies.js +73 -0
  27. package/build/tools/custom-field-resolver.js +92 -0
  28. package/build/tools/custom-fields.js +155 -0
  29. package/build/tools/folders.js +516 -0
  30. package/build/tools/include-resolver.js +45 -0
  31. package/build/tools/invoice-actions.js +476 -0
  32. package/build/tools/invoice-defaults.js +65 -0
  33. package/build/tools/invoice-time-entries.js +320 -0
  34. package/build/tools/invoices.js +657 -0
  35. package/build/tools/my-tasks.js +100 -0
  36. package/build/tools/page-children.js +129 -0
  37. package/build/tools/pages.js +466 -0
  38. package/build/tools/people.js +147 -0
  39. package/build/tools/projects.js +77 -0
  40. package/build/tools/recent-updates.js +112 -0
  41. package/build/tools/registry.js +409 -0
  42. package/build/tools/subtasks.js +245 -0
  43. package/build/tools/task-backlog.js +106 -0
  44. package/build/tools/task-dependencies.js +244 -0
  45. package/build/tools/task-list-move.js +65 -0
  46. package/build/tools/task-lists.js +535 -0
  47. package/build/tools/task-reposition.js +199 -0
  48. package/build/tools/task-status.js +178 -0
  49. package/build/tools/tasks.js +738 -0
  50. package/build/tools/time-entries.js +736 -0
  51. package/build/tools/time-entry-approval.js +103 -0
  52. package/build/tools/time-entry-delete.js +72 -0
  53. package/build/tools/time-entry-update.js +126 -0
  54. package/build/tools/timers.js +195 -0
  55. package/build/tools/todos.js +342 -0
  56. package/build/tools/tool-helpers.js +114 -0
  57. package/build/tools/toolsets.js +153 -0
  58. package/build/tools/whoami.js +64 -0
  59. package/build/tools/workflow-statuses.js +81 -0
  60. package/build/utils/errors.js +67 -0
  61. package/build/utils/mentions.js +98 -0
  62. package/npm-shrinkwrap.json +1159 -0
  63. package/package.json +79 -0
@@ -0,0 +1,469 @@
1
+ import { z } from 'zod';
2
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
3
+ import { resolveMentions } from '../utils/mentions.js';
4
+ import { toMcpError } from '../utils/errors.js';
5
+ function resolvePersonName(personId, included) {
6
+ if (!personId || !included)
7
+ return undefined;
8
+ const person = included.find((item) => item.type === 'people' && item.id === personId);
9
+ if (!person)
10
+ return undefined;
11
+ const first = person.attributes.first_name || '';
12
+ const last = person.attributes.last_name || '';
13
+ return `${first} ${last}`.trim() || undefined;
14
+ }
15
+ function truncateBody(body, maxLength = 200) {
16
+ if (!body)
17
+ return '(no content)';
18
+ if (body.length <= maxLength)
19
+ return body;
20
+ return body.substring(0, maxLength) + '...';
21
+ }
22
+ function formatMentionFeedback(result) {
23
+ let feedback = '';
24
+ if (result.resolved.length > 0) {
25
+ feedback += `\nMentions resolved: ${result.resolved.map((r) => r.token.raw).join(', ')}`;
26
+ }
27
+ if (result.unresolved.length > 0) {
28
+ feedback += `\nWarning - unresolved mentions (left as plain text): ${result.unresolved.map((u) => u.raw).join(', ')}`;
29
+ }
30
+ return feedback;
31
+ }
32
+ function buildAmbiguousError(result) {
33
+ return result.ambiguous
34
+ .map((a) => `"${a.token.raw}" matches multiple people: ${a.candidates
35
+ .map((c) => `${c.attributes.first_name} ${c.attributes.last_name} (ID: ${c.id})`)
36
+ .join(', ')}`)
37
+ .join('\n');
38
+ }
39
+ // ---- Add Task Comment ----
40
+ const addTaskCommentSchema = z.object({
41
+ task_id: z.string().min(1, 'Task ID is required'),
42
+ comment: z.string().min(1, 'Comment text is required'),
43
+ hidden: z.boolean().optional(),
44
+ });
45
+ export async function addTaskCommentTool(client, args) {
46
+ try {
47
+ const params = addTaskCommentSchema.parse(args);
48
+ const mentionResult = await resolveMentions(params.comment, client);
49
+ if (mentionResult.ambiguous.length > 0) {
50
+ throw new McpError(ErrorCode.InvalidParams, `Ambiguous mentions found:\n${buildAmbiguousError(mentionResult)}\nPlease use full names to disambiguate.`);
51
+ }
52
+ const commentData = {
53
+ data: {
54
+ type: 'comments',
55
+ attributes: {
56
+ body: mentionResult.resolvedBody,
57
+ ...(params.hidden !== undefined ? { hidden: params.hidden } : {}),
58
+ },
59
+ relationships: {
60
+ task: {
61
+ data: {
62
+ id: params.task_id,
63
+ type: 'tasks',
64
+ },
65
+ },
66
+ },
67
+ },
68
+ };
69
+ const response = await client.createComment(commentData);
70
+ let text = params.hidden
71
+ ? `Hidden comment added successfully!\n`
72
+ : `Comment added successfully!\n`;
73
+ text += `Task ID: ${params.task_id}\n`;
74
+ text += `Comment: ${response.data.attributes.body}\n`;
75
+ text += `Comment ID: ${response.data.id}`;
76
+ if (response.data.attributes.hidden !== undefined) {
77
+ text += `\nHidden: ${response.data.attributes.hidden}`;
78
+ }
79
+ if (response.data.attributes.created_at) {
80
+ text += `\nCreated at: ${response.data.attributes.created_at}`;
81
+ }
82
+ text += formatMentionFeedback(mentionResult);
83
+ return {
84
+ content: [
85
+ {
86
+ type: 'text',
87
+ text: text,
88
+ },
89
+ ],
90
+ };
91
+ }
92
+ catch (error) {
93
+ throw toMcpError(error);
94
+ }
95
+ }
96
+ export const addTaskCommentDefinition = {
97
+ name: 'add_task_comment',
98
+ description: "Post a new comment onto a task's activity feed. Use this to leave a fresh note or to follow up on something surfaced by list_comments. Supports @mentions (e.g. @Jarrod Lawson) which are automatically resolved to notify the mentioned person. Set hidden to true to post an internal comment not visible to clients in the client portal. To change an existing comment instead, use update_comment; to acknowledge one without writing text, use add_comment_reaction.",
99
+ inputSchema: {
100
+ type: 'object',
101
+ properties: {
102
+ task_id: {
103
+ type: 'string',
104
+ description: 'ID of the task to add the comment to (required)',
105
+ },
106
+ comment: {
107
+ type: 'string',
108
+ description: 'Comment content (required). Plain text or HTML — supported tags include <div>, <p>, <strong>, <em>, <ul>, <li>, and <a href="">. Supports @mentions (e.g. @Jarrod Lawson) to notify a person.',
109
+ },
110
+ hidden: {
111
+ type: 'boolean',
112
+ description: 'When true, posts a hidden (internal) comment not visible to clients in the client portal. Defaults to false. Note: hidden comments are not available in internal projects.',
113
+ },
114
+ },
115
+ required: ['task_id', 'comment'],
116
+ },
117
+ annotations: {
118
+ title: 'Add task comment',
119
+ readOnlyHint: false,
120
+ destructiveHint: false,
121
+ idempotentHint: false,
122
+ openWorldHint: true,
123
+ },
124
+ };
125
+ // ---- List Comments ----
126
+ const listCommentsSchema = z.object({
127
+ task_id: z.string().optional(),
128
+ project_id: z.string().optional(),
129
+ limit: z.coerce.number().optional(),
130
+ });
131
+ export async function listCommentsTool(client, args) {
132
+ try {
133
+ const params = listCommentsSchema.parse(args);
134
+ const response = await client.listComments({
135
+ task_id: params.task_id,
136
+ project_id: params.project_id,
137
+ limit: params.limit,
138
+ });
139
+ if (!response.data || response.data.length === 0) {
140
+ return {
141
+ content: [{ type: 'text', text: 'No comments found.' }],
142
+ };
143
+ }
144
+ const commentsText = response.data
145
+ .map((comment) => {
146
+ const creatorId = comment.relationships?.creator?.data?.id;
147
+ const creatorName = resolvePersonName(creatorId, response.included) || `Person ${creatorId || 'unknown'}`;
148
+ const pinned = comment.attributes.pinned_at ? ' [PINNED]' : '';
149
+ const body = truncateBody(comment.attributes.body);
150
+ return `- Comment ID: ${comment.id}${pinned}\n By: ${creatorName}\n Date: ${comment.attributes.created_at}\n Body: ${body}`;
151
+ })
152
+ .join('\n\n');
153
+ return {
154
+ content: [{ type: 'text', text: `Comments (${response.data.length}):\n\n${commentsText}` }],
155
+ };
156
+ }
157
+ catch (error) {
158
+ throw toMcpError(error);
159
+ }
160
+ }
161
+ export const listCommentsDefinition = {
162
+ name: 'list_comments',
163
+ description: "List comments, each rendered with its body truncated to ~200 characters and a [PINNED] marker where applicable. Filter by task_id to read a single task's thread or by project_id to see a project's comments; omit both to list broadly. Use this to survey a thread, then call get_comment for one comment's full untruncated body and metadata. Returns up to `limit` comments.",
164
+ inputSchema: {
165
+ type: 'object',
166
+ properties: {
167
+ task_id: {
168
+ type: 'string',
169
+ description: "Filter to comments on a single task (the task's comment thread)",
170
+ },
171
+ project_id: {
172
+ type: 'string',
173
+ description: 'Filter to comments within a project',
174
+ },
175
+ limit: {
176
+ type: 'number',
177
+ description: 'Maximum number of comments to return',
178
+ },
179
+ },
180
+ },
181
+ annotations: { title: 'List comments', readOnlyHint: true, openWorldHint: true },
182
+ };
183
+ // ---- Get Comment ----
184
+ const getCommentSchema = z.object({
185
+ comment_id: z.string().min(1, 'Comment ID is required'),
186
+ });
187
+ export async function getCommentTool(client, args) {
188
+ try {
189
+ const params = getCommentSchema.parse(args);
190
+ const response = await client.getComment(params.comment_id);
191
+ const comment = response.data;
192
+ const attrs = comment.attributes;
193
+ const creatorId = comment.relationships?.creator?.data?.id;
194
+ const included = response.included;
195
+ const creatorName = resolvePersonName(creatorId, included) || `Person ${creatorId || 'unknown'}`;
196
+ let text = `Comment ID: ${comment.id}\n`;
197
+ text += `Body: ${attrs.body ?? '(no content)'}\n`;
198
+ text += `Commentable Type: ${attrs.commentable_type}\n`;
199
+ text += `Creator: ${creatorName}\n`;
200
+ text += `Created: ${attrs.created_at}\n`;
201
+ text += `Updated: ${attrs.updated_at}\n`;
202
+ if (attrs.edited_at)
203
+ text += `Edited: ${attrs.edited_at}\n`;
204
+ if (attrs.deleted_at)
205
+ text += `Deleted: ${attrs.deleted_at}\n`;
206
+ text += `Draft: ${attrs.draft ?? false}\n`;
207
+ text += `Hidden: ${attrs.hidden ?? false}\n`;
208
+ text += `Pinned: ${attrs.pinned_at ? `Yes (${attrs.pinned_at})` : 'No'}\n`;
209
+ if (attrs.reactions)
210
+ text += `Reactions: ${JSON.stringify(attrs.reactions)}\n`;
211
+ if (attrs.version_number !== undefined)
212
+ text += `Version: ${attrs.version_number}\n`;
213
+ return {
214
+ content: [{ type: 'text', text }],
215
+ };
216
+ }
217
+ catch (error) {
218
+ throw toMcpError(error);
219
+ }
220
+ }
221
+ export const getCommentDefinition = {
222
+ name: 'get_comment',
223
+ description: "Fetch one comment by ID with its complete untruncated body plus metadata that list_comments omits: creator, created/updated/edited/deleted timestamps, draft and hidden flags, pinned state, reactions, and version number. Use this when list_comments' 200-character preview isn't enough.",
224
+ inputSchema: {
225
+ type: 'object',
226
+ properties: {
227
+ comment_id: {
228
+ type: 'string',
229
+ description: 'The ID of the comment to retrieve (required)',
230
+ },
231
+ },
232
+ required: ['comment_id'],
233
+ },
234
+ annotations: { title: 'Get comment', readOnlyHint: true, openWorldHint: true },
235
+ };
236
+ // ---- Update Comment ----
237
+ const updateCommentSchema = z.object({
238
+ comment_id: z.string().min(1, 'Comment ID is required'),
239
+ body: z.string().min(1, 'Comment body is required'),
240
+ });
241
+ export async function updateCommentTool(client, args) {
242
+ try {
243
+ const params = updateCommentSchema.parse(args);
244
+ const mentionResult = await resolveMentions(params.body, client);
245
+ if (mentionResult.ambiguous.length > 0) {
246
+ throw new McpError(ErrorCode.InvalidParams, `Ambiguous mentions found:\n${buildAmbiguousError(mentionResult)}\nPlease use full names to disambiguate.`);
247
+ }
248
+ const response = await client.updateComment(params.comment_id, {
249
+ data: {
250
+ type: 'comments',
251
+ id: params.comment_id,
252
+ attributes: {
253
+ body: mentionResult.resolvedBody,
254
+ },
255
+ },
256
+ });
257
+ let text = `Comment ${params.comment_id} updated successfully.\nNew body: ${response.data.attributes.body}`;
258
+ text += formatMentionFeedback(mentionResult);
259
+ return {
260
+ content: [
261
+ {
262
+ type: 'text',
263
+ text,
264
+ },
265
+ ],
266
+ };
267
+ }
268
+ catch (error) {
269
+ throw toMcpError(error);
270
+ }
271
+ }
272
+ export const updateCommentDefinition = {
273
+ name: 'update_comment',
274
+ description: 'Replace the body of an existing comment. The new body overwrites the old one entirely — there is no append, so include any text you want to keep. Supports @mentions (e.g. @Jarrod Lawson) which are automatically resolved. To post a new comment instead of editing one, use add_task_comment.',
275
+ inputSchema: {
276
+ type: 'object',
277
+ properties: {
278
+ comment_id: {
279
+ type: 'string',
280
+ description: 'The ID of the comment to update (required)',
281
+ },
282
+ body: {
283
+ type: 'string',
284
+ description: 'The new comment body (required), which fully replaces the existing body. Plain text or HTML. Supports @mentions (e.g. @Jarrod Lawson).',
285
+ },
286
+ },
287
+ required: ['comment_id', 'body'],
288
+ },
289
+ annotations: {
290
+ title: 'Update comment',
291
+ readOnlyHint: false,
292
+ destructiveHint: false,
293
+ idempotentHint: true,
294
+ openWorldHint: true,
295
+ },
296
+ };
297
+ // ---- Delete Comment ----
298
+ const deleteCommentSchema = z.object({
299
+ comment_id: z.string().min(1, 'Comment ID is required'),
300
+ });
301
+ export async function deleteCommentTool(client, args) {
302
+ try {
303
+ const params = deleteCommentSchema.parse(args);
304
+ await client.deleteComment(params.comment_id);
305
+ return {
306
+ content: [
307
+ {
308
+ type: 'text',
309
+ text: `Comment ${params.comment_id} deleted successfully.`,
310
+ },
311
+ ],
312
+ };
313
+ }
314
+ catch (error) {
315
+ throw toMcpError(error);
316
+ }
317
+ }
318
+ export const deleteCommentDefinition = {
319
+ name: 'delete_comment',
320
+ description: 'Delete a comment by ID, removing it from the thread. This removes the comment itself — if you only want to take a pinned comment out of the highlighted area while keeping it, use unpin_comment instead.',
321
+ inputSchema: {
322
+ type: 'object',
323
+ properties: {
324
+ comment_id: {
325
+ type: 'string',
326
+ description: 'The ID of the comment to delete (required)',
327
+ },
328
+ },
329
+ required: ['comment_id'],
330
+ },
331
+ annotations: {
332
+ title: 'Delete comment',
333
+ readOnlyHint: false,
334
+ destructiveHint: true,
335
+ idempotentHint: true,
336
+ openWorldHint: true,
337
+ },
338
+ };
339
+ // ---- Pin Comment ----
340
+ const pinCommentSchema = z.object({
341
+ comment_id: z.string().min(1, 'Comment ID is required'),
342
+ });
343
+ export async function pinCommentTool(client, args) {
344
+ try {
345
+ const params = pinCommentSchema.parse(args);
346
+ await client.pinComment(params.comment_id);
347
+ return {
348
+ content: [
349
+ {
350
+ type: 'text',
351
+ text: `Comment ${params.comment_id} pinned successfully.`,
352
+ },
353
+ ],
354
+ };
355
+ }
356
+ catch (error) {
357
+ throw toMcpError(error);
358
+ }
359
+ }
360
+ export const pinCommentDefinition = {
361
+ name: 'pin_comment',
362
+ description: "Pin a comment so it is highlighted at the top of its task's comment area; list_comments then shows it with a [PINNED] marker. The inverse action is unpin_comment.",
363
+ inputSchema: {
364
+ type: 'object',
365
+ properties: {
366
+ comment_id: {
367
+ type: 'string',
368
+ description: 'The ID of the comment to pin (required)',
369
+ },
370
+ },
371
+ required: ['comment_id'],
372
+ },
373
+ annotations: {
374
+ title: 'Pin comment',
375
+ readOnlyHint: false,
376
+ destructiveHint: false,
377
+ idempotentHint: true,
378
+ openWorldHint: true,
379
+ },
380
+ };
381
+ // ---- Unpin Comment ----
382
+ const unpinCommentSchema = z.object({
383
+ comment_id: z.string().min(1, 'Comment ID is required'),
384
+ });
385
+ export async function unpinCommentTool(client, args) {
386
+ try {
387
+ const params = unpinCommentSchema.parse(args);
388
+ await client.unpinComment(params.comment_id);
389
+ return {
390
+ content: [
391
+ {
392
+ type: 'text',
393
+ text: `Comment ${params.comment_id} unpinned successfully.`,
394
+ },
395
+ ],
396
+ };
397
+ }
398
+ catch (error) {
399
+ throw toMcpError(error);
400
+ }
401
+ }
402
+ export const unpinCommentDefinition = {
403
+ name: 'unpin_comment',
404
+ description: 'Remove the pinned highlight from a comment previously pinned with pin_comment, leaving the comment itself in place in the thread. The inverse action is pin_comment.',
405
+ inputSchema: {
406
+ type: 'object',
407
+ properties: {
408
+ comment_id: {
409
+ type: 'string',
410
+ description: 'The ID of the comment to unpin (required)',
411
+ },
412
+ },
413
+ required: ['comment_id'],
414
+ },
415
+ annotations: {
416
+ title: 'Unpin comment',
417
+ readOnlyHint: false,
418
+ destructiveHint: false,
419
+ idempotentHint: true,
420
+ openWorldHint: true,
421
+ },
422
+ };
423
+ // ---- Add Comment Reaction ----
424
+ const addCommentReactionSchema = z.object({
425
+ comment_id: z.string().min(1, 'Comment ID is required'),
426
+ reaction: z.string().min(1, 'Reaction is required'),
427
+ });
428
+ export async function addCommentReactionTool(client, args) {
429
+ try {
430
+ const params = addCommentReactionSchema.parse(args);
431
+ await client.addCommentReaction(params.comment_id, params.reaction);
432
+ return {
433
+ content: [
434
+ {
435
+ type: 'text',
436
+ text: `Reaction "${params.reaction}" added to comment ${params.comment_id} successfully.`,
437
+ },
438
+ ],
439
+ };
440
+ }
441
+ catch (error) {
442
+ throw toMcpError(error);
443
+ }
444
+ }
445
+ export const addCommentReactionDefinition = {
446
+ name: 'add_comment_reaction',
447
+ description: 'Attach an emoji-style reaction (e.g. "like", "heart", "thumbsup") to a comment — a lightweight acknowledgement when you want to respond without writing a reply via add_task_comment.',
448
+ inputSchema: {
449
+ type: 'object',
450
+ properties: {
451
+ comment_id: {
452
+ type: 'string',
453
+ description: 'The ID of the comment to react to (required)',
454
+ },
455
+ reaction: {
456
+ type: 'string',
457
+ description: 'The reaction key to add, e.g. "like", "heart", or "thumbsup" (required)',
458
+ },
459
+ },
460
+ required: ['comment_id', 'reaction'],
461
+ },
462
+ annotations: {
463
+ title: 'Add comment reaction',
464
+ readOnlyHint: false,
465
+ destructiveHint: false,
466
+ idempotentHint: false,
467
+ openWorldHint: true,
468
+ },
469
+ };
@@ -0,0 +1,73 @@
1
+ import { z } from 'zod';
2
+ import { toMcpError } from '../utils/errors.js';
3
+ const listCompaniesSchema = z.object({
4
+ status: z.enum(['active', 'archived']).optional(),
5
+ limit: z.coerce.number().min(1).max(200).default(30).optional(),
6
+ });
7
+ function formatDomains(domains) {
8
+ return domains?.length ? `Domains: ${domains.join(', ')}` : 'No domains';
9
+ }
10
+ export async function listCompaniesTool(client, args) {
11
+ try {
12
+ const params = listCompaniesSchema.parse(args || {});
13
+ const response = await client.listCompanies({
14
+ status: params.status,
15
+ limit: params.limit,
16
+ });
17
+ if (!response || !response.data || response.data.length === 0) {
18
+ return {
19
+ content: [
20
+ {
21
+ type: 'text',
22
+ text: 'No companies found matching the criteria.',
23
+ },
24
+ ],
25
+ };
26
+ }
27
+ const companiesText = response.data
28
+ .filter((company) => company && company.attributes)
29
+ .map((company) => {
30
+ const tags = company.attributes.tag_list?.length
31
+ ? `Tags: ${company.attributes.tag_list.join(', ')}`
32
+ : '';
33
+ return `• ${company.attributes.name} (ID: ${company.id})
34
+ ${formatDomains(company.attributes.domains)}
35
+ ${tags}`;
36
+ })
37
+ .join('\n\n');
38
+ const summary = `Found ${response.data.length} compan${response.data.length !== 1 ? 'ies' : 'y'}${response.meta?.total_count ? ` (showing ${response.data.length} of ${response.meta.total_count})` : ''}:\n\n${companiesText}`;
39
+ return {
40
+ content: [
41
+ {
42
+ type: 'text',
43
+ text: summary,
44
+ },
45
+ ],
46
+ };
47
+ }
48
+ catch (error) {
49
+ throw toMcpError(error);
50
+ }
51
+ }
52
+ export const listCompaniesDefinition = {
53
+ name: 'list_companies',
54
+ description: "List companies (clients/customers), optionally filtered by active/archived status. Returns each company's name, ID, email domains, and tags. A company ID from here filters list_projects and list_invoices, and is the entry point for the list_companies -> list_projects -> list_tasks drill-down. Returns 30 results by default; raise limit (max 200) for large workspaces.",
55
+ inputSchema: {
56
+ type: 'object',
57
+ properties: {
58
+ status: {
59
+ type: 'string',
60
+ enum: ['active', 'archived'],
61
+ description: 'Filter by company status: active or archived',
62
+ },
63
+ limit: {
64
+ type: 'number',
65
+ description: 'Number of companies to return (default 30, max 200)',
66
+ minimum: 1,
67
+ maximum: 200,
68
+ default: 30,
69
+ },
70
+ },
71
+ },
72
+ annotations: { title: 'List companies', readOnlyHint: true, openWorldHint: true },
73
+ };
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Collects the distinct set of custom field IDs referenced as keys of
3
+ * task.attributes.custom_fields across all given tasks. Tasks without a
4
+ * custom_fields object (or with an empty one) are skipped.
5
+ */
6
+ function collectCustomFieldIds(tasks) {
7
+ const ids = new Set();
8
+ for (const task of tasks) {
9
+ const customFields = task.attributes?.custom_fields;
10
+ if (!customFields || typeof customFields !== 'object')
11
+ continue;
12
+ for (const key of Object.keys(customFields)) {
13
+ ids.add(key);
14
+ }
15
+ }
16
+ return ids;
17
+ }
18
+ /** Builds a lookup of custom field ID -> display name via a single API call. */
19
+ async function buildFieldNameMap(client) {
20
+ const response = await client.listCustomFields();
21
+ const map = new Map();
22
+ for (const field of response.data ?? []) {
23
+ if (!field)
24
+ continue;
25
+ map.set(field.id, field.attributes?.name || field.id);
26
+ }
27
+ return map;
28
+ }
29
+ /** Builds a lookup of option ID -> display label for a single custom field. */
30
+ async function buildOptionsMapForField(client, fieldId) {
31
+ const response = await client.listCustomFieldOptions({ customFieldId: fieldId });
32
+ const map = new Map();
33
+ for (const option of response.data ?? []) {
34
+ if (!option)
35
+ continue;
36
+ map.set(option.id, option.attributes?.name || option.id);
37
+ }
38
+ return map;
39
+ }
40
+ /**
41
+ * Builds a resolver map for the custom fields referenced by the given task(s).
42
+ * Costs zero API calls when no task has any custom_fields set. Otherwise:
43
+ * one call to list all custom field definitions, plus one parallel call per
44
+ * distinct custom field to list its options.
45
+ */
46
+ export async function buildCustomFieldValueMap(client, tasks) {
47
+ const taskArray = Array.isArray(tasks) ? tasks : [tasks];
48
+ const fieldIds = Array.from(collectCustomFieldIds(taskArray));
49
+ const result = new Map();
50
+ if (fieldIds.length === 0) {
51
+ return result;
52
+ }
53
+ const nameMap = await buildFieldNameMap(client);
54
+ const optionMaps = await Promise.all(fieldIds.map((id) => buildOptionsMapForField(client, id)));
55
+ fieldIds.forEach((id, index) => {
56
+ result.set(id, { name: nameMap.get(id) || id, options: optionMaps[index] });
57
+ });
58
+ return result;
59
+ }
60
+ /** Resolves a single raw custom field value (one array element) through the options map. */
61
+ function resolveSingleValue(options, value) {
62
+ if (typeof value === 'string' && options.has(value)) {
63
+ return options.get(value);
64
+ }
65
+ return value === null || value === undefined ? 'null' : String(value);
66
+ }
67
+ /**
68
+ * Formats a task's raw custom_fields into human-readable "name: value" lines,
69
+ * resolving field names and dropdown/multi-select option IDs to display labels.
70
+ */
71
+ export function resolveCustomFieldsText(map, rawCustomFields) {
72
+ if (!rawCustomFields)
73
+ return [];
74
+ const lines = [];
75
+ for (const [fieldId, rawValue] of Object.entries(rawCustomFields)) {
76
+ const info = map.get(fieldId);
77
+ const fieldName = info?.name ?? fieldId;
78
+ const options = info?.options ?? new Map();
79
+ let displayValue;
80
+ if (Array.isArray(rawValue)) {
81
+ displayValue = rawValue.map((item) => resolveSingleValue(options, item)).join(', ');
82
+ }
83
+ else if (typeof rawValue === 'string' && options.has(rawValue)) {
84
+ displayValue = options.get(rawValue);
85
+ }
86
+ else {
87
+ displayValue = rawValue === null || rawValue === undefined ? 'null' : String(rawValue);
88
+ }
89
+ lines.push(`${fieldName}: ${displayValue}`);
90
+ }
91
+ return lines;
92
+ }