@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,45 @@
1
+ /**
2
+ * Builds a lookup map from a JSON API included[] array.
3
+ * Key format: "type:id" → human-readable name
4
+ * Supported types: people, companies, projects, tasks, deals, task_lists, boards
5
+ */
6
+ export function buildIncludeMap(included) {
7
+ const map = new Map();
8
+ if (!included)
9
+ return map;
10
+ for (const resource of included) {
11
+ const key = `${resource.type}:${resource.id}`;
12
+ const attrs = resource.attributes;
13
+ let name;
14
+ if (resource.type === 'people') {
15
+ const first = typeof attrs.first_name === 'string' ? attrs.first_name : '';
16
+ const last = typeof attrs.last_name === 'string' ? attrs.last_name : '';
17
+ name = `${first} ${last}`.trim() || undefined;
18
+ }
19
+ else {
20
+ // Tasks name themselves with `title`, not `name` (live: a sideloaded task
21
+ // carries `title: "#940 - Versandanweisung"` and no `name` at all). Reading
22
+ // only `name` is why this map has never resolved a task despite the
23
+ // docblock above listing them, and why `list_time_entries` always printed
24
+ // the bare task ID.
25
+ name =
26
+ typeof attrs.name === 'string'
27
+ ? attrs.name
28
+ : typeof attrs.title === 'string'
29
+ ? attrs.title
30
+ : undefined;
31
+ }
32
+ if (name)
33
+ map.set(key, name);
34
+ }
35
+ return map;
36
+ }
37
+ /**
38
+ * Resolves an entity ID to a name using the include map.
39
+ * Returns undefined if id is absent or if the name was not sideloaded.
40
+ */
41
+ export function resolveName(map, type, id) {
42
+ if (!id)
43
+ return undefined;
44
+ return map.get(`${type}:${id}`);
45
+ }
@@ -0,0 +1,476 @@
1
+ import { z } from 'zod';
2
+ import { toMcpError } from '../utils/errors.js';
3
+ /** Coerce "true"/"false" strings to booleans (some MCP clients send strings). */
4
+ const coerceBoolean = z.preprocess((v) => (v === 'true' ? true : v === 'false' ? false : v), z.boolean());
5
+ // ─── finalize_invoice ────────────────────────────────────────────────────────
6
+ const finalizeInvoiceSchema = z.object({
7
+ invoice_id: z.string().min(1),
8
+ confirm: coerceBoolean.optional(),
9
+ });
10
+ /**
11
+ * Finalize an invoice (irreversible action).
12
+ *
13
+ * Requires explicit confirmation before executing because finalizing cannot be undone.
14
+ *
15
+ * @param client - Productive API client
16
+ * @param args - Tool arguments matching finalizeInvoiceSchema
17
+ * @returns MCP content response
18
+ */
19
+ export async function finalizeInvoiceTool(client, args) {
20
+ try {
21
+ const params = finalizeInvoiceSchema.parse(args);
22
+ if (!params.confirm) {
23
+ return {
24
+ content: [
25
+ {
26
+ type: 'text',
27
+ text: `⚠️ Finalizing invoice ${params.invoice_id} is IRREVERSIBLE.\n\nOnce finalized, the invoice cannot be edited or deleted. Call this tool again with confirm: true to proceed.`,
28
+ },
29
+ ],
30
+ };
31
+ }
32
+ const response = await client.finalizeInvoice(params.invoice_id);
33
+ const invoice = response.data;
34
+ const attrs = invoice.attributes;
35
+ return {
36
+ content: [
37
+ {
38
+ type: 'text',
39
+ text: [
40
+ `Invoice finalized!`,
41
+ `Number: ${attrs.number ?? 'N/A'}`,
42
+ `Total: ${(parseInt(attrs.amount_with_tax ?? '0', 10) / 100).toFixed(2)} ${attrs.currency ?? ''}`,
43
+ ``,
44
+ `Next step: Use mark_invoice_paid once payment is received.`,
45
+ ].join('\n'),
46
+ },
47
+ ],
48
+ };
49
+ }
50
+ catch (error) {
51
+ throw toMcpError(error);
52
+ }
53
+ }
54
+ export const finalizeInvoiceDefinition = {
55
+ name: 'finalize_invoice',
56
+ description: 'Finalize an invoice, making it ready to send to the client. This action is IRREVERSIBLE — the invoice can no longer be edited after finalization. Requires confirm: true.',
57
+ inputSchema: {
58
+ type: 'object',
59
+ properties: {
60
+ invoice_id: {
61
+ type: 'string',
62
+ description: 'ID of the invoice to finalize',
63
+ },
64
+ confirm: {
65
+ type: 'boolean',
66
+ description: 'Must be true to execute the irreversible finalization',
67
+ },
68
+ },
69
+ required: ['invoice_id'],
70
+ },
71
+ annotations: {
72
+ title: 'Finalize invoice',
73
+ readOnlyHint: false,
74
+ destructiveHint: true,
75
+ idempotentHint: true,
76
+ openWorldHint: true,
77
+ },
78
+ };
79
+ // ─── get_invoice_pdf_url ─────────────────────────────────────────────────────
80
+ const getInvoicePdfUrlSchema = z.object({
81
+ invoice_id: z.string().min(1),
82
+ });
83
+ function buildPdfUrl(invoiceId, invoiceNumber, config) {
84
+ const baseUrl = config.PRODUCTIVE_API_BASE_URL;
85
+ const isSandbox = baseUrl.includes('sandbox');
86
+ const exporterHost = isSandbox ? 'exporter-sandbox.productive.io' : 'exporter.productive.io';
87
+ const appHost = isSandbox ? 'sandbox.productive.io' : 'app.productive.io';
88
+ const orgId = config.PRODUCTIVE_ORG_ID;
89
+ const payload = {
90
+ name: `invoice_${invoiceNumber}`,
91
+ url: `https://${appHost}/${orgId}/export/document/invoice/${invoiceId}`,
92
+ };
93
+ const encoded = Buffer.from(JSON.stringify(payload)).toString('base64');
94
+ return `https://${exporterHost}/export/document?payload=${encodeURIComponent(encoded)}&download=true`;
95
+ }
96
+ export async function getInvoicePdfUrlTool(client, args, config) {
97
+ try {
98
+ const { invoice_id } = getInvoicePdfUrlSchema.parse(args);
99
+ const response = await client.getInvoice(invoice_id);
100
+ const number = response.data.attributes.number ?? invoice_id;
101
+ const url = buildPdfUrl(invoice_id, number, config);
102
+ return {
103
+ content: [
104
+ {
105
+ type: 'text',
106
+ text: `PDF download URL for invoice #${number}:\n\n${url}`,
107
+ },
108
+ ],
109
+ };
110
+ }
111
+ catch (error) {
112
+ throw toMcpError(error);
113
+ }
114
+ }
115
+ export const getInvoicePdfUrlDefinition = {
116
+ name: 'get_invoice_pdf_url',
117
+ description: 'Generate a PDF download URL for an invoice. The URL must be opened in a browser where the user is logged into Productive — it does not work via API or curl. Use list_invoices or get_invoice to find the invoice_id.',
118
+ inputSchema: {
119
+ type: 'object',
120
+ properties: {
121
+ invoice_id: {
122
+ type: 'string',
123
+ description: 'ID of the invoice',
124
+ },
125
+ },
126
+ required: ['invoice_id'],
127
+ },
128
+ annotations: { title: 'Get invoice PDF URL', readOnlyHint: true, openWorldHint: true },
129
+ };
130
+ // ─── delete_invoice ──────────────────────────────────────────────────────────
131
+ const deleteInvoiceSchema = z.object({
132
+ invoice_id: z.string().min(1),
133
+ confirm: coerceBoolean.optional(),
134
+ });
135
+ /**
136
+ * Delete a draft invoice.
137
+ *
138
+ * Fetches the invoice first to verify it is a draft (not yet finalized).
139
+ * Finalized invoices cannot be deleted. Requires explicit confirmation
140
+ * before executing because deletion is irreversible.
141
+ *
142
+ * @param client - Productive API client
143
+ * @param args - Tool arguments matching deleteInvoiceSchema
144
+ * @returns MCP content response
145
+ */
146
+ export async function deleteInvoiceTool(client, args) {
147
+ try {
148
+ const params = deleteInvoiceSchema.parse(args);
149
+ const invoiceResponse = await client.getInvoice(params.invoice_id);
150
+ const attrs = invoiceResponse.data.attributes;
151
+ if (attrs.finalized_at) {
152
+ return {
153
+ content: [
154
+ {
155
+ type: 'text',
156
+ text: `Cannot delete finalized invoice ${params.invoice_id}. Only draft invoices can be deleted.`,
157
+ },
158
+ ],
159
+ };
160
+ }
161
+ if (!params.confirm) {
162
+ return {
163
+ content: [
164
+ {
165
+ type: 'text',
166
+ text: [
167
+ `Delete preview for invoice ${params.invoice_id}:`,
168
+ ` Number: ${attrs.number ?? 'N/A'}`,
169
+ ` Status: Draft`,
170
+ ``,
171
+ `This action is IRREVERSIBLE. Call again with confirm: true to delete.`,
172
+ ].join('\n'),
173
+ },
174
+ ],
175
+ };
176
+ }
177
+ await client.deleteInvoice(params.invoice_id);
178
+ return {
179
+ content: [
180
+ {
181
+ type: 'text',
182
+ text: `Invoice ${params.invoice_id} deleted.`,
183
+ },
184
+ ],
185
+ };
186
+ }
187
+ catch (error) {
188
+ throw toMcpError(error);
189
+ }
190
+ }
191
+ export const deleteInvoiceDefinition = {
192
+ name: 'delete_invoice',
193
+ description: 'Delete a draft invoice. Only draft invoices (not yet finalized) can be deleted. This action is irreversible. Requires confirm: true to execute.',
194
+ inputSchema: {
195
+ type: 'object',
196
+ properties: {
197
+ invoice_id: {
198
+ type: 'string',
199
+ description: 'ID of the invoice to delete',
200
+ },
201
+ confirm: {
202
+ type: 'boolean',
203
+ description: 'Must be true to execute the irreversible deletion',
204
+ },
205
+ },
206
+ required: ['invoice_id'],
207
+ },
208
+ annotations: {
209
+ title: 'Delete invoice',
210
+ readOnlyHint: false,
211
+ destructiveHint: true,
212
+ idempotentHint: true,
213
+ openWorldHint: true,
214
+ },
215
+ };
216
+ // ─── get_timesheet_report_url ────────────────────────────────────────────────
217
+ const getTimesheetReportUrlSchema = z.object({
218
+ budget_id: z.string().describe('Budget/Deal ID'),
219
+ date_from: z.string().describe('Start date YYYY-MM-DD'),
220
+ date_to: z.string().describe('End date YYYY-MM-DD'),
221
+ columns: z.string().describe('Comma-separated columns, e.g. "day,person,note,billable-time"'),
222
+ name: z.string().describe('PDF filename, e.g. "Zeitnachweis_20260011"'),
223
+ title: z.string().describe('Title shown in PDF header'),
224
+ group_by: z
225
+ .string()
226
+ .default('time-entry')
227
+ .optional()
228
+ .describe('Grouping: "time-entry", "task", "person", "service"'),
229
+ sort_by: z.string().default('day').optional().describe('Sort field'),
230
+ orientation: z.string().default('portrait').optional().describe('"portrait" or "landscape"'),
231
+ page_size: z.string().default('A4').optional().describe('Page size'),
232
+ });
233
+ function buildTimesheetReportUrl(params, config) {
234
+ const baseUrl = config.PRODUCTIVE_API_BASE_URL;
235
+ const isSandbox = baseUrl.includes('sandbox');
236
+ const exporterHost = isSandbox ? 'exporter-sandbox.productive.io' : 'exporter.productive.io';
237
+ const appHost = isSandbox ? 'sandbox.productive.io' : 'app.productive.io';
238
+ const orgId = config.PRODUCTIVE_ORG_ID;
239
+ const dateFrom = params.date_from;
240
+ const dateTo = params.date_to;
241
+ const startD = new Date(dateFrom);
242
+ startD.setUTCDate(startD.getUTCDate() - 1);
243
+ const startDateISO = `${startD.toISOString().slice(0, 10)}T23:00:00.000Z`;
244
+ const endDateISO = `${dateTo}T22:00:00.000Z`;
245
+ const exportData = {
246
+ name: params.name,
247
+ format: '1',
248
+ pageSize: params.page_size ?? 'A4',
249
+ isAttachmentsEnabled: false,
250
+ orientation: params.orientation ?? 'portrait',
251
+ exportAs: 'manager',
252
+ isTimeExport: false,
253
+ isTimeEntryReportExport: true,
254
+ itemTypeColumnId: 'day',
255
+ extraApiParams: null,
256
+ apiFilterParams: {
257
+ '0': { date: { gtEq: dateFrom, ltEq: dateTo } },
258
+ '1': { budgetId: { eq: [params.budget_id] } },
259
+ '2': { 'service.billable': { eq: true } },
260
+ '3': { billableTime: { gt: 0 } },
261
+ '4': { billingTypeId: { eq: '2' } },
262
+ $op: 'and',
263
+ },
264
+ description: null,
265
+ dateFilters: [
266
+ {
267
+ label: 'Date',
268
+ value: [{ intervalId: '4', startDate: startDateISO, endDate: endDateISO }],
269
+ },
270
+ ],
271
+ };
272
+ const filterData = {
273
+ name: params.title,
274
+ default: false,
275
+ filterableCollection: 'time_entry_reports',
276
+ public: false,
277
+ columns: params.columns,
278
+ params: {
279
+ '0': {
280
+ '0': { date: { eq: '4' } },
281
+ '1': { budget_id: { eq: [params.budget_id] } },
282
+ '2': { 'service.billable': { eq: true } },
283
+ '3': { billable_time: { gt: 0 } },
284
+ '4': { billing_type_id: { eq: '2' } },
285
+ $op: 'and',
286
+ },
287
+ $op: 'and',
288
+ },
289
+ sortBy: params.sort_by ?? 'day',
290
+ groupBy: params.group_by ?? 'time-entry',
291
+ layoutId: 103,
292
+ chartTypeId: '3',
293
+ reportLayoutId: '2',
294
+ transposeBy: null,
295
+ report: true,
296
+ columnSettings: { person: { avatar: false } },
297
+ formulas: {},
298
+ exchangeCurrency: null,
299
+ exchangeDate: { intervalId: '12', startDate: null, endDate: null, date: null },
300
+ typeId: '2',
301
+ };
302
+ const exportB64 = Buffer.from(JSON.stringify(exportData)).toString('base64');
303
+ const filterB64 = Buffer.from(JSON.stringify(filterData)).toString('base64');
304
+ const innerUrl = `https://${appHost}/${orgId}/export/report/time_entry_reports?exportData=${exportB64}&filter=${filterB64}&download=true`;
305
+ const outerB64 = Buffer.from(innerUrl).toString('base64');
306
+ return `https://${exporterHost}/export?timezone=Bern&url=${encodeURIComponent(outerB64)}`;
307
+ }
308
+ export async function getTimesheetReportUrlTool(_client, args, config) {
309
+ try {
310
+ const params = getTimesheetReportUrlSchema.parse(args);
311
+ const url = buildTimesheetReportUrl(params, config);
312
+ return {
313
+ content: [
314
+ {
315
+ type: 'text',
316
+ text: `Timesheet report URL for "${params.title}":\n\n${url}\n\nOpen in browser (must be logged into Productive).`,
317
+ },
318
+ ],
319
+ };
320
+ }
321
+ catch (error) {
322
+ throw toMcpError(error);
323
+ }
324
+ }
325
+ export const getTimesheetReportUrlDefinition = {
326
+ name: 'get_timesheet_report_url',
327
+ description: 'Generate a PDF timesheet/time-entry report URL for a specific budget. Shows billable time entries with configurable columns, grouping, and sorting. NOT for invoice PDFs — use get_invoice_pdf_url for that. Use list_company_budgets to get budget_id. URL must be opened in a browser where the user is logged into Productive.',
328
+ inputSchema: {
329
+ type: 'object',
330
+ required: ['budget_id', 'date_from', 'date_to', 'columns', 'name', 'title'],
331
+ properties: {
332
+ budget_id: { type: 'string', description: 'Budget/Deal ID' },
333
+ date_from: { type: 'string', description: 'Start date YYYY-MM-DD' },
334
+ date_to: { type: 'string', description: 'End date YYYY-MM-DD' },
335
+ columns: {
336
+ type: 'string',
337
+ description: 'Comma-separated columns. Available: "day", "person", "note", "billable-time", "task", "service"',
338
+ },
339
+ name: { type: 'string', description: 'PDF filename (e.g. "Zeitnachweis_20260011")' },
340
+ title: { type: 'string', description: 'Title shown in PDF header' },
341
+ group_by: {
342
+ type: 'string',
343
+ description: 'Grouping: "time-entry" (default), "task", "person", "service"',
344
+ },
345
+ sort_by: { type: 'string', description: 'Sort field (default: "day")' },
346
+ orientation: { type: 'string', description: '"portrait" (default) or "landscape"' },
347
+ page_size: { type: 'string', description: 'Page size (default: "A4")' },
348
+ },
349
+ },
350
+ annotations: { title: 'Get timesheet report URL', readOnlyHint: true, openWorldHint: true },
351
+ };
352
+ // ─── mark_invoice_paid ───────────────────────────────────────────────────────
353
+ const markInvoicePaidSchema = z.object({
354
+ invoice_id: z.string().min(1),
355
+ paid_on: z.string().optional(),
356
+ note: z.string().optional(),
357
+ confirm: coerceBoolean.optional(),
358
+ });
359
+ /**
360
+ * Record a payment against an invoice, marking it as paid.
361
+ *
362
+ * Fetches the invoice first to calculate the remaining amount. Requires
363
+ * explicit confirmation before creating the payment record.
364
+ *
365
+ * @param client - Productive API client
366
+ * @param args - Tool arguments matching markInvoicePaidSchema
367
+ * @returns MCP content response
368
+ */
369
+ export async function markInvoicePaidTool(client, args) {
370
+ try {
371
+ const params = markInvoicePaidSchema.parse(args);
372
+ const invoiceResponse = await client.getInvoice(params.invoice_id);
373
+ const attrs = invoiceResponse.data.attributes;
374
+ // Amounts from API are in cents (integer strings)
375
+ const amountWithTaxCents = parseInt(attrs.amount_with_tax ?? '0', 10);
376
+ const remainingCents = parseInt(attrs.amount_unpaid ?? '0', 10);
377
+ const currency = attrs.currency ?? '';
378
+ const fmtAmount = (cents) => (cents / 100).toFixed(2);
379
+ if (remainingCents <= 0) {
380
+ return {
381
+ content: [
382
+ {
383
+ type: 'text',
384
+ text: `Invoice ${params.invoice_id} is already fully paid (total: ${fmtAmount(amountWithTaxCents)} ${currency}).`,
385
+ },
386
+ ],
387
+ };
388
+ }
389
+ const paidOn = params.paid_on ?? new Date().toISOString().slice(0, 10);
390
+ if (!params.confirm) {
391
+ return {
392
+ content: [
393
+ {
394
+ type: 'text',
395
+ text: [
396
+ `Payment preview for invoice ${params.invoice_id}:`,
397
+ ` Will pay: ${fmtAmount(remainingCents)} ${currency} (of total ${fmtAmount(amountWithTaxCents)} ${currency})`,
398
+ ` Date: ${paidOn}`,
399
+ params.note ? ` Note: ${params.note}` : null,
400
+ ``,
401
+ `Call again with confirm: true to record the payment.`,
402
+ ]
403
+ .filter(Boolean)
404
+ .join('\n'),
405
+ },
406
+ ],
407
+ };
408
+ }
409
+ const paymentData = {
410
+ data: {
411
+ type: 'payments',
412
+ attributes: {
413
+ amount: remainingCents.toString(),
414
+ paid_on: paidOn,
415
+ ...(params.note !== undefined && { note: params.note }),
416
+ },
417
+ relationships: {
418
+ invoice: { data: { id: params.invoice_id, type: 'invoices' } },
419
+ },
420
+ },
421
+ };
422
+ await client.createPayment(paymentData);
423
+ return {
424
+ content: [
425
+ {
426
+ type: 'text',
427
+ text: [
428
+ `Payment recorded successfully!`,
429
+ ` Invoice: ${params.invoice_id}`,
430
+ ` Amount paid: ${fmtAmount(remainingCents)} ${currency}`,
431
+ ` Date: ${paidOn}`,
432
+ params.note ? ` Note: ${params.note}` : null,
433
+ ]
434
+ .filter(Boolean)
435
+ .join('\n'),
436
+ },
437
+ ],
438
+ };
439
+ }
440
+ catch (error) {
441
+ throw toMcpError(error);
442
+ }
443
+ }
444
+ export const markInvoicePaidDefinition = {
445
+ name: 'mark_invoice_paid',
446
+ description: 'Mark an invoice as fully paid. Automatically calculates the remaining unpaid amount and creates a payment for that exact amount. Requires confirm: true to execute.',
447
+ inputSchema: {
448
+ type: 'object',
449
+ properties: {
450
+ invoice_id: {
451
+ type: 'string',
452
+ description: 'ID of the invoice to mark as paid',
453
+ },
454
+ paid_on: {
455
+ type: 'string',
456
+ description: 'Payment date in YYYY-MM-DD format (defaults to today)',
457
+ },
458
+ note: {
459
+ type: 'string',
460
+ description: 'Optional note to attach to the payment record',
461
+ },
462
+ confirm: {
463
+ type: 'boolean',
464
+ description: 'Must be true to record the payment',
465
+ },
466
+ },
467
+ required: ['invoice_id'],
468
+ },
469
+ annotations: {
470
+ title: 'Mark invoice paid',
471
+ readOnlyHint: false,
472
+ destructiveHint: true,
473
+ idempotentHint: true,
474
+ openWorldHint: true,
475
+ },
476
+ };
@@ -0,0 +1,65 @@
1
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
+ export async function resolveInvoiceDefaults(client) {
3
+ const [docTypes, taxRates, subsidiaries] = await Promise.all([
4
+ client.listDocumentTypes({ limit: 200 }),
5
+ client.listTaxRates({ limit: 200 }),
6
+ client.listSubsidiaries(),
7
+ ]);
8
+ // Document Type: filter for invoices (exportable_type_id === 1) that are not archived
9
+ const activeInvoiceTypes = (docTypes.data ?? []).filter((dt) => dt.attributes.exportable_type_id === 1 && !dt.attributes.archived_at);
10
+ let document_type_id;
11
+ let note_template = null;
12
+ let footer_template = null;
13
+ let locale = null;
14
+ if (activeInvoiceTypes.length === 0) {
15
+ throw new McpError(ErrorCode.InternalError, 'No active invoice document type found.');
16
+ }
17
+ else if (activeInvoiceTypes.length === 1) {
18
+ const dt = activeInvoiceTypes[0];
19
+ document_type_id = dt.id;
20
+ note_template = dt.attributes.note ?? null;
21
+ footer_template = dt.attributes.footer ?? null;
22
+ locale = dt.attributes.locale ?? null;
23
+ }
24
+ else {
25
+ const list = activeInvoiceTypes
26
+ .map((dt, i) => `${i + 1}. ${dt.attributes.name} (ID: ${dt.id})`)
27
+ .join('\n');
28
+ throw new McpError(ErrorCode.InvalidParams, `Multiple invoice templates found. Please choose:\n${list}\n\nCall again with document_type_id.`);
29
+ }
30
+ // Tax Rate: filter for not archived
31
+ const activeTaxRates = (taxRates.data ?? []).filter((tr) => !tr.attributes.archived_at);
32
+ let tax_rate_id;
33
+ if (activeTaxRates.length === 0) {
34
+ throw new McpError(ErrorCode.InternalError, 'No active tax rate found.');
35
+ }
36
+ else if (activeTaxRates.length === 1) {
37
+ tax_rate_id = activeTaxRates[0].id;
38
+ }
39
+ else {
40
+ const list = activeTaxRates
41
+ .map((tr, i) => `${i + 1}. ${tr.attributes.name} — ${tr.attributes.primary_component_value}% (ID: ${tr.id})`)
42
+ .join('\n');
43
+ throw new McpError(ErrorCode.InvalidParams, `Multiple tax rates found. Please choose:\n${list}\n\nCall again with tax_rate_id.`);
44
+ }
45
+ // Subsidiary: filter for not archived
46
+ const activeSubsidiaries = (subsidiaries.data ?? []).filter((s) => !s.attributes.archived_at);
47
+ let subsidiary_id = null;
48
+ if (activeSubsidiaries.length === 1) {
49
+ subsidiary_id = activeSubsidiaries[0].id;
50
+ }
51
+ else if (activeSubsidiaries.length > 1) {
52
+ const list = activeSubsidiaries
53
+ .map((s, i) => `${i + 1}. ${s.attributes.name} (ID: ${s.id})`)
54
+ .join('\n');
55
+ throw new McpError(ErrorCode.InvalidParams, `Multiple subsidiaries found. Please choose:\n${list}\n\nCall again with subsidiary_id.`);
56
+ }
57
+ return {
58
+ document_type_id,
59
+ tax_rate_id,
60
+ subsidiary_id,
61
+ note_template,
62
+ footer_template,
63
+ locale,
64
+ };
65
+ }