@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,50 @@
1
+ /**
2
+ * An error response from the Productive API, carrying the HTTP status.
3
+ *
4
+ * The status is the whole point: without it every failure looks the same to the
5
+ * caller, so a mistyped ID (404) and a broken gateway (502) both surface as
6
+ * "something went wrong at my end". `src/utils/errors.ts` maps the status onto
7
+ * the right MCP error code.
8
+ *
9
+ * Lives in its own module rather than in client.ts so that consumers which only
10
+ * need to recognise the error -- the tool layer, via toMcpError -- do not have
11
+ * to import the whole API client.
12
+ */
13
+ export class ProductiveApiError extends Error {
14
+ httpStatus;
15
+ errors;
16
+ constructor(message, httpStatus, errors = []) {
17
+ super(message);
18
+ this.name = 'ProductiveApiError';
19
+ this.httpStatus = httpStatus;
20
+ this.errors = errors;
21
+ }
22
+ }
23
+ /**
24
+ * Render JSON:API error objects into one human-readable line.
25
+ *
26
+ * This is the message format `makeRequest` has always produced: `detail`
27
+ * preferred over `title`, the failing field appended in parentheses when the API
28
+ * names one, several errors joined with `; `.
29
+ *
30
+ * The one deliberate departure: an error object carrying neither `detail` nor
31
+ * `title` contributes nothing instead of the literal "Unknown error". That way
32
+ * `{"errors":[{"status":"500"}]}` falls through to the caller's
33
+ * `API request failed with status 500`, which at least names the status, rather
34
+ * than replacing it with a string that says less.
35
+ *
36
+ * @param errors - The `errors` array from the response body, possibly empty.
37
+ * @returns The joined message, or an empty string when there is nothing to say.
38
+ */
39
+ export function formatProductiveErrors(errors) {
40
+ return errors
41
+ .map((e) => {
42
+ const text = e.detail || e.title;
43
+ if (!text)
44
+ return '';
45
+ const field = e.source?.pointer ? ` (${e.source.pointer})` : '';
46
+ return `${text}${field}`;
47
+ })
48
+ .filter(Boolean)
49
+ .join('; ');
50
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Arithmetic and paging for the invoice time-entry audit, kept free of the API
3
+ * client so it is unit-testable without mocks -- the same split as
4
+ * `src/api/capacity.ts` against `src/tools/capacity.ts`.
5
+ *
6
+ * The one number that matters here is that tracked and billable time are not
7
+ * the same figure. In a 200-entry live sample, 9 entries billed MORE than was
8
+ * tracked (rounding up: 336 -> 360 minutes) and one billed nothing against 450
9
+ * tracked minutes. Both directions are normal, so every total is reported twice
10
+ * and neither is derived from the other.
11
+ */
12
+ /** Largest page the time-entries endpoint is asked for (the API's own maximum). */
13
+ export const MAX_PAGE_SIZE = 200;
14
+ /**
15
+ * Hard ceiling on pages fetched for one invoice.
16
+ *
17
+ * 5 x 200 = 1000 entries against a live worst case of 79 on the busiest invoice
18
+ * in the sandbox -- twelve times headroom, while still bounding the Worker's
19
+ * subrequest budget and Productive's 100-requests-per-10s limit.
20
+ */
21
+ export const MAX_TIME_ENTRY_PAGES = 5;
22
+ /** `unit_id` on a line item that makes `quantity` a number of hours. */
23
+ export const HOUR_UNIT_ID = 1;
24
+ /** Two line-item quantities closer than this count as equal (they are decimals). */
25
+ export const RECONCILE_TOLERANCE_HOURS = 0.01;
26
+ export function durationOf(minutes) {
27
+ return {
28
+ minutes,
29
+ hours: Math.round((minutes / 60) * 100) / 100,
30
+ display: formatDuration(minutes),
31
+ };
32
+ }
33
+ /**
34
+ * Render minutes as `5h 36m`.
35
+ *
36
+ * The twin of `formatMinutesDisplay` in `src/tools/time-entries.ts`, which this
37
+ * cannot import without inverting the api/tools layering. It differs in one way
38
+ * that matters: the sign is pulled out first, so a negative span (billable minus
39
+ * tracked, when less was billed than tracked) reads `-5h 30m` rather than the
40
+ * `-6h -30m` that flooring a negative quotient produces.
41
+ */
42
+ function formatDuration(totalMinutes) {
43
+ const sign = totalMinutes < 0 ? '-' : '';
44
+ const absolute = Math.abs(totalMinutes);
45
+ const hours = Math.floor(absolute / 60);
46
+ const minutes = absolute % 60;
47
+ if (hours > 0) {
48
+ return minutes > 0 ? `${sign}${hours}h ${minutes}m` : `${sign}${hours}h`;
49
+ }
50
+ return `${sign}${minutes}m`;
51
+ }
52
+ /**
53
+ * `2026-09-05` -> `05.09.2026`.
54
+ *
55
+ * Deliberately a string split and not `new Date()`: `new Date('2026-09-05')` is
56
+ * parsed as UTC midnight, so `.getDate()` in any negative-offset timezone yields
57
+ * the 4th. The Worker's timezone is not the reader's, and an audit document that
58
+ * shifts dates by one day depending on where it runs is worse than useless.
59
+ * Anything that is not an ISO date comes back untouched.
60
+ */
61
+ export function formatDateDe(isoDate) {
62
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(isoDate);
63
+ if (!match)
64
+ return isoDate;
65
+ return `${match[3]}.${match[2]}.${match[1]}`;
66
+ }
67
+ /**
68
+ * Tracked and billable time for one entry.
69
+ *
70
+ * `billable_time ?? time` and never `||`: zero is a real, live value (an entry
71
+ * with 450 tracked minutes and 0 billable ones), and `||` would silently promote
72
+ * it to 450 -- shifting the invoice reconciliation by 7.5 hours with no error.
73
+ */
74
+ export function entryDurations(entry) {
75
+ const tracked = entry.attributes.time ?? 0;
76
+ const billable = entry.attributes.billable_time ?? tracked;
77
+ return { tracked: durationOf(tracked), billable: durationOf(billable) };
78
+ }
79
+ /**
80
+ * Group entries and total both time figures per group.
81
+ *
82
+ * `key` returns `id: null` for an entry whose relationship is missing; those
83
+ * collect in one bucket rather than being dropped, so the subtotals always add
84
+ * up to the report total.
85
+ */
86
+ export function subtotalsBy(entries, key) {
87
+ const groups = new Map();
88
+ for (const entry of entries) {
89
+ const { id, name } = key(entry);
90
+ const bucket = groups.get(id ?? name) ?? { id, name, count: 0, tracked: 0, billable: 0 };
91
+ const durations = entryDurations(entry);
92
+ bucket.count += 1;
93
+ bucket.tracked += durations.tracked.minutes;
94
+ bucket.billable += durations.billable.minutes;
95
+ groups.set(id ?? name, bucket);
96
+ }
97
+ return [...groups.values()]
98
+ .map((bucket) => ({
99
+ id: bucket.id,
100
+ name: bucket.name,
101
+ entry_count: bucket.count,
102
+ tracked: durationOf(bucket.tracked),
103
+ billable: durationOf(bucket.billable),
104
+ }))
105
+ .sort((a, b) => b.billable.minutes - a.billable.minutes);
106
+ }
107
+ /**
108
+ * Compare what the invoice bills against what the time entries hold.
109
+ *
110
+ * Only `unit_id === 1` items are summed. A piece or a day is not an hour, and a
111
+ * live invoice (1439185) mixes both kinds -- adding a quantity of `1 piece` into
112
+ * an hour total is the silent error this guards against. Excluded items are
113
+ * returned with a reason rather than dropped, so the output never hides part of
114
+ * the invoice.
115
+ *
116
+ * Residual limitation, deliberately not guessed at: for a percentage billing
117
+ * type the spec says `quantity` is a percentage, but a line item carries no
118
+ * billing-type field to detect that with. Such a row would have to pass through
119
+ * `unit_id === 1` to be miscounted, which no observed invoice does.
120
+ */
121
+ export function reconcile(lineItems, billableMinutes, describe) {
122
+ const comparable = [];
123
+ const excluded = [];
124
+ for (const item of lineItems) {
125
+ const unitId = item.attributes.unit_id ?? null;
126
+ const quantity = parseQuantity(item.attributes.quantity);
127
+ const row = {
128
+ id: item.id,
129
+ description: describe(item.attributes.description),
130
+ quantity,
131
+ unit_id: unitId,
132
+ hours: null,
133
+ };
134
+ if (unitId !== HOUR_UNIT_ID) {
135
+ excluded.push({ ...row, reason: `unit_id ${unitId ?? 'missing'} is not hours` });
136
+ }
137
+ else if (quantity === null) {
138
+ excluded.push({ ...row, reason: 'quantity is missing or not numeric' });
139
+ }
140
+ else {
141
+ comparable.push({ ...row, hours: quantity });
142
+ }
143
+ }
144
+ const lineItemHours = round2(comparable.reduce((sum, row) => sum + (row.hours ?? 0), 0));
145
+ const billableHours = durationOf(billableMinutes).hours;
146
+ const difference = round2(lineItemHours - billableHours);
147
+ return {
148
+ status: statusFor(comparable.length, difference),
149
+ line_item_hours: lineItemHours,
150
+ billable_hours: billableHours,
151
+ difference_hours: difference,
152
+ line_items: comparable,
153
+ excluded,
154
+ };
155
+ }
156
+ /**
157
+ * A line item quantity arrives as a decimal string (`"191.25"`), not a number.
158
+ *
159
+ * Reading it as a number is what made a perfectly reconcilable invoice report
160
+ * `not_comparable` with both of its line items excluded -- caught only because
161
+ * the tool was run against the live API. Numbers are accepted too, so a mocked
162
+ * or future numeric payload behaves the same.
163
+ */
164
+ function parseQuantity(raw) {
165
+ if (typeof raw === 'number')
166
+ return Number.isFinite(raw) ? raw : null;
167
+ if (typeof raw !== 'string' || raw.trim() === '')
168
+ return null;
169
+ const parsed = Number(raw);
170
+ return Number.isFinite(parsed) ? parsed : null;
171
+ }
172
+ function statusFor(comparableCount, difference) {
173
+ if (comparableCount === 0)
174
+ return 'not_comparable';
175
+ return Math.abs(difference) < RECONCILE_TOLERANCE_HOURS ? 'ok' : 'mismatch';
176
+ }
177
+ /**
178
+ * Best-effort per-service breakdown of the reconciliation.
179
+ *
180
+ * Returns `null` when the two sides cannot be lined up, which is the common
181
+ * case and not an error: `/line_items` accepts no `include`, so a line item's
182
+ * service cannot be sideloaded and the only available join is its description.
183
+ * That description is whatever `generate_line_items` wrote -- service names on
184
+ * one live invoice (`AP1 - ...`), task names on another (`#940 - ...`). When no
185
+ * line item matches a service name, only the total is trustworthy and the caller
186
+ * says so instead of inventing rows.
187
+ */
188
+ export function reconcileByService(comparable, serviceSubtotals) {
189
+ const rows = [];
190
+ const claimed = new Set();
191
+ for (const service of serviceSubtotals) {
192
+ const match = comparable.find((item) => item.description.startsWith(service.name));
193
+ // A prefix match is not exclusive: with services "Beratung" and "Beratung
194
+ // Zusatz", the one line item "Beratung Zusatz - Mai" starts with both names
195
+ // and each row would then claim its full hours, reporting the invoice twice.
196
+ // The mapping is ambiguous in that case, which is the same situation as no
197
+ // match at all -- say so instead of inventing a breakdown that double-counts.
198
+ if (!match || claimed.has(match.id))
199
+ return null;
200
+ claimed.add(match.id);
201
+ const lineItemHours = match.hours ?? 0;
202
+ const difference = round2(lineItemHours - service.billable.hours);
203
+ rows.push({
204
+ name: service.name,
205
+ line_item_hours: lineItemHours,
206
+ billable_hours: service.billable.hours,
207
+ difference_hours: difference,
208
+ status: Math.abs(difference) < RECONCILE_TOLERANCE_HOURS ? 'ok' : 'mismatch',
209
+ });
210
+ }
211
+ return rows.length > 0 ? rows : null;
212
+ }
213
+ function round2(value) {
214
+ return Math.round(value * 100) / 100;
215
+ }
216
+ /**
217
+ * Page through a list endpoint until it runs out.
218
+ *
219
+ * Takes a callback rather than a client so it can be tested without any HTTP
220
+ * mock. Two stop conditions, both needed: `meta.total_pages` when the API sends
221
+ * it, and a short page regardless of what meta said.
222
+ *
223
+ * Rows are deduplicated by id, and `expected` is carried out so the caller can
224
+ * notice a mismatch. That matters more here than for bookings: `/time_entries`
225
+ * rejects every sort key but `date`, which is not unique, so rows sharing a date
226
+ * can in principle be ordered differently between two page requests and one
227
+ * could slip across a boundary. Deduplication cannot see that happen; comparing
228
+ * the final count against `expected` can.
229
+ */
230
+ export async function collectPages(fetchPage, maxPages = MAX_TIME_ENTRY_PAGES,
231
+ // The size `fetchPage` actually asks for. The short-page stop compares
232
+ // against this, so a caller requesting smaller pages must say so or every
233
+ // full page looks short and the sweep stops after the first one.
234
+ pageSize = MAX_PAGE_SIZE) {
235
+ const byId = new Map();
236
+ const included = [];
237
+ let expected;
238
+ for (let page = 1; page <= maxPages; page += 1) {
239
+ const response = await fetchPage(page);
240
+ const rows = response.data ?? [];
241
+ for (const row of rows)
242
+ byId.set(row.id, row);
243
+ included.push(...(response.included ?? []));
244
+ if (page === 1)
245
+ expected = response.meta?.total_count;
246
+ const totalPages = response.meta?.total_pages;
247
+ if (typeof totalPages === 'number' && page >= totalPages)
248
+ break;
249
+ if (rows.length < pageSize)
250
+ break;
251
+ if (page === maxPages) {
252
+ return { rows: [...byId.values()], included, truncated: true, expected };
253
+ }
254
+ }
255
+ return { rows: [...byId.values()], included, truncated: false, expected };
256
+ }
@@ -0,0 +1,106 @@
1
+ /** A page with no title set still has to be nameable in the output. */
2
+ export const UNTITLED = '(untitled)';
3
+ /**
4
+ * Group pages by their parent id.
5
+ *
6
+ * Siblings are ordered by `position`, falling back to the title. The fallback
7
+ * is the common case rather than the exception: `position` comes back null on
8
+ * every page in the live orgs checked so far, and `sort=position` is rejected
9
+ * by the API (400 `sort_param_unsupported`), so this is the only ordering
10
+ * available.
11
+ */
12
+ export function buildChildIndex(pages) {
13
+ const index = new Map();
14
+ for (const page of pages) {
15
+ const parentId = page.attributes?.parent_page_id;
16
+ if (parentId == null)
17
+ continue;
18
+ const key = String(parentId);
19
+ const siblings = index.get(key);
20
+ if (siblings)
21
+ siblings.push(page);
22
+ else
23
+ index.set(key, [page]);
24
+ }
25
+ for (const siblings of index.values()) {
26
+ siblings.sort(compareSiblings);
27
+ }
28
+ return index;
29
+ }
30
+ function compareSiblings(a, b) {
31
+ const posA = a.attributes?.position;
32
+ const posB = b.attributes?.position;
33
+ if (typeof posA === 'number' && typeof posB === 'number' && posA !== posB) {
34
+ return posA - posB;
35
+ }
36
+ if ((typeof posA === 'number') !== (typeof posB === 'number')) {
37
+ // A page with a position set sorts ahead of one without.
38
+ return typeof posA === 'number' ? -1 : 1;
39
+ }
40
+ return titleOf(a).localeCompare(titleOf(b));
41
+ }
42
+ function titleOf(page) {
43
+ const title = page.attributes?.title;
44
+ return typeof title === 'string' && title.trim() !== '' ? title : UNTITLED;
45
+ }
46
+ /**
47
+ * Walk down from `rootId`, deepest-first, into a nested tree.
48
+ *
49
+ * `visited` is not defensive dressing: the parent links come off the wire, and
50
+ * a cycle in them would otherwise spin here forever rather than return a wrong
51
+ * answer. `maxDepth` counts levels below the starting page -- 1 means direct
52
+ * children only.
53
+ */
54
+ export function collectSubtree(rootId, index, maxDepth = Number.POSITIVE_INFINITY) {
55
+ const visited = new Set([rootId]);
56
+ const descend = (parentId, depth) => {
57
+ if (depth > maxDepth)
58
+ return [];
59
+ const children = index.get(parentId) ?? [];
60
+ const nodes = [];
61
+ for (const child of children) {
62
+ if (visited.has(child.id))
63
+ continue;
64
+ visited.add(child.id);
65
+ nodes.push({
66
+ id: child.id,
67
+ title: titleOf(child),
68
+ editedAt: typeof child.attributes?.edited_at === 'string' ? child.attributes.edited_at : undefined,
69
+ version: typeof child.attributes?.version_number === 'number'
70
+ ? child.attributes.version_number
71
+ : undefined,
72
+ children: descend(child.id, depth + 1),
73
+ });
74
+ }
75
+ return nodes;
76
+ };
77
+ return descend(rootId, 1);
78
+ }
79
+ /** Total pages in the tree, all levels counted. */
80
+ export function countNodes(nodes) {
81
+ return nodes.reduce((total, node) => total + 1 + countNodes(node.children), 0);
82
+ }
83
+ /**
84
+ * Render the tree with box-drawing connectors, one page per line.
85
+ *
86
+ * The last child of a group gets the corner and its descendants are indented
87
+ * with blank space; every earlier one keeps a trailing bar so the column stays
88
+ * connected down the page.
89
+ */
90
+ export function renderTree(nodes, prefix = '') {
91
+ return nodes
92
+ .map((node, i) => {
93
+ const last = i === nodes.length - 1;
94
+ const line = `${prefix}${last ? '└─' : '├─'} ${formatNode(node)}`;
95
+ if (node.children.length === 0)
96
+ return line;
97
+ const childPrefix = `${prefix}${last ? ' ' : '│ '}`;
98
+ return `${line}\n${renderTree(node.children, childPrefix)}`;
99
+ })
100
+ .join('\n');
101
+ }
102
+ function formatNode(node) {
103
+ const version = node.version != null ? `, v${node.version}` : '';
104
+ const edited = node.editedAt ? ` — edited ${node.editedAt.slice(0, 10)}` : '';
105
+ return `${node.title} (ID: ${node.id}${version})${edited}`;
106
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * A time entry's note is a small HTML document, not text.
3
+ *
4
+ * Productive's UI writes it through a rich-text editor, so `attributes.note`
5
+ * comes back as markup: 197 of 200 sampled entries carried tags. Handing that
6
+ * straight to a caller (which is what `list_time_entries` does today) puts
7
+ * `<ul><li><p>` in front of a human and burns tokens on a model.
8
+ *
9
+ * The grammar is small and was measured, not assumed -- a 600-entry sample from
10
+ * the sandbox contained only `<ul>`, `<li>` and `<p>`, no nesting, and only the
11
+ * four entities `&amp; &lt; &gt; &nbsp;`. Three shapes in that sample are the
12
+ * reason this is not a one-line `replace(/<[^>]+>/g, '')`:
13
+ *
14
+ * 1. Two consecutive `<ul>` blocks in one note (entry 138732468). They are one
15
+ * list to a reader, and a `<ul>`-aware parser is exactly what would split
16
+ * them in two.
17
+ * 2. A trailing empty `<p></p>` (3 entries), which must not become a bullet.
18
+ * 3. Plain text with no tags at all (3 entries), which must still yield one
19
+ * bullet rather than nothing.
20
+ *
21
+ * Line item descriptions carry a wider vocabulary (`<div class="...">`), so the
22
+ * tag stripping has to tolerate attributes. This module is deliberately not
23
+ * invoice-specific: `list_time_entries` is the obvious next caller.
24
+ */
25
+ /**
26
+ * Split a note into its bullet points.
27
+ *
28
+ * Returns `[]` for an absent or empty note -- callers render no list at all in
29
+ * that case rather than an empty one.
30
+ */
31
+ export function noteToBullets(note) {
32
+ if (!note || !note.trim())
33
+ return [];
34
+ // Scanning for `<li>` and `<p>` rather than walking `<ul>` is what flattens
35
+ // two adjacent lists into one: their children are collected in document
36
+ // order and the list wrapper is never looked at. Non-greedy `*?` is exact
37
+ // here only because the sampled grammar has no nesting -- if Productive ever
38
+ // starts emitting nested lists, this is the line that has to change.
39
+ const blockPattern = /<(li|p)\b[^>]*>([\s\S]*?)<\/\1>/gi;
40
+ const blocks = [...note.matchAll(blockPattern)].map((match) => match[2]);
41
+ // No block markup at all: the whole note is one bullet.
42
+ const candidates = blocks.length > 0 ? blocks : [note];
43
+ return candidates.map(toPlainText).filter((line) => line.length > 0);
44
+ }
45
+ /** Strip markup, decode entities, and normalise whitespace to a single line. */
46
+ function toPlainText(fragment) {
47
+ // Tags first, entities second. The other order would turn a decoded `&lt;b&gt;`
48
+ // into something the tag pattern then eats as markup.
49
+ //
50
+ // A tag becomes a space, not nothing: dropping a `<br>` outright welds the
51
+ // words either side of it into `Zeileeins`, which is a worse error than the
52
+ // extra space an inline tag would leave -- and the whitespace collapse below
53
+ // removes that anyway.
54
+ const withoutTags = fragment.replace(/<[^>]+>/g, ' ');
55
+ // Collapsing whitespace is a safety property, not just cosmetics: it
56
+ // guarantees a note cannot contain a newline, so note text can never forge a
57
+ // line of its own in a rendered report.
58
+ return decodeEntities(withoutTags).replace(/\s+/g, ' ').trim();
59
+ }
60
+ /**
61
+ * Decode the entities Productive actually emits.
62
+ *
63
+ * `&amp;` MUST come last. Decoding it first turns the literal `&amp;lt;` into
64
+ * `&lt;` and then into `<` -- a double decode that silently rewrites the text.
65
+ */
66
+ function decodeEntities(text) {
67
+ return text
68
+ .replace(/&nbsp;/gi, ' ')
69
+ .replace(/&lt;/gi, '<')
70
+ .replace(/&gt;/gi, '>')
71
+ .replace(/&quot;/gi, '"')
72
+ .replace(/&#0*39;/g, "'")
73
+ .replace(/&apos;/gi, "'")
74
+ .replace(/&amp;/gi, '&');
75
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Inline SVG logo for Productive MCP.
3
+ * Teal gradient with a minimal "link" icon representing API integration.
4
+ * Exported as a data URI for use in HTML without external file dependencies.
5
+ */
6
+ export const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" fill="none">
7
+ <defs>
8
+ <linearGradient id="mg" x1="0" y1="0" x2="80" y2="80" gradientUnits="userSpaceOnUse">
9
+ <stop offset="0%" stop-color="#5BBFB5"/>
10
+ <stop offset="50%" stop-color="#154944"/>
11
+ <stop offset="100%" stop-color="#1a5c55"/>
12
+ </linearGradient>
13
+ </defs>
14
+ <rect width="80" height="80" rx="18" fill="url(#mg)"/>
15
+ <g stroke="#fff" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round" fill="none">
16
+ <path d="M30 40h20"/>
17
+ <path d="M36 32a10 10 0 1 0 0 16"/>
18
+ <path d="M44 32a10 10 0 1 1 0 16"/>
19
+ </g>
20
+ </svg>`;
21
+ export const LOGO_DATA_URI = `data:image/svg+xml;base64,${typeof btoa !== 'undefined' ? btoa(LOGO_SVG) : Buffer.from(LOGO_SVG).toString('base64')}`;
@@ -0,0 +1,61 @@
1
+ import { z } from 'zod';
2
+ import { ProductiveApiError } from '../api/errors.js';
3
+ const DEFAULT_TIMEOUT_MS = 5000;
4
+ const MembershipsSchema = z.object({
5
+ data: z.array(z.object({
6
+ relationships: z
7
+ .object({
8
+ person: z.object({ data: z.object({ id: z.string().min(1) }).nullish() }).optional(),
9
+ })
10
+ .optional(),
11
+ })),
12
+ });
13
+ /** stderr only: stdout is the MCP channel. Never pass the token or headers in here. */
14
+ function warn(reason) {
15
+ console.error(`Could not determine the Productive person ID from the API token (${reason}). ` +
16
+ 'Starting without "me" context -- set PRODUCTIVE_USER_ID to enable it.');
17
+ }
18
+ function describeFailure(error) {
19
+ if (error instanceof ProductiveApiError)
20
+ return `HTTP ${error.httpStatus}`;
21
+ if (error instanceof Error && error.name === 'TimeoutError')
22
+ return 'request timed out';
23
+ if (error instanceof z.ZodError)
24
+ return 'unexpected response shape';
25
+ return error instanceof Error ? error.message : 'unknown error';
26
+ }
27
+ /**
28
+ * Resolve the person ID of the token owner, for the stdio entry point where no
29
+ * Entra identity is available (the Worker uses `user-resolver.ts` instead).
30
+ *
31
+ * Takes the ID only when the memberships name exactly one person -- anything
32
+ * else is ambiguous, and a wrong "me" is worse than none. Never throws: like the
33
+ * Worker resolver, the person ID only powers the "me" keyword, so a failure
34
+ * degrades to `undefined` with a warning instead of stopping the server.
35
+ */
36
+ export async function resolveSelfPersonId(client, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
37
+ try {
38
+ const response = await client.listOwnOrganizationMemberships(AbortSignal.timeout(timeoutMs));
39
+ const { data } = MembershipsSchema.parse(response);
40
+ const personIds = new Set(data.flatMap((membership) => membership.relationships?.person?.data?.id ?? []));
41
+ if (personIds.size === 1)
42
+ return [...personIds][0];
43
+ warn(personIds.size === 0
44
+ ? 'no organization membership found'
45
+ : `${personIds.size} different people found, refusing to guess`);
46
+ return undefined;
47
+ }
48
+ catch (error) {
49
+ warn(describeFailure(error));
50
+ return undefined;
51
+ }
52
+ }
53
+ /**
54
+ * An explicitly configured PRODUCTIVE_USER_ID always wins and costs no API call;
55
+ * otherwise it is resolved from the token.
56
+ */
57
+ export async function withSelfPersonId(config, client) {
58
+ if (config.PRODUCTIVE_USER_ID)
59
+ return config;
60
+ return { ...config, PRODUCTIVE_USER_ID: await resolveSelfPersonId(client) };
61
+ }
@@ -0,0 +1,24 @@
1
+ import { config } from 'dotenv';
2
+ import { z } from 'zod';
3
+ // Silence dotenv output to stdout (MCP requires clean stdout)
4
+ const originalWrite = process.stdout.write;
5
+ process.stdout.write = () => true;
6
+ // Load environment variables
7
+ config();
8
+ // Restore stdout.write
9
+ process.stdout.write = originalWrite;
10
+ const configSchema = z.object({
11
+ PRODUCTIVE_API_TOKEN: z.string().min(1, 'API token is required'),
12
+ PRODUCTIVE_ORG_ID: z.string().min(1, 'Organization ID is required'),
13
+ PRODUCTIVE_USER_ID: z.string().optional(),
14
+ PRODUCTIVE_API_BASE_URL: z.string().url().default('https://api.productive.io/api/v2/'),
15
+ PRODUCTIVE_TOOLSETS: z.string().optional(),
16
+ });
17
+ export function getConfig() {
18
+ const result = configSchema.safeParse(process.env);
19
+ if (!result.success) {
20
+ console.error('Configuration validation failed:', result.error.format());
21
+ throw new Error('Invalid configuration. Please check your environment variables.');
22
+ }
23
+ return result.data;
24
+ }
package/build/index.js ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { createServer } from './server.js';
3
+ async function main() {
4
+ try {
5
+ await createServer();
6
+ }
7
+ catch (error) {
8
+ console.error('Failed to start server:', error);
9
+ process.exit(1);
10
+ }
11
+ }
12
+ main().catch((error) => {
13
+ console.error('Unhandled error:', error);
14
+ process.exit(1);
15
+ });