@monadsag/productive-mcp 1.2.48 → 1.2.51

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.
package/README.md CHANGED
@@ -228,13 +228,14 @@ Productive's UI calls this resource a "folder"; the API models it as a "board" (
228
228
 
229
229
  ### Time Tracking
230
230
 
231
- | Tool | Description |
232
- | -------------------------------------------------------------------------------------- | -------------------------------- |
233
- | `list_time_entries` / `create_time_entry` / `update_time_entry` | Time entry CRUD |
234
- | `set_time_entry_approval` | Approval workflow (action param) |
235
- | `start_timer` / `stop_timer` / `get_timer` | Real-time timers |
236
- | `list_services` / `get_project_services` / `list_project_deals` / `list_deal_services` | Budget & service lookup |
237
- | `create_budget_service` / `update_budget_service` | Budget service (line item) CRUD |
231
+ | Tool | Description |
232
+ | ---------------------------------------------------------------------------------------------------- | -------------------------------- |
233
+ | `list_time_entries` / `create_time_entry` / `update_time_entry` | Time entry CRUD |
234
+ | `set_time_entry_approval` | Approval workflow (action param) |
235
+ | `start_timer` / `stop_timer` / `get_timer` | Real-time timers |
236
+ | `list_services` / `get_project_services` / `list_project_deals` / `list_deal_services` | Budget & service lookup |
237
+ | `create_budget_service` / `update_budget_service` | Budget service (line item) CRUD |
238
+ | `list_budget_sections` / `create_budget_section` / `update_budget_section` / `delete_budget_section` | Budget sections (service groups) |
238
239
 
239
240
  ### Invoicing
240
241
 
@@ -305,6 +306,11 @@ create_budget → create_budget_service → update_budget_service (optional)
305
306
 
306
307
  `unit_id` (1=Hour, 2=Piece, 3=Day) defaults to `1`; `billing_type_id` (1=Fixed, 2=Actuals, 3=None, 4=Percentage) defaults to `2`.
307
308
 
309
+ To group a budget's services, for example by project phase, create sections with
310
+ `create_budget_section` and pass `section_id` to `create_budget_service` or `update_budget_service`.
311
+ `list_budget_sections` shows each section with its services; `delete_budget_section` deletes only
312
+ an empty section. `section_id: "none"` on `update_budget_service` takes a service out of its section.
313
+
308
314
  ## npm package / MCP hub
309
315
 
310
316
  The stdio entry point is also published to npm as
