@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,281 @@
1
+ /**
2
+ * Capacity overview: contracted hours vs. planned bookings per person.
3
+ *
4
+ * The arithmetic lives in api/capacity.ts as pure functions; this file only
5
+ * gathers data and renders it. See docs/resource-management-spec.md.
6
+ */
7
+ import { z } from 'zod';
8
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
9
+ import { MAX_BOOKING_PAGES, MAX_PAGE_SIZE, PERSON_TYPE, formatMinutes, remoteWorkEventIds, } from '../api/bookings-client.js';
10
+ import { bookedMinutes, hasUnreadableAvailabilities, parseAvailabilities, summariseCapacity, } from '../api/capacity.js';
11
+ import { parseDate } from './time-entries.js';
12
+ import { coerceBoolean, resolvePersonId, rethrowToolError, } from './tool-helpers.js';
13
+ /**
14
+ * Fetch every booking in the window, page by page.
15
+ *
16
+ * One sweep for the whole team rather than one call per person: Productive
17
+ * allows 100 requests per 10s and Workers caps subrequests per request, so a
18
+ * 200-person overview used to sit right on both limits. Sequential on purpose
19
+ * -- whether page n+1 exists is only known after page n, and serialising keeps
20
+ * the request rate flat.
21
+ */
22
+ async function collectBookings(client, filters, maxPages = MAX_BOOKING_PAGES) {
23
+ const bookings = [];
24
+ const included = [];
25
+ for (let page = 1; page <= maxPages; page += 1) {
26
+ // A fixed sort is what makes paging safe: without one the order across
27
+ // pages is not guaranteed and rows duplicate or vanish at the boundaries.
28
+ const response = await client.listBookings({
29
+ ...filters,
30
+ limit: MAX_PAGE_SIZE,
31
+ page,
32
+ sort: 'started_on',
33
+ });
34
+ const rows = response.data ?? [];
35
+ bookings.push(...rows);
36
+ included.push(...(response.included ?? []));
37
+ const totalPages = response.meta?.total_pages;
38
+ if (typeof totalPages === 'number' && page >= totalPages)
39
+ break;
40
+ // A short page is the last one, whether or not meta said so.
41
+ if (rows.length < MAX_PAGE_SIZE)
42
+ break;
43
+ if (page === maxPages)
44
+ return { bookings, included, truncated: true };
45
+ }
46
+ return { bookings, included, truncated: false };
47
+ }
48
+ /** Bookings keyed by person; ones with no person attached cannot be attributed. */
49
+ function groupByPerson(bookings) {
50
+ const byPerson = new Map();
51
+ for (const booking of bookings) {
52
+ const personId = booking.relationships?.person?.data?.id;
53
+ if (!personId)
54
+ continue;
55
+ const existing = byPerson.get(personId);
56
+ if (existing)
57
+ existing.push(booking);
58
+ else
59
+ byPerson.set(personId, [booking]);
60
+ }
61
+ return byPerson;
62
+ }
63
+ /**
64
+ * Look ahead at what this booking would do to the person's load.
65
+ *
66
+ * Returns null when the load cannot be established (no availabilities pattern),
67
+ * so callers can stay silent rather than guess.
68
+ */
69
+ export async function projectUtilisation(client, personId, from, to, planned) {
70
+ try {
71
+ const [person, existing] = await Promise.all([
72
+ client.getPerson(personId),
73
+ client.listBookings({ person_id: personId, after: from, before: to, limit: MAX_PAGE_SIZE }),
74
+ ]);
75
+ const slices = parseAvailabilities(person.data.attributes.availabilities);
76
+ // The response already sideloads its events, so telling working-from-home
77
+ // apart from real time off costs no extra call -- and without it every
78
+ // home-office day would read as absence and the warning would fire early.
79
+ const summary = summariseCapacity(existing.data ?? [], slices, from, to, remoteWorkEventIds(existing.included));
80
+ if (summary.contractedMinutes === null || summary.contractedMinutes === 0)
81
+ return null;
82
+ // Size the pending booking the same way an existing one would be counted,
83
+ // so a percentage booking is scaled against contracted time rather than
84
+ // silently contributing nothing.
85
+ const addedMinutes = bookedMinutes({
86
+ id: 'pending',
87
+ type: 'bookings',
88
+ attributes: { started_on: from, ended_on: to, ...planned },
89
+ }, slices, from, to);
90
+ const plannedTotal = summary.plannedMinutes + addedMinutes;
91
+ const percent = Math.round((plannedTotal / summary.contractedMinutes) * 1000) / 10;
92
+ const headline = `Projected load for ${from}..${to}: ${percent}% of ${formatMinutes(summary.contractedMinutes)} contracted`;
93
+ if (plannedTotal > summary.contractedMinutes) {
94
+ return `⚠️ ${headline} — this overbooks the person by ${formatMinutes(plannedTotal - summary.contractedMinutes)}. Bookings are still allowed; this is a warning, not a block.`;
95
+ }
96
+ return headline;
97
+ }
98
+ catch {
99
+ // A capacity hint must never prevent the actual booking.
100
+ return null;
101
+ }
102
+ }
103
+ const getCapacityOverviewSchema = z.object({
104
+ person_id: z.string().optional(),
105
+ date_from: z.string().min(1, 'date_from is required'),
106
+ date_to: z.string().min(1, 'date_to is required'),
107
+ include_placeholders: coerceBoolean.optional().default(false),
108
+ limit: z.coerce.number().min(1).max(200).default(50),
109
+ });
110
+ function personLabel(person) {
111
+ const first = typeof person.attributes.first_name === 'string' ? person.attributes.first_name : '';
112
+ const last = typeof person.attributes.last_name === 'string' ? person.attributes.last_name : '';
113
+ return `${first} ${last}`.trim() || `Person ${person.id}`;
114
+ }
115
+ /** One line per person, ordered so the busiest show up first. */
116
+ function renderRow(person, summary) {
117
+ const label = personLabel(person);
118
+ // Only rendered when there is something to render -- a "Remote: 0h" segment
119
+ // on every single row would be pure noise.
120
+ const remote = summary.remoteMinutes > 0 ? ` · Remote: ${formatMinutes(summary.remoteMinutes)}` : '';
121
+ if (summary.contractedMinutes === null) {
122
+ // "Nothing on file" and "on file but unreadable" call for different
123
+ // reactions: the first is a gap in Productive, the second is a bug in this
124
+ // tool. Reporting both the same way hides the bug behind a plausible result.
125
+ const reason = hasUnreadableAvailabilities(person.attributes.availabilities)
126
+ ? 'a working pattern is set on this person but could not be read'
127
+ : 'no working pattern set on this person';
128
+ return `• ${label} (ID: ${person.id})
129
+ Contracted hours unknown — ${reason}
130
+ Planned: ${formatMinutes(summary.plannedMinutes)} (${formatMinutes(summary.projectMinutes)} projects, ${formatMinutes(summary.absenceMinutes)} absence)${remote}`;
131
+ }
132
+ const pct = (value) => (value === null ? '—' : `${value}%`);
133
+ const free = summary.freeMinutes === null
134
+ ? '—'
135
+ : summary.freeMinutes >= 0
136
+ ? formatMinutes(summary.freeMinutes)
137
+ : `overbooked by ${formatMinutes(-summary.freeMinutes)}`;
138
+ // Project share and total claimed share are reported separately: somebody on
139
+ // leave all week is fully claimed while doing 0% project work, and showing
140
+ // only the project figure next to an OVERBOOKED flag reads as a contradiction.
141
+ return `• ${label} (ID: ${person.id})${summary.overbooked ? ' ⚠️ OVERBOOKED' : ''}
142
+ Contracted: ${formatMinutes(summary.contractedMinutes)} · Claimed: ${formatMinutes(summary.plannedMinutes)} (${pct(summary.plannedPercent)})
143
+ Projects: ${formatMinutes(summary.projectMinutes)} (${pct(summary.utilisationPercent)}) · Absence: ${formatMinutes(summary.absenceMinutes)}${remote}
144
+ Free: ${free}`;
145
+ }
146
+ function renderOverview(rows, opts) {
147
+ const header = `Capacity ${opts.from} to ${opts.to} — ${rows.length} person${rows.length !== 1 ? 's' : ''}`;
148
+ // Ahead of the rows, not after them: a reader who stops at the first
149
+ // interesting name must not walk away with a partial figure believed whole.
150
+ const truncation = opts.truncated
151
+ ? `\n\n⚠️ Incomplete: only the first ${MAX_BOOKING_PAGES * MAX_PAGE_SIZE} bookings in this range were counted and there are more. Every figure below is missing some load, so "Free" is an upper bound rather than what is actually left. Narrow the date range, or pass person_id for exact numbers.`
152
+ : '';
153
+ const body = rows.map((r) => renderRow(r.person, r.summary)).join('\n\n');
154
+ const overbooked = rows.filter((r) => r.summary.overbooked);
155
+ const warning = overbooked.length
156
+ ? `\n\n⚠️ ${overbooked.length} person${overbooked.length !== 1 ? 's are' : ' is'} overbooked: ${overbooked
157
+ .map((r) => personLabel(r.person))
158
+ .join(', ')}`
159
+ : '';
160
+ const remote = rows.some((r) => r.summary.remoteMinutes > 0)
161
+ ? '\n\nRemote work is reported separately and not deducted — those people are working, just not on site.'
162
+ : '';
163
+ const scope = opts.singlePerson
164
+ ? ''
165
+ : '\n\nOnly people and bookings visible to the calling token are included — a regular token sees only its own resource planning.';
166
+ return `${header}${truncation}\n\n${body}${warning}${remote}${scope}`;
167
+ }
168
+ const NO_BOOKINGS = { bookings: [], included: [], truncated: false };
169
+ /** One named person: their record plus their own bookings, in one call each. */
170
+ async function gatherOne(client, personId, window) {
171
+ // No person_type filter here: the caller named this person, so filtering on
172
+ // what kind of resource they are could only ever answer "nothing" for a
173
+ // placeholder that was asked about explicitly.
174
+ //
175
+ // Paged through collectBookings like the team sweep rather than taking a
176
+ // single page: one busy person over a year exceeds 200 bookings, and a flat
177
+ // `truncated: false` would report "Free: 800h" off a silently cut list --
178
+ // exactly what the truncation warning exists to prevent.
179
+ const [person, collected] = await Promise.all([
180
+ client.getPerson(personId),
181
+ collectBookings(client, { ...window, person_id: personId }),
182
+ ]);
183
+ return { people: [person.data], collected };
184
+ }
185
+ /** Everyone the token can see, plus every booking in the window in one sweep. */
186
+ async function gatherMany(client, params, window) {
187
+ // `is_active` becomes filter[status]=1 server-side, so deactivated people no
188
+ // longer eat into `limit`. The client-side filter below is still needed: it
189
+ // is what keeps contacts, agents and placeholders out.
190
+ const listed = await client.listPeople({ limit: params.limit, is_active: true });
191
+ const people = (listed.data ?? []).filter((p) => {
192
+ const attrs = p.attributes;
193
+ if (attrs.deactivated_at)
194
+ return false;
195
+ // Contacts and agents have no working pattern and would only add noise.
196
+ if (attrs.is_user === false && attrs.placeholder !== true)
197
+ return false;
198
+ if (!params.include_placeholders && attrs.placeholder === true)
199
+ return false;
200
+ return true;
201
+ });
202
+ if (people.length === 0)
203
+ return { people, collected: NO_BOOKINGS };
204
+ // Scoped to exactly the people being reported on (the filter takes a
205
+ // comma-separated list, verified live). Without it the sweep drags in
206
+ // bookings for everyone the token can see, which spends the page budget on
207
+ // rows that are then discarded -- and triggers the truncation warning on an
208
+ // overview that would otherwise have been complete.
209
+ const collected = await collectBookings(client, {
210
+ ...window,
211
+ person_id: people.map((p) => p.id).join(','),
212
+ ...(params.include_placeholders ? {} : { person_type: PERSON_TYPE.USER }),
213
+ });
214
+ return { people, collected };
215
+ }
216
+ export async function getCapacityOverviewTool(client, args, config) {
217
+ try {
218
+ const params = getCapacityOverviewSchema.parse(args);
219
+ const from = parseDate(params.date_from);
220
+ const to = parseDate(params.date_to);
221
+ if (to < from) {
222
+ throw new McpError(ErrorCode.InvalidParams, `date_to (${to}) is before date_from (${from}).`);
223
+ }
224
+ const personId = params.person_id ? resolvePersonId(params.person_id, config) : undefined;
225
+ const window = { after: from, before: to };
226
+ const { people, collected } = personId
227
+ ? await gatherOne(client, personId, window)
228
+ : await gatherMany(client, params, window);
229
+ if (people.length === 0) {
230
+ return { content: [{ type: 'text', text: 'No people to report on for these filters.' }] };
231
+ }
232
+ // Every booking is already in hand, so each person is a lookup rather than
233
+ // a request.
234
+ const remoteIds = remoteWorkEventIds(collected.included);
235
+ const byPerson = groupByPerson(collected.bookings);
236
+ const rows = people.map((person) => ({
237
+ person,
238
+ summary: summariseCapacity(byPerson.get(person.id) ?? [], parseAvailabilities(person.attributes.availabilities), from, to, remoteIds),
239
+ }));
240
+ rows.sort((a, b) => (b.summary.utilisationPercent ?? -1) - (a.summary.utilisationPercent ?? -1));
241
+ const text = renderOverview(rows, {
242
+ from,
243
+ to,
244
+ truncated: collected.truncated,
245
+ singlePerson: Boolean(personId),
246
+ });
247
+ return { content: [{ type: 'text', text }] };
248
+ }
249
+ catch (error) {
250
+ rethrowToolError(error);
251
+ }
252
+ }
253
+ export const getCapacityOverviewDefinition = {
254
+ name: 'get_capacity_overview',
255
+ description: 'Show planned utilisation per person for a date range: contracted hours (from the person\'s working pattern), how much is taken by project bookings and absences, what is left, and who is overbooked. Answers "do we have capacity for project X next month?". Contracted hours come from each person\'s own working pattern, so part-time contracts are handled correctly. Remote work (working from home) is reported separately and never deducted — those people are available, just not on site. Note that a regular API token only sees its own resource planning — with such a token this reports on the caller alone.',
256
+ inputSchema: {
257
+ type: 'object',
258
+ properties: {
259
+ person_id: {
260
+ type: 'string',
261
+ description: 'Report on a single person. "me" uses PRODUCTIVE_USER_ID. Omit to cover everyone visible.',
262
+ },
263
+ date_from: { type: 'string', description: 'Start of the range (YYYY-MM-DD) (required)' },
264
+ date_to: { type: 'string', description: 'End of the range, inclusive (required)' },
265
+ include_placeholders: {
266
+ type: 'boolean',
267
+ description: 'Include placeholder resources (unfilled roles) alongside real people (default false)',
268
+ default: false,
269
+ },
270
+ limit: {
271
+ type: 'number',
272
+ description: 'Maximum number of people to report on (1-200)',
273
+ minimum: 1,
274
+ maximum: 200,
275
+ default: 50,
276
+ },
277
+ },
278
+ required: ['date_from', 'date_to'],
279
+ },
280
+ annotations: { title: 'Capacity overview', readOnlyHint: true, openWorldHint: true },
281
+ };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Formatting for an activity's `changeset`.
3
+ *
4
+ * Productive returns the changed fields as an array of objects whose values are
5
+ * `[before, after]` pairs -- not the flat `changes` object this code used to
6
+ * assume (that attribute does not exist, so nothing was ever rendered):
7
+ *
8
+ * [{ "used": [{ "value": "0.0", "unit": "days" }, { "value": "1.0", "unit": "days" }] }]
9
+ */
10
+ /**
11
+ * Values arrive wrapped as `{ value: … }`, often with extra keys (`id`,
12
+ * `avatar_url`, `unit`). Unwrap one level so a change reads
13
+ * `person_id: null → Igor Kretov` instead of a JSON blob.
14
+ */
15
+ function renderValue(value, unwrap = true) {
16
+ if (typeof value === 'string')
17
+ return value;
18
+ if (unwrap && value !== null && typeof value === 'object' && 'value' in value) {
19
+ return renderValue(value.value, false);
20
+ }
21
+ return JSON.stringify(value);
22
+ }
23
+ /** One `field: before → after` line per changed field. */
24
+ export function formatChangeset(changeset) {
25
+ if (!Array.isArray(changeset))
26
+ return [];
27
+ const lines = [];
28
+ for (const entry of changeset) {
29
+ if (!entry || typeof entry !== 'object')
30
+ continue;
31
+ for (const [field, change] of Object.entries(entry)) {
32
+ if (Array.isArray(change) && change.length === 2) {
33
+ lines.push(`${field}: ${renderValue(change[0])} → ${renderValue(change[1])}`);
34
+ }
35
+ else {
36
+ lines.push(`${field}: ${renderValue(change)}`);
37
+ }
38
+ }
39
+ }
40
+ return lines;
41
+ }