@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,657 @@
1
+ import { z } from 'zod';
2
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
3
+ import { resolveInvoiceDefaults } from './invoice-defaults.js';
4
+ import { toMcpError } from '../utils/errors.js';
5
+ // ---------------------------------------------------------------------------
6
+ // Helper functions
7
+ // ---------------------------------------------------------------------------
8
+ function deriveInvoiceState(attrs) {
9
+ if (attrs.finalized_at)
10
+ return 'Finalized';
11
+ return 'Draft';
12
+ }
13
+ function derivePaymentStatus(attrs) {
14
+ const unpaid = parseInt(attrs.amount_unpaid || '0', 10);
15
+ const paid = parseInt(attrs.amount_paid || '0', 10);
16
+ if (unpaid <= 0 && paid > 0)
17
+ return 'Paid';
18
+ if (paid > 0 && unpaid > 0)
19
+ return 'Partially Paid';
20
+ return 'Unpaid';
21
+ }
22
+ /** Amounts arrive as integer strings in cents: "2506569" is 25065.69. */
23
+ export function formatAmount(cents) {
24
+ if (!cents)
25
+ return '0.00';
26
+ return (parseInt(cents, 10) / 100).toFixed(2);
27
+ }
28
+ function pad(n) {
29
+ return n.toString().padStart(2, '0');
30
+ }
31
+ function getLastMonthRange() {
32
+ const now = new Date();
33
+ const firstDay = new Date(now.getFullYear(), now.getMonth() - 1, 1);
34
+ const lastDay = new Date(now.getFullYear(), now.getMonth(), 0);
35
+ return {
36
+ date_from: `${firstDay.getFullYear()}-${pad(firstDay.getMonth() + 1)}-${pad(firstDay.getDate())}`,
37
+ date_to: `${lastDay.getFullYear()}-${pad(lastDay.getMonth() + 1)}-${pad(lastDay.getDate())}`,
38
+ };
39
+ }
40
+ export function resolveCompanyName(invoice, included) {
41
+ const companyId = invoice.relationships?.company?.data?.id;
42
+ if (companyId && included) {
43
+ const company = included.find((r) => r.type === 'companies' && r.id === companyId);
44
+ if (company)
45
+ return company.attributes.name;
46
+ }
47
+ return companyId ? `Company #${companyId}` : 'N/A';
48
+ }
49
+ // ---------------------------------------------------------------------------
50
+ // Tool 1: list_invoices
51
+ // ---------------------------------------------------------------------------
52
+ const listInvoicesSchema = z.object({
53
+ company_id: z.string().optional(),
54
+ project_id: z.string().optional(),
55
+ deal_id: z.string().optional(),
56
+ invoice_state: z.coerce.number().optional(),
57
+ invoice_status: z.coerce.number().optional(),
58
+ payment_status: z.coerce.number().optional(),
59
+ after: z.string().optional(),
60
+ before: z.string().optional(),
61
+ full_query: z.string().optional(),
62
+ limit: z.coerce.number().min(1).max(200).default(30).optional(),
63
+ });
64
+ /**
65
+ * Lists invoices from Productive.io with optional filters.
66
+ *
67
+ * @param client - The Productive API client instance
68
+ * @param args - Filter parameters matching listInvoicesSchema
69
+ * @returns Formatted list of invoices with key fields
70
+ */
71
+ export async function listInvoicesTool(client, args) {
72
+ try {
73
+ const params = listInvoicesSchema.parse(args || {});
74
+ const response = await client.listInvoices(params);
75
+ if (!response?.data?.length) {
76
+ return { content: [{ type: 'text', text: 'No invoices found.' }] };
77
+ }
78
+ const lines = response.data.map((inv) => {
79
+ const company = resolveCompanyName(inv, response.included);
80
+ const number = inv.attributes.number ?? 'N/A';
81
+ const date = inv.attributes.invoiced_on ?? 'N/A';
82
+ const amount = formatAmount(inv.attributes.amount_with_tax);
83
+ const currency = inv.attributes.currency ?? '';
84
+ const state = deriveInvoiceState(inv.attributes);
85
+ const payment = derivePaymentStatus(inv.attributes);
86
+ return `• #${number} | ${company} | ${date} | ${amount} ${currency} | ${state} | ${payment} (ID: ${inv.id})`;
87
+ });
88
+ return {
89
+ content: [
90
+ {
91
+ type: 'text',
92
+ text: `Found ${response.data.length} invoice(s):\n\n${lines.join('\n')}`,
93
+ },
94
+ ],
95
+ };
96
+ }
97
+ catch (error) {
98
+ throw toMcpError(error);
99
+ }
100
+ }
101
+ export const listInvoicesDefinition = {
102
+ name: 'list_invoices',
103
+ description: 'List invoices with optional filters. Returns number, company, date, amount, state, and payment status. Use list_companies to get company_id, list_company_budgets to get deal_id.',
104
+ inputSchema: {
105
+ type: 'object',
106
+ properties: {
107
+ company_id: { type: 'string', description: 'Filter by company ID' },
108
+ project_id: { type: 'string', description: 'Filter by project ID' },
109
+ deal_id: { type: 'string', description: 'Filter by deal/budget ID' },
110
+ invoice_state: {
111
+ type: 'number',
112
+ description: 'Filter by state: 1=Draft, 2=Finalized',
113
+ },
114
+ invoice_status: {
115
+ type: 'number',
116
+ description: 'Filter by invoice status number',
117
+ },
118
+ payment_status: {
119
+ type: 'number',
120
+ description: 'Filter by payment status: 1=Paid, 2=Unpaid, 3=Partially Paid',
121
+ },
122
+ after: {
123
+ type: 'string',
124
+ description: 'Filter invoices after this date (YYYY-MM-DD)',
125
+ },
126
+ before: {
127
+ type: 'string',
128
+ description: 'Filter invoices before this date (YYYY-MM-DD)',
129
+ },
130
+ full_query: { type: 'string', description: 'Full-text search query' },
131
+ limit: {
132
+ type: 'number',
133
+ description: 'Max results (1-200, default 30)',
134
+ minimum: 1,
135
+ maximum: 200,
136
+ },
137
+ },
138
+ },
139
+ annotations: { title: 'List invoices', readOnlyHint: true, openWorldHint: true },
140
+ };
141
+ // ---------------------------------------------------------------------------
142
+ // Tool: list_company_budgets
143
+ // ---------------------------------------------------------------------------
144
+ const listCompanyBudgetsSchema = z.object({
145
+ company_id: z.string().describe('Company ID (use list_companies to find)'),
146
+ include_closed: z
147
+ .boolean()
148
+ .default(false)
149
+ .optional()
150
+ .describe('Include closed budgets (default: false, only open)'),
151
+ limit: z.coerce.number().min(1).max(200).default(50).optional(),
152
+ });
153
+ export async function listCompanyBudgetsTool(client, args) {
154
+ try {
155
+ const params = listCompanyBudgetsSchema.parse(args || {});
156
+ const response = await client.listCompanyBudgets({
157
+ company_id: params.company_id,
158
+ status: params.include_closed ? undefined : 1,
159
+ limit: params.limit,
160
+ });
161
+ if (!response?.data?.length) {
162
+ return { content: [{ type: 'text', text: 'No budgets found for this company.' }] };
163
+ }
164
+ const text = response.data
165
+ .map((deal) => {
166
+ const project = response.included?.find((r) => r.type === 'projects' && r.id === deal.relationships?.project?.data?.id);
167
+ const projectName = project ? project.attributes.name : '';
168
+ const po = deal.attributes.purchase_order_number;
169
+ const terms = deal.attributes.payment_terms;
170
+ const details = [];
171
+ if (projectName)
172
+ details.push(`Project: ${projectName}`);
173
+ if (po)
174
+ details.push(`PO: ${po}`);
175
+ if (terms !== undefined)
176
+ details.push(`Payment Terms: ${terms} days`);
177
+ const detailStr = details.length > 0 ? `\n ${details.join(' | ')}` : '';
178
+ return `• ${deal.attributes.name} (ID: ${deal.id})${detailStr}`;
179
+ })
180
+ .join('\n\n');
181
+ return {
182
+ content: [
183
+ {
184
+ type: 'text',
185
+ text: `Found ${response.data.length} budget(s):\n\n${text}`,
186
+ },
187
+ ],
188
+ };
189
+ }
190
+ catch (error) {
191
+ throw toMcpError(error);
192
+ }
193
+ }
194
+ export const listCompanyBudgetsDefinition = {
195
+ name: 'list_company_budgets',
196
+ description: 'List budgets for a company. Shows only open budgets by default. Use list_companies to get company_id. Returns budget IDs needed for generate_line_items. Also returns PO number and payment terms per budget — pass these to create_invoice.',
197
+ inputSchema: {
198
+ type: 'object',
199
+ required: ['company_id'],
200
+ properties: {
201
+ company_id: {
202
+ type: 'string',
203
+ description: 'Company ID (use list_companies)',
204
+ },
205
+ include_closed: {
206
+ type: 'boolean',
207
+ description: 'Include closed budgets (default: false)',
208
+ },
209
+ limit: {
210
+ type: 'number',
211
+ description: 'Max results (1-200, default 50)',
212
+ minimum: 1,
213
+ maximum: 200,
214
+ },
215
+ },
216
+ },
217
+ annotations: { title: 'List company budgets', readOnlyHint: true, openWorldHint: true },
218
+ };
219
+ // ---------------------------------------------------------------------------
220
+ // Tool 2: get_invoice
221
+ // ---------------------------------------------------------------------------
222
+ const getInvoiceSchema = z.object({
223
+ invoice_id: z.string(),
224
+ });
225
+ /**
226
+ * Retrieves full details of a single invoice including line items.
227
+ *
228
+ * @param client - The Productive API client instance
229
+ * @param args - Object containing invoice_id
230
+ * @returns Detailed invoice information with line items
231
+ */
232
+ export async function getInvoiceTool(client, args) {
233
+ try {
234
+ const { invoice_id } = getInvoiceSchema.parse(args || {});
235
+ const [invoiceResponse, lineItemsResponse] = await Promise.all([
236
+ client.getInvoice(invoice_id),
237
+ client.listLineItems({ invoice_id, limit: 200 }),
238
+ ]);
239
+ const inv = invoiceResponse.data;
240
+ const a = inv.attributes;
241
+ const included = invoiceResponse.included;
242
+ const company = resolveCompanyName(inv, included);
243
+ const lineItems = lineItemsResponse.data ?? [];
244
+ const lineItemsText = lineItems.length > 0
245
+ ? lineItems
246
+ .map((li) => {
247
+ const desc = li.attributes.description ?? '—';
248
+ const qty = li.attributes.quantity ?? '';
249
+ const unitPrice = formatAmount(li.attributes.unit_price);
250
+ const amount = formatAmount(li.attributes.amount);
251
+ return ` - ${desc} | qty: ${qty} | unit: ${unitPrice} | total: ${amount} (ID: ${li.id})`;
252
+ })
253
+ .join('\n')
254
+ : ' (none)';
255
+ const exportUrl = a.export_invoice_url ? `\nExport URL: ${a.export_invoice_url}` : '';
256
+ const text = [
257
+ `Invoice (ID: ${inv.id})`,
258
+ `Number: ${a.number ?? 'N/A'}`,
259
+ `Subject: ${a.subject ?? 'N/A'}`,
260
+ `Company: ${company}`,
261
+ `State: ${deriveInvoiceState(a)}`,
262
+ `Payment Status: ${derivePaymentStatus(a)}`,
263
+ `Invoiced on: ${a.invoiced_on ?? 'N/A'}`,
264
+ `Pay on: ${a.pay_on ?? 'N/A'}`,
265
+ `Delivery on: ${a.delivery_on ?? 'N/A'}`,
266
+ `Paid on: ${a.paid_on ?? 'N/A'}`,
267
+ `Currency: ${a.currency ?? 'N/A'}`,
268
+ `Amount: ${formatAmount(a.amount)} ${a.currency ?? ''}`,
269
+ `Amount w/ tax: ${formatAmount(a.amount_with_tax)} ${a.currency ?? ''}`,
270
+ `Amount tax: ${formatAmount(a.amount_tax)} ${a.currency ?? ''}`,
271
+ `Amount paid: ${formatAmount(a.amount_paid)} ${a.currency ?? ''}`,
272
+ `Amount unpaid: ${formatAmount(a.amount_unpaid)} ${a.currency ?? ''}`,
273
+ `Note: ${a.note ?? 'N/A'}${exportUrl}`,
274
+ ``,
275
+ `Line Items (${lineItems.length}):`,
276
+ lineItemsText,
277
+ ].join('\n');
278
+ return { content: [{ type: 'text', text }] };
279
+ }
280
+ catch (error) {
281
+ throw toMcpError(error);
282
+ }
283
+ }
284
+ export const getInvoiceDefinition = {
285
+ name: 'get_invoice',
286
+ description: 'Get full details of a single invoice including line items. Use list_invoices to find the invoice_id.',
287
+ inputSchema: {
288
+ type: 'object',
289
+ required: ['invoice_id'],
290
+ properties: {
291
+ invoice_id: {
292
+ type: 'string',
293
+ description: 'The ID of the invoice to retrieve',
294
+ },
295
+ },
296
+ },
297
+ annotations: { title: 'Get invoice', readOnlyHint: true, openWorldHint: true },
298
+ };
299
+ // ---------------------------------------------------------------------------
300
+ // Tool 3: create_invoice
301
+ // ---------------------------------------------------------------------------
302
+ const createInvoiceSchema = z.object({
303
+ company_id: z.string(),
304
+ document_type_id: z.string().optional().describe('Auto-resolved if omitted'),
305
+ invoiced_on: z.string().optional(),
306
+ currency: z.string().default('EUR').optional(),
307
+ pay_on: z
308
+ .string()
309
+ .optional()
310
+ .describe('Due date YYYY-MM-DD. Auto-calculated from invoiced_on + payment_terms if omitted'),
311
+ delivery_on: z.string().optional(),
312
+ subject: z.string().optional(),
313
+ note: z.string().optional(),
314
+ footer: z.string().optional(),
315
+ payment_terms: z.coerce
316
+ .number()
317
+ .default(30)
318
+ .optional()
319
+ .describe('Payment terms in days (default: 30)'),
320
+ purchase_order_number: z.string().optional().describe('PO number for the invoice'),
321
+ subsidiary_id: z.string().optional().describe('Auto-resolved if omitted'),
322
+ });
323
+ /**
324
+ * Creates a new invoice in Productive.io.
325
+ *
326
+ * @param client - The Productive API client instance
327
+ * @param args - Invoice creation parameters matching createInvoiceSchema
328
+ * @returns Confirmation with the new invoice ID and next steps
329
+ */
330
+ export async function createInvoiceTool(client, args) {
331
+ try {
332
+ const params = createInvoiceSchema.parse(args || {});
333
+ const today = new Date().toISOString().slice(0, 10);
334
+ // Auto-resolve defaults (always needed for note/footer templates)
335
+ const needsDefaults = !params.document_type_id || !params.subsidiary_id || !params.note || !params.footer;
336
+ const defaults = needsDefaults ? await resolveInvoiceDefaults(client) : null;
337
+ const documentTypeId = params.document_type_id ?? defaults?.document_type_id;
338
+ const subsidiaryId = params.subsidiary_id ?? defaults?.subsidiary_id;
339
+ if (!documentTypeId) {
340
+ throw new McpError(ErrorCode.InvalidParams, 'Could not resolve document_type_id automatically. Pass it explicitly.');
341
+ }
342
+ const invoicedOn = params.invoiced_on ?? today;
343
+ const paymentTerms = params.payment_terms ?? 30;
344
+ // Auto-calculate pay_on from invoiced_on + payment_terms if not explicitly set
345
+ let payOn = params.pay_on;
346
+ if (!payOn) {
347
+ const d = new Date(invoicedOn);
348
+ d.setDate(d.getDate() + paymentTerms);
349
+ payOn = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
350
+ }
351
+ const data = {
352
+ data: {
353
+ type: 'invoices',
354
+ attributes: {
355
+ invoiced_on: invoicedOn,
356
+ currency: params.currency ?? 'EUR',
357
+ pay_on: payOn,
358
+ delivery_on: params.delivery_on ?? getLastMonthRange().date_to,
359
+ ...(params.subject !== undefined && { subject: params.subject }),
360
+ note: params.note ?? defaults?.note_template ?? undefined,
361
+ footer: params.footer ?? defaults?.footer_template ?? undefined,
362
+ payment_terms: paymentTerms,
363
+ ...(params.purchase_order_number !== undefined && {
364
+ purchase_order_number: params.purchase_order_number,
365
+ }),
366
+ },
367
+ relationships: {
368
+ company: { data: { id: params.company_id, type: 'companies' } },
369
+ document_type: {
370
+ data: { id: documentTypeId, type: 'document_types' },
371
+ },
372
+ ...(subsidiaryId && {
373
+ subsidiary: {
374
+ data: { id: subsidiaryId, type: 'subsidiaries' },
375
+ },
376
+ }),
377
+ },
378
+ },
379
+ };
380
+ const response = await client.createInvoice(data);
381
+ const id = response.data.id;
382
+ const number = response.data.attributes.number ?? 'N/A';
383
+ return {
384
+ content: [
385
+ {
386
+ type: 'text',
387
+ text: `Invoice created! Invoice ID: ${id} (Number: ${number})\n\nNext step: use generate_line_items with invoice_id="${id}" and your budget_ids to add line items.`,
388
+ },
389
+ ],
390
+ };
391
+ }
392
+ catch (error) {
393
+ throw toMcpError(error);
394
+ }
395
+ }
396
+ export const createInvoiceDefinition = {
397
+ name: 'create_invoice',
398
+ description: 'Create a new draft invoice. Only company_id is required — document_type_id, subsidiary_id, note, and footer are auto-resolved. Use list_company_budgets first to get budget details including PO number and payment terms, then pass them here. pay_on is auto-calculated from invoiced_on + payment_terms. After creation, use generate_line_items to add line items.',
399
+ inputSchema: {
400
+ type: 'object',
401
+ required: ['company_id'],
402
+ properties: {
403
+ company_id: {
404
+ type: 'string',
405
+ description: 'Company ID (use list_companies to find)',
406
+ },
407
+ document_type_id: {
408
+ type: 'string',
409
+ description: 'Document type ID (use list_document_types to find)',
410
+ },
411
+ invoiced_on: {
412
+ type: 'string',
413
+ description: 'Invoice date (YYYY-MM-DD, defaults to today)',
414
+ },
415
+ currency: {
416
+ type: 'string',
417
+ description: 'Currency code (default: "EUR")',
418
+ },
419
+ pay_on: {
420
+ type: 'string',
421
+ description: 'Payment due date (YYYY-MM-DD). Auto-calculated from invoiced_on + payment_terms if omitted',
422
+ },
423
+ delivery_on: {
424
+ type: 'string',
425
+ description: 'Delivery date (YYYY-MM-DD)',
426
+ },
427
+ subject: { type: 'string', description: 'Invoice subject/title' },
428
+ note: { type: 'string', description: 'Internal note' },
429
+ footer: { type: 'string', description: 'Invoice footer text' },
430
+ payment_terms: {
431
+ type: 'number',
432
+ description: 'Payment terms in days (use value from list_company_budgets, default: 30)',
433
+ },
434
+ purchase_order_number: {
435
+ type: 'string',
436
+ description: 'PO number (use value from list_company_budgets)',
437
+ },
438
+ subsidiary_id: {
439
+ type: 'string',
440
+ description: 'Subsidiary ID if applicable',
441
+ },
442
+ },
443
+ },
444
+ annotations: {
445
+ title: 'Create invoice',
446
+ readOnlyHint: false,
447
+ destructiveHint: false,
448
+ idempotentHint: false,
449
+ openWorldHint: true,
450
+ },
451
+ };
452
+ // ---------------------------------------------------------------------------
453
+ // Tool: update_invoice
454
+ // ---------------------------------------------------------------------------
455
+ const updateInvoiceSchema = z.object({
456
+ invoice_id: z.string().describe('Invoice ID'),
457
+ subject: z.string().optional(),
458
+ note: z.string().optional(),
459
+ footer: z.string().optional(),
460
+ invoiced_on: z.string().optional().describe('Invoice date YYYY-MM-DD'),
461
+ pay_on: z.string().optional().describe('Due date YYYY-MM-DD'),
462
+ delivery_on: z.string().optional().describe('Delivery date YYYY-MM-DD'),
463
+ currency: z.string().optional(),
464
+ payment_terms: z.coerce.number().optional().describe('Payment terms in days'),
465
+ number: z.string().optional().describe('Invoice number'),
466
+ purchase_order_number: z.string().optional(),
467
+ });
468
+ export async function updateInvoiceTool(client, args) {
469
+ try {
470
+ const { invoice_id, ...fields } = updateInvoiceSchema.parse(args);
471
+ const attributes = {};
472
+ for (const [key, value] of Object.entries(fields)) {
473
+ if (value !== undefined) {
474
+ attributes[key] = value;
475
+ }
476
+ }
477
+ if (Object.keys(attributes).length === 0) {
478
+ throw new McpError(ErrorCode.InvalidParams, 'No fields to update provided.');
479
+ }
480
+ const data = {
481
+ data: {
482
+ type: 'invoices',
483
+ id: invoice_id,
484
+ attributes: attributes,
485
+ },
486
+ };
487
+ const response = await client.updateInvoice(invoice_id, data);
488
+ const inv = response.data;
489
+ return {
490
+ content: [
491
+ {
492
+ type: 'text',
493
+ text: `Invoice ${invoice_id} updated.\n\nNumber: ${inv.attributes.number ?? 'N/A'}\nSubject: ${inv.attributes.subject ?? 'N/A'}\nState: ${deriveInvoiceState(inv.attributes)}`,
494
+ },
495
+ ],
496
+ };
497
+ }
498
+ catch (error) {
499
+ throw toMcpError(error);
500
+ }
501
+ }
502
+ export const updateInvoiceDefinition = {
503
+ name: 'update_invoice',
504
+ description: 'Update an invoice. Can change subject, note, footer, dates, payment terms, number, and PO number. Works on both draft and finalized invoices.',
505
+ inputSchema: {
506
+ type: 'object',
507
+ properties: {
508
+ invoice_id: { type: 'string', description: 'Invoice ID' },
509
+ subject: { type: 'string', description: 'Invoice subject' },
510
+ note: { type: 'string', description: 'Invoice note (supports HTML)' },
511
+ footer: { type: 'string', description: 'Invoice footer (supports HTML)' },
512
+ invoiced_on: { type: 'string', description: 'Invoice date YYYY-MM-DD' },
513
+ pay_on: { type: 'string', description: 'Due date YYYY-MM-DD' },
514
+ delivery_on: { type: 'string', description: 'Delivery date YYYY-MM-DD' },
515
+ currency: { type: 'string', description: 'Currency code' },
516
+ payment_terms: { type: 'number', description: 'Payment terms in days' },
517
+ number: { type: 'string', description: 'Invoice number' },
518
+ purchase_order_number: { type: 'string', description: 'PO number' },
519
+ },
520
+ required: ['invoice_id'],
521
+ },
522
+ annotations: {
523
+ title: 'Update invoice',
524
+ readOnlyHint: false,
525
+ destructiveHint: false,
526
+ idempotentHint: true,
527
+ openWorldHint: true,
528
+ },
529
+ };
530
+ // ---------------------------------------------------------------------------
531
+ // Tool 4: generate_line_items
532
+ // ---------------------------------------------------------------------------
533
+ const generateLineItemsSchema = z.object({
534
+ invoice_id: z.string(),
535
+ budget_ids: z.preprocess((val) => {
536
+ if (typeof val === 'string') {
537
+ try {
538
+ const parsed = JSON.parse(val);
539
+ return Array.isArray(parsed) ? parsed.map(String) : [val];
540
+ }
541
+ catch {
542
+ return [val];
543
+ }
544
+ }
545
+ return val;
546
+ }, z.array(z.string())),
547
+ tax_rate_id: z.string().optional().describe('Auto-resolved if omitted'),
548
+ display_format: z.string().default('{service}').optional(),
549
+ date_from: z.string().optional(),
550
+ date_to: z.string().optional(),
551
+ invoicing_by: z.enum(['service', 'budget']).default('service').optional(),
552
+ });
553
+ /**
554
+ * Generates line items for an invoice from uninvoiced time and expenses.
555
+ *
556
+ * @param client - The Productive API client instance
557
+ * @param args - Parameters matching generateLineItemsSchema
558
+ * @returns Summary of generated line items and next steps
559
+ */
560
+ export async function generateLineItemsTool(client, args) {
561
+ try {
562
+ const params = generateLineItemsSchema.parse(args || {});
563
+ const defaultRange = getLastMonthRange();
564
+ const dateFrom = params.date_from ?? defaultRange.date_from;
565
+ const dateTo = params.date_to ?? defaultRange.date_to;
566
+ // Auto-resolve tax_rate_id and locale if not provided
567
+ const defaults = !params.tax_rate_id ? await resolveInvoiceDefaults(client) : null;
568
+ const taxRateId = params.tax_rate_id ?? defaults?.tax_rate_id;
569
+ const locale = defaults?.locale ?? 'de';
570
+ if (!taxRateId) {
571
+ throw new McpError(ErrorCode.InvalidParams, 'Could not resolve tax_rate_id automatically. Pass it explicitly.');
572
+ }
573
+ const data = {
574
+ data: {
575
+ invoice_id: parseInt(params.invoice_id, 10),
576
+ budget_ids: params.budget_ids.map((id) => parseInt(id, 10)),
577
+ tax_rate_id: parseInt(taxRateId, 10),
578
+ invoicing_method: 'uninvoiced_time_and_expenses',
579
+ display_format: params.display_format ?? '{service}',
580
+ date_from: dateFrom,
581
+ date_to: dateTo,
582
+ invoicing_by: params.invoicing_by ?? 'service',
583
+ locale,
584
+ },
585
+ };
586
+ const response = await client.generateLineItems(data);
587
+ const count = Array.isArray(response.data) ? response.data.length : 0;
588
+ if (count === 0) {
589
+ return {
590
+ content: [
591
+ {
592
+ type: 'text',
593
+ text: `0 line items generated — no uninvoiced time found for period ${dateFrom} to ${dateTo}.\nInvoice ${params.invoice_id} is empty (draft). You may want to delete it with delete_invoice.`,
594
+ },
595
+ ],
596
+ };
597
+ }
598
+ return {
599
+ content: [
600
+ {
601
+ type: 'text',
602
+ text: `Generated ${count} line item(s) for invoice ${params.invoice_id}. Period: ${dateFrom} to ${dateTo}\n\nNext step: use get_invoice with invoice_id="${params.invoice_id}" to review the invoice, or finalize_invoice to finalize it.`,
603
+ },
604
+ ],
605
+ };
606
+ }
607
+ catch (error) {
608
+ throw toMcpError(error);
609
+ }
610
+ }
611
+ export const generateLineItemsDefinition = {
612
+ name: 'generate_line_items',
613
+ description: 'Generate line items from uninvoiced time and expenses for a given period. Defaults to last month. Use list_company_budgets for budget_ids. tax_rate_id is auto-resolved if omitted.',
614
+ inputSchema: {
615
+ type: 'object',
616
+ required: ['invoice_id', 'budget_ids'],
617
+ properties: {
618
+ invoice_id: {
619
+ type: 'string',
620
+ description: 'Invoice ID to add line items to (use create_invoice first)',
621
+ },
622
+ budget_ids: {
623
+ type: 'array',
624
+ items: { type: 'string' },
625
+ description: 'Array of budget/deal IDs to pull time from',
626
+ },
627
+ tax_rate_id: {
628
+ type: 'string',
629
+ description: 'Tax rate ID to apply (use list_tax_rates to find)',
630
+ },
631
+ display_format: {
632
+ type: 'string',
633
+ description: 'Display format template (default: "{service}")',
634
+ },
635
+ date_from: {
636
+ type: 'string',
637
+ description: 'Start date for time period (YYYY-MM-DD, defaults to first day of last month)',
638
+ },
639
+ date_to: {
640
+ type: 'string',
641
+ description: 'End date for time period (YYYY-MM-DD, defaults to last day of last month)',
642
+ },
643
+ invoicing_by: {
644
+ type: 'string',
645
+ enum: ['service', 'budget'],
646
+ description: 'Group line items by "service" or "budget" (default: "service")',
647
+ },
648
+ },
649
+ },
650
+ annotations: {
651
+ title: 'Generate invoice line items',
652
+ readOnlyHint: false,
653
+ destructiveHint: false,
654
+ idempotentHint: false,
655
+ openWorldHint: true,
656
+ },
657
+ };