@@ -447,6 +447,8 @@ export class ProductiveAPIClient {
447
447
  * @param params.deal_id - Filter by deal/budget ID
448
448
  * @param params.limit - Number of results per page
449
449
  * @param params.page - Page number for pagination
450
+ * @param params.include - Relationships to sideload, e.g. `section` to get each
451
+ * service's section id (without it the relationship is a stub)
450
452
  * @returns Promise resolving to paginated services response
451
453
  *
452
454
  * @example
@@ -459,6 +461,14 @@ export class ProductiveAPIClient {
459
461
  const queryParams = new URLSearchParams();
460
462
  // Filter by deal/budget
461
463
  queryParams.append('filter[deal_id]', params.deal_id);
464
+ if (params.include) {
465
+ queryParams.append('include', params.include);
466
+ }
467
+ // Per the spec, services of budgets without a project are only included
468
+ // when this is set.
469
+ if (params.projectless_budgets) {
470
+ queryParams.append('filter[projectless_budgets]', 'true');
471
+ }
462
472
  if (params.limit) {
463
473
  queryParams.append('page[size]', params.limit.toString());
464
474
  }
@@ -790,6 +800,57 @@ export class ProductiveAPIClient {
790
800
  async deleteService(id) {
791
801
  return this.makeVoidRequest(`services/${id}`, { method: 'DELETE' });
792
802
  }
803
+ /** One service with its `section` linkage sideloaded. */
804
+ async getServiceWithSection(id) {
805
+ return this.makeRequest(`services/${id}?include=section`);
806
+ }
807
+ /**
808
+ * One page of the sections of a deal/budget. `include=deal` carries each
809
+ * section's parent budget id, so a caller can check that the filter really
810
+ * narrowed the list.
811
+ */
812
+ async listSections(dealId, page = 1) {
813
+ const queryParams = new URLSearchParams();
814
+ queryParams.append('filter[deal_id]', dealId);
815
+ queryParams.append('include', 'deal');
816
+ queryParams.append('page[size]', '200');
817
+ queryParams.append('page[number]', page.toString());
818
+ return this.makeRequest(`sections?${queryParams.toString()}`);
819
+ }
820
+ /**
821
+ * One page of the services in a section, from any budget, with each one's
822
+ * `section` linkage sideloaded so the caller can check the filter's result.
823
+ * `projectless` adds `filter[projectless_budgets]=true`, without which the
824
+ * spec says services of budgets not linked to a project are left out.
825
+ */
826
+ async listServicesInSection(sectionId, page, projectless) {
827
+ const queryParams = new URLSearchParams();
828
+ queryParams.append('filter[section_id]', sectionId);
829
+ if (projectless)
830
+ queryParams.append('filter[projectless_budgets]', 'true');
831
+ queryParams.append('include', 'section');
832
+ queryParams.append('page[size]', '200');
833
+ queryParams.append('page[number]', page.toString());
834
+ return this.makeRequest(`services?${queryParams.toString()}`);
835
+ }
836
+ async getSection(id) {
837
+ return this.makeRequest(`sections/${id}?include=deal`);
838
+ }
839
+ async createSection(data) {
840
+ return this.makeRequest('sections', {
841
+ method: 'POST',
842
+ body: JSON.stringify(data),
843
+ });
844
+ }
845
+ async updateSection(id, data) {
846
+ return this.makeRequest(`sections/${id}`, {
847
+ method: 'PATCH',
848
+ body: JSON.stringify(data),
849
+ });
850
+ }
851
+ async deleteSection(id) {
852
+ return this.makeVoidRequest(`sections/${id}`, { method: 'DELETE' });
853
+ }
793
854
  async deleteInvoice(id) {
794
855
  // Was a hand-rolled fetch carrying its own copy of the error parsing.
795
856
  return this.makeVoidRequest(`invoices/${id}`, { method: 'DELETE' });
@@ -0,0 +1,382 @@
1
+ import { z } from 'zod';
2
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
3
+ import { collectPages, MAX_PAGE_SIZE } from '../api/invoice-time-entries.js';
4
+ import { toMcpError } from '../utils/errors.js';
5
+ import { toNumericId } from './tool-helpers.js';
6
+ // Ceiling for every sweep in this file (10 x 200 rows). Past it a list says it
7
+ // may be incomplete and a delete refuses.
8
+ const MAX_PAGES = 10;
9
+ const linkageSchema = z.object({
10
+ data: z.object({ id: z.union([z.string(), z.number()]).transform(String) }).nullable(),
11
+ meta: z.object({ included: z.boolean().optional() }).optional(),
12
+ });
13
+ export function readLinkage(relationship) {
14
+ const parsed = linkageSchema.safeParse(relationship);
15
+ if (!parsed.success || parsed.data.meta?.included === false)
16
+ return { kind: 'unknown' };
17
+ return parsed.data.data ? { kind: 'linked', id: parsed.data.data.id } : { kind: 'none' };
18
+ }
19
+ function sectionOf(service) {
20
+ return readLinkage(service.relationships?.section);
21
+ }
22
+ function isIn(service, sectionId) {
23
+ const link = sectionOf(service);
24
+ return link.kind === 'linked' && link.id === sectionId;
25
+ }
26
+ /**
27
+ * Why a sweep did not provably read every row, or null when it did. Neither
28
+ * /services nor /sections offers a unique sort key, so a row can slip across a
29
+ * page boundary without the deduplication noticing; only the total Productive
30
+ * reports proves the list complete.
31
+ */
32
+ function incompleteness(pages) {
33
+ if (pages.truncated)
34
+ return `more than ${MAX_PAGES * MAX_PAGE_SIZE} rows came back`;
35
+ if (pages.expected === undefined)
36
+ return 'Productive reported no total';
37
+ if (pages.rows.length !== pages.expected) {
38
+ return `${pages.rows.length} of ${pages.expected} reported rows were read`;
39
+ }
40
+ return null;
41
+ }
42
+ function sweep(fetchPage) {
43
+ return collectPages(fetchPage, MAX_PAGES, MAX_PAGE_SIZE);
44
+ }
45
+ /**
46
+ * Per the spec, /services leaves out the services of budgets that are not
47
+ * linked to a project unless `filter[projectless_budgets]=true` is set, and
48
+ * create_budget makes such budgets. Every service lookup therefore runs once
49
+ * without and once with the flag, merged by id: whether the flag adds those
50
+ * services or narrows the result to them, the union covers both.
51
+ */
52
+ async function sweepServices(fetchPage) {
53
+ const lookups = await Promise.all([false, true].map((projectless) => sweep((page) => fetchPage(page, projectless))));
54
+ const byId = new Map();
55
+ for (const lookup of lookups)
56
+ for (const row of lookup.rows)
57
+ byId.set(row.id, row);
58
+ const labels = ['plain lookup', 'lookup including budgets without a project'];
59
+ const gaps = lookups.flatMap((lookup, i) => {
60
+ const why = incompleteness(lookup);
61
+ return why === null ? [] : [`${labels[i]}: ${why}`];
62
+ });
63
+ return { rows: [...byId.values()], gaps };
64
+ }
65
+ /**
66
+ * Read a service back and check that Productive kept the requested section,
67
+ * or -- for `sectionId: null` -- that the service is in no section.
68
+ *
69
+ * The flat `section_id` attribute follows the spec and is not verified against
70
+ * the live API. An API that accepted the field and ignored it would otherwise
71
+ * report success for a service in the wrong section. Every failure here says
72
+ * that the write itself happened, so a create is not retried into a duplicate.
73
+ */
74
+ export async function confirmSection(client, serviceId, sectionId, action) {
75
+ const written = `Service ${serviceId} was ${action}`;
76
+ const duplicateWarning = action === 'created' ? ' The service exists, do not create it again.' : '';
77
+ const label = sectionId ?? 'none';
78
+ let linkage;
79
+ try {
80
+ linkage = sectionOf((await client.getServiceWithSection(serviceId)).data);
81
+ }
82
+ catch (error) {
83
+ const reason = error instanceof Error ? error.message : String(error);
84
+ throw new McpError(ErrorCode.InternalError, `${written}, but reading it back to check its section (${label}) failed (${reason}).${duplicateWarning}`);
85
+ }
86
+ const kept = sectionId === null
87
+ ? linkage.kind === 'none'
88
+ : linkage.kind === 'linked' && linkage.id === sectionId;
89
+ if (kept)
90
+ return `Section: ${label} (confirmed by reading the service back)`;
91
+ if (linkage.kind === 'unknown') {
92
+ return `Section: ${label} requested, but Productive did not report the assignment, so it is not confirmed`;
93
+ }
94
+ const actual = linkage.kind === 'linked' ? `section ${linkage.id}` : 'no section';
95
+ const intended = sectionId === null ? 'take it out of its section' : `put it into section ${sectionId}`;
96
+ throw new McpError(ErrorCode.InternalError, `${written}, but Productive did not ${intended} (it reports ${actual}).` +
97
+ `${duplicateWarning} Check the budget with list_budget_sections.`);
98
+ }
99
+ // ---------------------------------------------------------------------------
100
+ // Tool: list_budget_sections
101
+ // ---------------------------------------------------------------------------
102
+ const listBudgetSectionsSchema = z.object({
103
+ budget_id: z.string().min(1, 'Budget ID is required'),
104
+ });
105
+ /** Sections ordered as Productive positions them; unpositioned ones last, by id. */
106
+ function byPosition(a, b) {
107
+ const pa = a.attributes.position ?? Number.MAX_SAFE_INTEGER;
108
+ const pb = b.attributes.position ?? Number.MAX_SAFE_INTEGER;
109
+ return pa - pb || Number(a.id) - Number(b.id);
110
+ }
111
+ function serviceLines(services) {
112
+ return services.map((s) => ` - Service ${s.id}: ${s.attributes.name}`);
113
+ }
114
+ function countLabel(n) {
115
+ return n === 0 ? 'no services' : `${n} service${n === 1 ? '' : 's'}`;
116
+ }
117
+ function sectionHeading(section, members) {
118
+ const unreported = readLinkage(section.relationships?.deal).kind === 'linked' ? '' : ', budget not reported';
119
+ return `Section ${section.id}: ${section.attributes.name} (${countLabel(members)}${unreported})`;
120
+ }
121
+ function formatSectionList(budgetId, sections, services, notes) {
122
+ const lines = [
123
+ `Budget ${budgetId}: ${sections.length} section(s), ${services.length} service(s)`,
124
+ ];
125
+ for (const section of sections) {
126
+ const members = services.filter((s) => isIn(s, String(section.id)));
127
+ lines.push('', sectionHeading(section, members.length), ...serviceLines(members));
128
+ }
129
+ const known = new Set(sections.map((s) => String(s.id)));
130
+ const groups = [
131
+ ['Not in any section', (link) => link.kind === 'none'],
132
+ ['In a section not listed above', (link) => link.kind === 'linked' && !known.has(link.id)],
133
+ ['Section unknown (Productive did not report it)', (link) => link.kind === 'unknown'],
134
+ ];
135
+ for (const [label, matches] of groups) {
136
+ const members = services.filter((s) => matches(sectionOf(s)));
137
+ if (members.length > 0) {
138
+ lines.push('', `${label} (${countLabel(members.length)})`, ...serviceLines(members));
139
+ }
140
+ }
141
+ for (const note of notes)
142
+ lines.push('', note);
143
+ return lines.join('\n');
144
+ }
145
+ export async function listBudgetSectionsTool(client, args) {
146
+ try {
147
+ const { budget_id } = listBudgetSectionsSchema.parse(args);
148
+ const budgetId = String(toNumericId(budget_id, 'budget_id'));
149
+ const [sectionPages, services] = await Promise.all([
150
+ sweep((page) => client.listSections(budgetId, page)),
151
+ sweepServices((page, projectless) => client.listDealServices({
152
+ deal_id: budgetId,
153
+ include: 'section',
154
+ limit: MAX_PAGE_SIZE,
155
+ page,
156
+ projectless_budgets: projectless,
157
+ })),
158
+ ]);
159
+ // A filter can be accepted and still not narrow the result (CLAUDE.md,
160
+ // Gotchas), so sections that name a different budget are dropped here.
161
+ const sections = sectionPages.rows
162
+ .filter((s) => {
163
+ const deal = readLinkage(s.relationships?.deal);
164
+ return deal.kind !== 'linked' || deal.id === budgetId;
165
+ })
166
+ .sort(byPosition);
167
+ const notes = [];
168
+ const foreign = sectionPages.rows.length - sections.length;
169
+ if (foreign > 0)
170
+ notes.push(`Left out ${foreign} section(s) that belong to other budgets.`);
171
+ const sectionGap = incompleteness(sectionPages);
172
+ if (sectionGap)
173
+ notes.push(`The section list may be incomplete: ${sectionGap}.`);
174
+ if (services.gaps.length > 0) {
175
+ notes.push(`The service list may be incomplete: ${services.gaps.join('; ')}.`);
176
+ }
177
+ return {
178
+ content: [
179
+ { type: 'text', text: formatSectionList(budgetId, sections, services.rows, notes) },
180
+ ],
181
+ };
182
+ }
183
+ catch (error) {
184
+ throw toMcpError(error);
185
+ }
186
+ }
187
+ export const listBudgetSectionsDefinition = {
188
+ name: 'list_budget_sections',
189
+ description: 'List the sections of a budget (groups of services, e.g. project phases) together with the ' +
190
+ 'services in each section. Services that are in no section are listed separately. ' +
191
+ 'Use list_company_budgets or create_budget to get budget_id.',
192
+ inputSchema: {
193
+ type: 'object',
194
+ required: ['budget_id'],
195
+ properties: {
196
+ budget_id: { type: 'string', description: 'Budget ID' },
197
+ },
198
+ },
199
+ annotations: {
200
+ title: 'List budget sections',
201
+ readOnlyHint: true,
202
+ destructiveHint: false,
203
+ idempotentHint: true,
204
+ openWorldHint: true,
205
+ },
206
+ };
207
+ // ---------------------------------------------------------------------------
208
+ // Tool: create_budget_section
209
+ // ---------------------------------------------------------------------------
210
+ const createBudgetSectionSchema = z.object({
211
+ budget_id: z.string().min(1, 'Budget ID is required'),
212
+ name: z.string().trim().min(1, 'Name is required'),
213
+ });
214
+ export async function createBudgetSectionTool(client, args) {
215
+ try {
216
+ const { budget_id, name } = createBudgetSectionSchema.parse(args);
217
+ const budgetId = toNumericId(budget_id, 'budget_id');
218
+ const response = await client.createSection({
219
+ data: { type: 'sections', attributes: { name, deal_id: budgetId } },
220
+ });
221
+ const section = response.data;
222
+ return {
223
+ content: [
224
+ {
225
+ type: 'text',
226
+ text: `Section created! Section ID: ${section.id} (${section.attributes.name}) on budget ${budgetId}\n\n` +
227
+ `Next step: put services into it with create_budget_service or update_budget_service (section_id: ${section.id}).`,
228
+ },
229
+ ],
230
+ };
231
+ }
232
+ catch (error) {
233
+ throw toMcpError(error);
234
+ }
235
+ }
236
+ export const createBudgetSectionDefinition = {
237
+ name: 'create_budget_section',
238
+ description: "Create a section in a budget. A section groups the budget's services, e.g. by project " +
239
+ 'phase. Put services into it with the section_id parameter of create_budget_service or ' +
240
+ 'update_budget_service.',
241
+ inputSchema: {
242
+ type: 'object',
243
+ required: ['budget_id', 'name'],
244
+ properties: {
245
+ budget_id: { type: 'string', description: 'Budget ID to create the section in' },
246
+ name: { type: 'string', description: 'Section name' },
247
+ },
248
+ },
249
+ annotations: {
250
+ title: 'Create budget section',
251
+ readOnlyHint: false,
252
+ destructiveHint: false,
253
+ idempotentHint: false,
254
+ openWorldHint: true,
255
+ },
256
+ };
257
+ // ---------------------------------------------------------------------------
258
+ // Tool: update_budget_section
259
+ // ---------------------------------------------------------------------------
260
+ const updateBudgetSectionSchema = z.object({
261
+ section_id: z.string().min(1, 'Section ID is required'),
262
+ name: z.string().trim().min(1, 'Name is required'),
263
+ });
264
+ export async function updateBudgetSectionTool(client, args) {
265
+ try {
266
+ const { section_id, name } = updateBudgetSectionSchema.parse(args);
267
+ const sectionId = String(toNumericId(section_id, 'section_id'));
268
+ const response = await client.updateSection(sectionId, {
269
+ data: { type: 'sections', id: sectionId, attributes: { name } },
270
+ });
271
+ // The name Productive stored, not the one requested: if the rename did not
272
+ // take, the old name shows here.
273
+ return {
274
+ content: [
275
+ {
276
+ type: 'text',
277
+ text: `Section ${sectionId} renamed to "${response.data.attributes.name}".`,
278
+ },
279
+ ],
280
+ };
281
+ }
282
+ catch (error) {
283
+ throw toMcpError(error);
284
+ }
285
+ }
286
+ export const updateBudgetSectionDefinition = {
287
+ name: 'update_budget_section',
288
+ description: 'Rename a budget section. Use list_budget_sections to find section IDs.',
289
+ inputSchema: {
290
+ type: 'object',
291
+ required: ['section_id', 'name'],
292
+ properties: {
293
+ section_id: { type: 'string', description: 'Section ID' },
294
+ name: { type: 'string', description: 'New section name' },
295
+ },
296
+ },
297
+ annotations: {
298
+ title: 'Update budget section',
299
+ readOnlyHint: false,
300
+ destructiveHint: false,
301
+ idempotentHint: true,
302
+ openWorldHint: true,
303
+ },
304
+ };
305
+ // ---------------------------------------------------------------------------
306
+ // Tool: delete_budget_section
307
+ // ---------------------------------------------------------------------------
308
+ const deleteBudgetSectionSchema = z.object({
309
+ section_id: z.string().min(1, 'Section ID is required'),
310
+ });
311
+ /**
312
+ * Refuse unless the section is provably empty. What Productive does with the
313
+ * services of a deleted section is not documented, so "probably empty" is not
314
+ * enough. Services are looked up by section rather than by budget, which also
315
+ * catches a service of another budget sitting in this section; if Productive
316
+ * ignored the section filter, more services come back rather than fewer, and
317
+ * the check only gets stricter.
318
+ */
319
+ async function assertSectionEmpty(client, section, sectionId) {
320
+ const services = await sweepServices((page, projectless) => client.listServicesInSection(sectionId, page, projectless));
321
+ const unknown = services.rows.filter((s) => sectionOf(s).kind === 'unknown');
322
+ const reasons = [...services.gaps];
323
+ if (unknown.length > 0) {
324
+ reasons.push(`Productive did not report the section of ${countLabel(unknown.length)}`);
325
+ }
326
+ if (reasons.length > 0) {
327
+ throw new McpError(ErrorCode.InternalError, `Cannot confirm that section ${sectionId} is empty (${reasons.join('; ')}). Nothing was deleted.`);
328
+ }
329
+ // Rows the filter returned whose own link names no section or another one
330
+ // are not counted: an ignored filter returns exactly such rows. Only a filter
331
+ // and a link that contradict each other could hide a service here.
332
+ const inside = services.rows.filter((s) => isIn(s, sectionId));
333
+ if (inside.length > 0) {
334
+ throw new McpError(ErrorCode.InvalidParams, `Section ${sectionId} (${section.attributes.name}) still contains ${countLabel(inside.length)}:\n` +
335
+ `${serviceLines(inside).join('\n')}\n` +
336
+ 'Move them to another section, or take them out with section_id "none", using ' +
337
+ 'update_budget_service first. Nothing was deleted.');
338
+ }
339
+ }
340
+ export async function deleteBudgetSectionTool(client, args) {
341
+ try {
342
+ const { section_id } = deleteBudgetSectionSchema.parse(args);
343
+ const sectionId = String(toNumericId(section_id, 'section_id'));
344
+ const section = (await client.getSection(sectionId)).data;
345
+ if (section.type !== 'sections' || String(section.id) !== sectionId) {
346
+ throw new McpError(ErrorCode.InternalError, `Productive did not return section ${sectionId}. Nothing was deleted.`);
347
+ }
348
+ await assertSectionEmpty(client, section, sectionId);
349
+ await client.deleteSection(sectionId);
350
+ const budget = readLinkage(section.relationships?.deal);
351
+ const from = budget.kind === 'linked' ? ` from budget ${budget.id}` : '';
352
+ return {
353
+ content: [
354
+ { type: 'text', text: `Section ${sectionId} (${section.attributes.name}) deleted${from}.` },
355
+ ],
356
+ };
357
+ }
358
+ catch (error) {
359
+ throw toMcpError(error);
360
+ }
361
+ }
362
+ export const deleteBudgetSectionDefinition = {
363
+ name: 'delete_budget_section',
364
+ description: 'Delete a budget section. Only an empty section can be deleted: while any service is still ' +
365
+ 'in it, the call is refused and names the services; move them to another section, or take ' +
366
+ 'them out with section_id "none", using update_budget_service first. It is also refused ' +
367
+ "when Productive's answer does not prove the section empty. Cannot be undone.",
368
+ inputSchema: {
369
+ type: 'object',
370
+ required: ['section_id'],
371
+ properties: {
372
+ section_id: { type: 'string', description: 'Section ID' },
373
+ },
374
+ },
375
+ annotations: {
376
+ title: 'Delete budget section',
377
+ readOnlyHint: false,
378
+ destructiveHint: true,
379
+ idempotentHint: true,
380
+ openWorldHint: true,
381
+ },
382
+ };
@@ -1,6 +1,8 @@
1
1
  import { z } from 'zod';
2
2
  import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
3
3
  import { toMcpError } from '../utils/errors.js';
4
+ import { toNumericId } from './tool-helpers.js';
5
+ import { confirmSection } from './budget-sections.js';
4
6
  // ---------------------------------------------------------------------------
5
7
  // Tool: create_budget_service
6
8
  // ---------------------------------------------------------------------------
@@ -13,10 +15,28 @@ const createBudgetServiceSchema = z.object({
13
15
  price: z.coerce.number().optional(),
14
16
  quantity: z.coerce.number().optional(),
15
17
  budgeted_time: z.coerce.number().optional(),
18
+ section_id: z.string().min(1).optional(),
16
19
  });
20
+ const SECTION_HINT = 'Use a section of the same budget (from list_budget_sections or create_budget_section). ' +
21
+ 'The service is read back to confirm the assignment.';
22
+ const createSectionIdProperty = {
23
+ type: 'string',
24
+ description: `Section to put the service into. ${SECTION_HINT}`,
25
+ };
26
+ const updateSectionIdProperty = {
27
+ type: 'string',
28
+ description: `Section to put the service into, or "none" to take it out of its section. ${SECTION_HINT}`,
29
+ };
30
+ /** `"none"` takes a service out of its section, sent as `section_id: null`. */
31
+ function sectionChoice(value) {
32
+ if (value === undefined)
33
+ return undefined;
34
+ return value.trim().toLowerCase() === 'none' ? null : toNumericId(value, 'section_id');
35
+ }
17
36
  export async function createBudgetServiceTool(client, args) {
18
37
  try {
19
38
  const params = createBudgetServiceSchema.parse(args);
39
+ const sectionId = params.section_id === undefined ? undefined : toNumericId(params.section_id, 'section_id');
20
40
  const data = {
21
41
  data: {
22
42
  type: 'services',
@@ -28,6 +48,7 @@ export async function createBudgetServiceTool(client, args) {
28
48
  ...(params.price !== undefined && { price: params.price }),
29
49
  ...(params.quantity !== undefined && { quantity: params.quantity }),
30
50
  ...(params.budgeted_time !== undefined && { budgeted_time: params.budgeted_time }),
51
+ ...(sectionId !== undefined && { section_id: sectionId }),
31
52
  },
32
53
  relationships: {
33
54
  deal: { data: { id: params.budget_id, type: 'deals' } },
@@ -37,11 +58,14 @@ export async function createBudgetServiceTool(client, args) {
37
58
  const response = await client.createService(data);
38
59
  const id = response.data.id;
39
60
  const serviceName = response.data.attributes.name;
61
+ const sectionNote = sectionId === undefined
62
+ ? ''
63
+ : `\n${await confirmSection(client, id, String(sectionId), 'created')}`;
40
64
  return {
41
65
  content: [
42
66
  {
43
67
  type: 'text',
44
- text: `Service created! Service ID: ${id} (${serviceName}) on budget ${params.budget_id}\n\n` +
68
+ text: `Service created! Service ID: ${id} (${serviceName}) on budget ${params.budget_id}${sectionNote}\n\n` +
45
69
  'Next step: use update_budget_service to adjust fields, or list_deal_services to verify.',
46
70
  },
47
71
  ],
@@ -77,6 +101,7 @@ export const createBudgetServiceDefinition = {
77
101
  price: { type: 'number', description: 'Unit price' },
78
102
  quantity: { type: 'number', description: 'Number of units (hours/days/pieces)' },
79
103
  budgeted_time: { type: 'number', description: 'Allocated hours for this service' },
104
+ section_id: createSectionIdProperty,
80
105
  },
81
106
  },
82
107
  annotations: {
@@ -99,16 +124,21 @@ const updateBudgetServiceSchema = z.object({
99
124
  unit_id: z.coerce.number().optional(),
100
125
  billing_type_id: z.coerce.number().optional(),
101
126
  budgeted_time: z.coerce.number().optional(),
127
+ section_id: z.string().min(1).optional(),
102
128
  });
103
129
  export async function updateBudgetServiceTool(client, args) {
104
130
  try {
105
- const { service_id, ...fields } = updateBudgetServiceSchema.parse(args);
131
+ const { service_id, section_id, ...fields } = updateBudgetServiceSchema.parse(args);
106
132
  const attributes = {};
107
133
  for (const [key, value] of Object.entries(fields)) {
108
134
  if (value !== undefined) {
109
135
  attributes[key] = value;
110
136
  }
111
137
  }
138
+ const sectionId = sectionChoice(section_id);
139
+ if (sectionId !== undefined) {
140
+ attributes.section_id = sectionId;
141
+ }
112
142
  if (Object.keys(attributes).length === 0) {
113
143
  throw new McpError(ErrorCode.InvalidParams, 'No fields to update provided.');
114
144
  }
@@ -121,11 +151,15 @@ export async function updateBudgetServiceTool(client, args) {
121
151
  };
122
152
  const response = await client.updateService(service_id, data);
123
153
  const service = response.data;
154
+ const expected = sectionId === null ? null : String(sectionId);
155
+ const sectionNote = sectionId === undefined
156
+ ? ''
157
+ : `\n${await confirmSection(client, service_id, expected, 'updated')}`;
124
158
  return {
125
159
  content: [
126
160
  {
127
161
  type: 'text',
128
- text: `Service ${service_id} updated.\n\nName: ${service.attributes.name}\nPrice: ${service.attributes.price ?? 'N/A'}\nQuantity: ${service.attributes.quantity ?? 'N/A'}`,
162
+ text: `Service ${service_id} updated.\n\nName: ${service.attributes.name}\nPrice: ${service.attributes.price ?? 'N/A'}\nQuantity: ${service.attributes.quantity ?? 'N/A'}${sectionNote}`,
129
163
  },
130
164
  ],
131
165
  };
@@ -137,7 +171,8 @@ export async function updateBudgetServiceTool(client, args) {
137
171
  export const updateBudgetServiceDefinition = {
138
172
  name: 'update_budget_service',
139
173
  description: 'Update a budget service (line item). Can change name, description, price, quantity, ' +
140
- 'unit_id, billing_type_id, and budgeted_time. Cannot move the service to a different budget.',
174
+ 'unit_id, billing_type_id, budgeted_time and the section (section_id, or "none" to take ' +
175
+ 'the service out of its section). Cannot move the service to a different budget.',
141
176
  inputSchema: {
142
177
  type: 'object',
143
178
  required: ['service_id'],
@@ -156,6 +191,7 @@ export const updateBudgetServiceDefinition = {
156
191
  description: 'Billing type: 1 = Fixed, 2 = Actuals, 3 = None, 4 = Percentage',
157
192
  },
158
193
  budgeted_time: { type: 'number', description: 'Allocated hours for this service' },
194
+ section_id: updateSectionIdProperty,
159
195
  },
160
196
  },
161
197
  annotations: {
@@ -32,6 +32,7 @@ import { listPageChildrenTool, listPageChildrenDefinition } from './page-childre
32
32
  import { listTaskDependenciesTool, listTaskDependenciesDefinition, getTaskDependencyTool, getTaskDependencyDefinition, createTaskDependencyTool, createTaskDependencyDefinition, deleteTaskDependencyTool, deleteTaskDependencyDefinition, } from './task-dependencies.js';
33
33
  import { createBudgetTool, createBudgetDefinition, updateBudgetTool, updateBudgetDefinition, createBudgetFromDealTool, createBudgetFromDealDefinition, } from './budgets.js';
34
34
  import { createBudgetServiceTool, createBudgetServiceDefinition, updateBudgetServiceTool, updateBudgetServiceDefinition, } from './budget-services.js';
35
+ import { listBudgetSectionsTool, listBudgetSectionsDefinition, createBudgetSectionTool, createBudgetSectionDefinition, updateBudgetSectionTool, updateBudgetSectionDefinition, deleteBudgetSectionTool, deleteBudgetSectionDefinition, } from './budget-sections.js';
35
36
  import { listPeopleTool, listPeopleDefinition, getPersonTool, getPersonDefinition, } from './people.js';
36
37
  import { listAbsenceTypesTool, listAbsenceTypesDefinition, createAbsenceTool, createAbsenceDefinition, listAbsencesTool, listAbsencesDefinition, } from './absences.js';
37
38
  import { createBookingTool, createBookingDefinition, updateBookingTool, updateBookingDefinition, deleteBookingTool, deleteBookingDefinition, listBookingsTool, listBookingsDefinition, } from './bookings.js';
@@ -72,6 +73,10 @@ export function getToolDefinitions(enabledToolNames) {
72
73
  getProjectServicesDefinition,
73
74
  createBudgetServiceDefinition,
74
75
  updateBudgetServiceDefinition,
76
+ listBudgetSectionsDefinition,
77
+ createBudgetSectionDefinition,
78
+ updateBudgetSectionDefinition,
79
+ deleteBudgetSectionDefinition,
75
80
  updateTimeEntryDefinition,
76
81
  deleteTimeEntryDefinition,
77
82
  setTimeEntryApprovalDefinition,
@@ -227,6 +232,14 @@ export async function handleToolCall(name, args, apiClient, config, enabledToolN
227
232
  return await createBudgetServiceTool(apiClient, args);
228
233
  case 'update_budget_service':
229
234
  return await updateBudgetServiceTool(apiClient, args);
235
+ case 'list_budget_sections':
236
+ return await listBudgetSectionsTool(apiClient, args);
237
+ case 'create_budget_section':
238
+ return await createBudgetSectionTool(apiClient, args);
239
+ case 'update_budget_section':
240
+ return await updateBudgetSectionTool(apiClient, args);
241
+ case 'delete_budget_section':
242
+ return await deleteBudgetSectionTool(apiClient, args);
230
243
  case 'update_time_entry':
231
244
  return await updateTimeEntryTool(apiClient, args);
232
245
  case 'delete_time_entry':
@@ -104,10 +104,12 @@ export function rethrowToolError(error) {
104
104
  * `Number('abc')` is NaN and JSON.stringify writes that as `null`, so a
105
105
  * mistyped ID would reach the API as a missing field and come back as a
106
106
  * confusing 422 about the person. Reject it here, where the field name is known.
107
+ * Digits beyond `Number.MAX_SAFE_INTEGER` are rejected too: they would round to
108
+ * a different ID, and the section tools also use the result in request paths.
107
109
  */
108
110
  export function toNumericId(value, field) {
109
111
  const trimmed = value.trim();
110
- if (!/^\d+$/.test(trimmed)) {
112
+ if (!/^\d+$/.test(trimmed) || !Number.isSafeInteger(Number(trimmed))) {
111
113
  throw new McpError(ErrorCode.InvalidParams, `${field} must be a numeric Productive ID, got "${value}".`);
112
114
  }
113
115
  return Number(trimmed);
@@ -64,6 +64,10 @@ export const TOOLSETS = {
64
64
  'get_project_services',
65
65
  'create_budget_service',
66
66
  'update_budget_service',
67
+ 'list_budget_sections',
68
+ 'create_budget_section',
69
+ 'update_budget_section',
70
+ 'delete_budget_section',
67
71
  'update_time_entry',
68
72
  'delete_time_entry',
69
73
  'set_time_entry_approval',
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@monadsag/productive-mcp",
3
- "version": "1.2.48",
3
+ "version": "1.2.51",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@monadsag/productive-mcp",
9
- "version": "1.2.48",
9
+ "version": "1.2.51",
10
10
  "license": "Apache-2.0",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "^1.13.2",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monadsag/productive-mcp",
3
- "version": "1.2.48",
3
+ "version": "1.2.51",
4
4
  "type": "module",
5
5
  "main": "./build/index.js",
6
6
  "bin": {