@monadsag/productive-mcp 1.2.48 → 1.2.53

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.
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,361 @@
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
+ // Tool: list_budget_sections
67
+ // ---------------------------------------------------------------------------
68
+ const listBudgetSectionsSchema = z.object({
69
+ budget_id: z.string().min(1, 'Budget ID is required'),
70
+ });
71
+ /** Sections ordered as Productive positions them; unpositioned ones last, by id. */
72
+ function byPosition(a, b) {
73
+ const pa = a.attributes.position ?? Number.MAX_SAFE_INTEGER;
74
+ const pb = b.attributes.position ?? Number.MAX_SAFE_INTEGER;
75
+ return pa - pb || Number(a.id) - Number(b.id);
76
+ }
77
+ function serviceLines(services) {
78
+ return services.map((s) => ` - Service ${s.id}: ${s.attributes.name}`);
79
+ }
80
+ function countLabel(n) {
81
+ return n === 0 ? 'no services' : `${n} service${n === 1 ? '' : 's'}`;
82
+ }
83
+ /**
84
+ * A section's name, or null when it has none: Productive keeps sections with
85
+ * an empty name (seen live), and a blank in the output reads like a bug.
86
+ */
87
+ function nameOf(section) {
88
+ return section.attributes.name?.trim() ? section.attributes.name : null;
89
+ }
90
+ function sectionHeading(section, members) {
91
+ const unreported = readLinkage(section.relationships?.deal).kind === 'linked' ? '' : ', budget not reported';
92
+ const details = `${countLabel(members)}${unreported}`;
93
+ const name = nameOf(section);
94
+ return name === null
95
+ ? `Section ${section.id} (unnamed, ${details})`
96
+ : `Section ${section.id}: ${name} (${details})`;
97
+ }
98
+ function formatSectionList(budgetId, sections, services, notes) {
99
+ const lines = [
100
+ `Budget ${budgetId}: ${sections.length} section(s), ${services.length} service(s)`,
101
+ ];
102
+ for (const section of sections) {
103
+ const members = services.filter((s) => isIn(s, String(section.id)));
104
+ lines.push('', sectionHeading(section, members.length), ...serviceLines(members));
105
+ }
106
+ const known = new Set(sections.map((s) => String(s.id)));
107
+ const groups = [
108
+ ['Not in any section', (link) => link.kind === 'none'],
109
+ ['In a section not listed above', (link) => link.kind === 'linked' && !known.has(link.id)],
110
+ ['Section unknown (Productive did not report it)', (link) => link.kind === 'unknown'],
111
+ ];
112
+ for (const [label, matches] of groups) {
113
+ const members = services.filter((s) => matches(sectionOf(s)));
114
+ if (members.length > 0) {
115
+ lines.push('', `${label} (${countLabel(members.length)})`, ...serviceLines(members));
116
+ }
117
+ }
118
+ for (const note of notes)
119
+ lines.push('', note);
120
+ return lines.join('\n');
121
+ }
122
+ export async function listBudgetSectionsTool(client, args) {
123
+ try {
124
+ const { budget_id } = listBudgetSectionsSchema.parse(args);
125
+ const budgetId = String(toNumericId(budget_id, 'budget_id'));
126
+ const [sectionPages, services] = await Promise.all([
127
+ sweep((page) => client.listSections(budgetId, page)),
128
+ sweepServices((page, projectless) => client.listDealServices({
129
+ deal_id: budgetId,
130
+ include: 'section',
131
+ limit: MAX_PAGE_SIZE,
132
+ page,
133
+ projectless_budgets: projectless,
134
+ })),
135
+ ]);
136
+ // A filter can be accepted and still not narrow the result (CLAUDE.md,
137
+ // Gotchas), so sections that name a different budget are dropped here.
138
+ const sections = sectionPages.rows
139
+ .filter((s) => {
140
+ const deal = readLinkage(s.relationships?.deal);
141
+ return deal.kind !== 'linked' || deal.id === budgetId;
142
+ })
143
+ .sort(byPosition);
144
+ const notes = [];
145
+ const foreign = sectionPages.rows.length - sections.length;
146
+ if (foreign > 0)
147
+ notes.push(`Left out ${foreign} section(s) that belong to other budgets.`);
148
+ const sectionGap = incompleteness(sectionPages);
149
+ if (sectionGap)
150
+ notes.push(`The section list may be incomplete: ${sectionGap}.`);
151
+ if (services.gaps.length > 0) {
152
+ notes.push(`The service list may be incomplete: ${services.gaps.join('; ')}.`);
153
+ }
154
+ return {
155
+ content: [
156
+ { type: 'text', text: formatSectionList(budgetId, sections, services.rows, notes) },
157
+ ],
158
+ };
159
+ }
160
+ catch (error) {
161
+ throw toMcpError(error);
162
+ }
163
+ }
164
+ export const listBudgetSectionsDefinition = {
165
+ name: 'list_budget_sections',
166
+ description: 'List the sections of a budget (groups of services, e.g. project phases) together with the ' +
167
+ 'services in each section. Services that are in no section are listed separately. ' +
168
+ 'Use list_company_budgets or create_budget to get budget_id.',
169
+ inputSchema: {
170
+ type: 'object',
171
+ required: ['budget_id'],
172
+ properties: {
173
+ budget_id: { type: 'string', description: 'Budget ID' },
174
+ },
175
+ },
176
+ annotations: {
177
+ title: 'List budget sections',
178
+ readOnlyHint: true,
179
+ destructiveHint: false,
180
+ idempotentHint: true,
181
+ openWorldHint: true,
182
+ },
183
+ };
184
+ // ---------------------------------------------------------------------------
185
+ // Tool: create_budget_section
186
+ // ---------------------------------------------------------------------------
187
+ const createBudgetSectionSchema = z.object({
188
+ budget_id: z.string().min(1, 'Budget ID is required'),
189
+ name: z.string().trim().min(1, 'Name is required'),
190
+ });
191
+ export async function createBudgetSectionTool(client, args) {
192
+ try {
193
+ const { budget_id, name } = createBudgetSectionSchema.parse(args);
194
+ const budgetId = toNumericId(budget_id, 'budget_id');
195
+ const response = await client.createSection({
196
+ data: { type: 'sections', attributes: { name, deal_id: budgetId } },
197
+ });
198
+ const section = response.data;
199
+ return {
200
+ content: [
201
+ {
202
+ type: 'text',
203
+ text: `Section created! Section ID: ${section.id} (${section.attributes.name}) on budget ${budgetId}\n\n` +
204
+ `Next step: put services into it with create_budget_service or update_budget_service (section_id: ${section.id}).`,
205
+ },
206
+ ],
207
+ };
208
+ }
209
+ catch (error) {
210
+ throw toMcpError(error);
211
+ }
212
+ }
213
+ export const createBudgetSectionDefinition = {
214
+ name: 'create_budget_section',
215
+ description: "Create a section in a budget. A section groups the budget's services, e.g. by project " +
216
+ 'phase. Put services into it with the section_id parameter of create_budget_service or ' +
217
+ 'update_budget_service.',
218
+ inputSchema: {
219
+ type: 'object',
220
+ required: ['budget_id', 'name'],
221
+ properties: {
222
+ budget_id: { type: 'string', description: 'Budget ID to create the section in' },
223
+ name: { type: 'string', description: 'Section name' },
224
+ },
225
+ },
226
+ annotations: {
227
+ title: 'Create budget section',
228
+ readOnlyHint: false,
229
+ destructiveHint: false,
230
+ idempotentHint: false,
231
+ openWorldHint: true,
232
+ },
233
+ };
234
+ // ---------------------------------------------------------------------------
235
+ // Tool: update_budget_section
236
+ // ---------------------------------------------------------------------------
237
+ const updateBudgetSectionSchema = z.object({
238
+ section_id: z.string().min(1, 'Section ID is required'),
239
+ name: z.string().trim().min(1, 'Name is required'),
240
+ });
241
+ export async function updateBudgetSectionTool(client, args) {
242
+ try {
243
+ const { section_id, name } = updateBudgetSectionSchema.parse(args);
244
+ const sectionId = String(toNumericId(section_id, 'section_id'));
245
+ const response = await client.updateSection(sectionId, {
246
+ data: { type: 'sections', id: sectionId, attributes: { name } },
247
+ });
248
+ // The name Productive stored, not the one requested: if the rename did not
249
+ // take, the old name shows here.
250
+ return {
251
+ content: [
252
+ {
253
+ type: 'text',
254
+ text: `Section ${sectionId} renamed to "${response.data.attributes.name}".`,
255
+ },
256
+ ],
257
+ };
258
+ }
259
+ catch (error) {
260
+ throw toMcpError(error);
261
+ }
262
+ }
263
+ export const updateBudgetSectionDefinition = {
264
+ name: 'update_budget_section',
265
+ description: 'Rename a budget section. Use list_budget_sections to find section IDs.',
266
+ inputSchema: {
267
+ type: 'object',
268
+ required: ['section_id', 'name'],
269
+ properties: {
270
+ section_id: { type: 'string', description: 'Section ID' },
271
+ name: { type: 'string', description: 'New section name' },
272
+ },
273
+ },
274
+ annotations: {
275
+ title: 'Update budget section',
276
+ readOnlyHint: false,
277
+ destructiveHint: false,
278
+ idempotentHint: true,
279
+ openWorldHint: true,
280
+ },
281
+ };
282
+ // ---------------------------------------------------------------------------
283
+ // Tool: delete_budget_section
284
+ // ---------------------------------------------------------------------------
285
+ const deleteBudgetSectionSchema = z.object({
286
+ section_id: z.string().min(1, 'Section ID is required'),
287
+ });
288
+ /**
289
+ * Refuse unless the section is provably empty. What Productive does with the
290
+ * services of a deleted section is not documented, so "probably empty" is not
291
+ * enough. Services are looked up by section rather than by budget, which also
292
+ * catches a service of another budget sitting in this section; if Productive
293
+ * ignored the section filter, more services come back rather than fewer, and
294
+ * the check only gets stricter.
295
+ */
296
+ async function assertSectionEmpty(client, section, sectionId) {
297
+ const services = await sweepServices((page, projectless) => client.listServicesInSection(sectionId, page, projectless));
298
+ const unknown = services.rows.filter((s) => sectionOf(s).kind === 'unknown');
299
+ const reasons = [...services.gaps];
300
+ if (unknown.length > 0) {
301
+ reasons.push(`Productive did not report the section of ${countLabel(unknown.length)}`);
302
+ }
303
+ if (reasons.length > 0) {
304
+ throw new McpError(ErrorCode.InternalError, `Cannot confirm that section ${sectionId} is empty (${reasons.join('; ')}). Nothing was deleted.`);
305
+ }
306
+ // Rows the filter returned whose own link names no section or another one
307
+ // are not counted: an ignored filter returns exactly such rows. Only a filter
308
+ // and a link that contradict each other could hide a service here.
309
+ const inside = services.rows.filter((s) => isIn(s, sectionId));
310
+ if (inside.length > 0) {
311
+ throw new McpError(ErrorCode.InvalidParams, `Section ${sectionId} (${nameOf(section) ?? 'unnamed'}) still contains ${countLabel(inside.length)}:\n` +
312
+ `${serviceLines(inside).join('\n')}\n` +
313
+ 'Move them to another section with update_budget_service first. Nothing was deleted.');
314
+ }
315
+ }
316
+ export async function deleteBudgetSectionTool(client, args) {
317
+ try {
318
+ const { section_id } = deleteBudgetSectionSchema.parse(args);
319
+ const sectionId = String(toNumericId(section_id, 'section_id'));
320
+ const section = (await client.getSection(sectionId)).data;
321
+ if (section.type !== 'sections' || String(section.id) !== sectionId) {
322
+ throw new McpError(ErrorCode.InternalError, `Productive did not return section ${sectionId}. Nothing was deleted.`);
323
+ }
324
+ await assertSectionEmpty(client, section, sectionId);
325
+ await client.deleteSection(sectionId);
326
+ const budget = readLinkage(section.relationships?.deal);
327
+ const from = budget.kind === 'linked' ? ` from budget ${budget.id}` : '';
328
+ return {
329
+ content: [
330
+ {
331
+ type: 'text',
332
+ text: `Section ${sectionId} (${nameOf(section) ?? 'unnamed'}) deleted${from}.`,
333
+ },
334
+ ],
335
+ };
336
+ }
337
+ catch (error) {
338
+ throw toMcpError(error);
339
+ }
340
+ }
341
+ export const deleteBudgetSectionDefinition = {
342
+ name: 'delete_budget_section',
343
+ description: 'Delete a budget section. Only an empty section can be deleted: while any service is still ' +
344
+ 'in it, the call is refused and names the services; move them to another section with ' +
345
+ 'update_budget_service first. It is also refused ' +
346
+ "when Productive's answer does not prove the section empty. Cannot be undone.",
347
+ inputSchema: {
348
+ type: 'object',
349
+ required: ['section_id'],
350
+ properties: {
351
+ section_id: { type: 'string', description: 'Section ID' },
352
+ },
353
+ },
354
+ annotations: {
355
+ title: 'Delete budget section',
356
+ readOnlyHint: false,
357
+ destructiveHint: true,
358
+ idempotentHint: true,
359
+ openWorldHint: true,
360
+ },
361
+ };
@@ -1,6 +1,38 @@
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 { readLinkage } from './budget-sections.js';
6
+ /**
7
+ * Read a service back and check that Productive kept the requested section.
8
+ *
9
+ * Setting the section through the flat `section_id` attribute is verified live;
10
+ * the read-back stays because a field that is accepted and then ignored would
11
+ * otherwise report success for a service in the wrong section. Every failure
12
+ * here says that the write itself happened, so a create is not retried into a
13
+ * duplicate.
14
+ */
15
+ async function confirmSection(client, serviceId, sectionId, action) {
16
+ const written = `Service ${serviceId} was ${action}`;
17
+ const duplicateWarning = action === 'created' ? ' The service exists, do not create it again.' : '';
18
+ let linkage;
19
+ try {
20
+ linkage = readLinkage((await client.getServiceWithSection(serviceId)).data.relationships?.section);
21
+ }
22
+ catch (error) {
23
+ const reason = error instanceof Error ? error.message : String(error);
24
+ throw new McpError(ErrorCode.InternalError, `${written}, but reading it back to check its section (${sectionId}) failed (${reason}).${duplicateWarning}`);
25
+ }
26
+ if (linkage.kind === 'linked' && linkage.id === sectionId) {
27
+ return `Section: ${sectionId} (confirmed by reading the service back)`;
28
+ }
29
+ if (linkage.kind === 'unknown') {
30
+ return `Section: ${sectionId} requested, but Productive did not report the assignment, so it is not confirmed`;
31
+ }
32
+ const actual = linkage.kind === 'linked' ? `section ${linkage.id}` : 'no section';
33
+ throw new McpError(ErrorCode.InternalError, `${written}, but Productive did not put it into section ${sectionId} (it reports ${actual}).` +
34
+ `${duplicateWarning} Check the budget with list_budget_sections.`);
35
+ }
4
36
  // ---------------------------------------------------------------------------
5
37
  // Tool: create_budget_service
6
38
  // ---------------------------------------------------------------------------
@@ -13,10 +45,18 @@ const createBudgetServiceSchema = z.object({
13
45
  price: z.coerce.number().optional(),
14
46
  quantity: z.coerce.number().optional(),
15
47
  budgeted_time: z.coerce.number().optional(),
48
+ section_id: z.string().min(1).optional(),
16
49
  });
50
+ const SECTION_HINT = 'Use a section of the same budget (from list_budget_sections or create_budget_section). ' +
51
+ 'The service is read back to confirm the assignment.';
52
+ const sectionIdProperty = {
53
+ type: 'string',
54
+ description: `Section to put the service into. ${SECTION_HINT}`,
55
+ };
17
56
  export async function createBudgetServiceTool(client, args) {
18
57
  try {
19
58
  const params = createBudgetServiceSchema.parse(args);
59
+ const sectionId = params.section_id === undefined ? undefined : toNumericId(params.section_id, 'section_id');
20
60
  const data = {
21
61
  data: {
22
62
  type: 'services',
@@ -28,6 +68,7 @@ export async function createBudgetServiceTool(client, args) {
28
68
  ...(params.price !== undefined && { price: params.price }),
29
69
  ...(params.quantity !== undefined && { quantity: params.quantity }),
30
70
  ...(params.budgeted_time !== undefined && { budgeted_time: params.budgeted_time }),
71
+ ...(sectionId !== undefined && { section_id: sectionId }),
31
72
  },
32
73
  relationships: {
33
74
  deal: { data: { id: params.budget_id, type: 'deals' } },
@@ -37,11 +78,14 @@ export async function createBudgetServiceTool(client, args) {
37
78
  const response = await client.createService(data);
38
79
  const id = response.data.id;
39
80
  const serviceName = response.data.attributes.name;
81
+ const sectionNote = sectionId === undefined
82
+ ? ''
83
+ : `\n${await confirmSection(client, id, String(sectionId), 'created')}`;
40
84
  return {
41
85
  content: [
42
86
  {
43
87
  type: 'text',
44
- text: `Service created! Service ID: ${id} (${serviceName}) on budget ${params.budget_id}\n\n` +
88
+ text: `Service created! Service ID: ${id} (${serviceName}) on budget ${params.budget_id}${sectionNote}\n\n` +
45
89
  'Next step: use update_budget_service to adjust fields, or list_deal_services to verify.',
46
90
  },
47
91
  ],
@@ -77,6 +121,7 @@ export const createBudgetServiceDefinition = {
77
121
  price: { type: 'number', description: 'Unit price' },
78
122
  quantity: { type: 'number', description: 'Number of units (hours/days/pieces)' },
79
123
  budgeted_time: { type: 'number', description: 'Allocated hours for this service' },
124
+ section_id: sectionIdProperty,
80
125
  },
81
126
  },
82
127
  annotations: {
@@ -99,16 +144,21 @@ const updateBudgetServiceSchema = z.object({
99
144
  unit_id: z.coerce.number().optional(),
100
145
  billing_type_id: z.coerce.number().optional(),
101
146
  budgeted_time: z.coerce.number().optional(),
147
+ section_id: z.string().min(1).optional(),
102
148
  });
103
149
  export async function updateBudgetServiceTool(client, args) {
104
150
  try {
105
- const { service_id, ...fields } = updateBudgetServiceSchema.parse(args);
151
+ const { service_id, section_id, ...fields } = updateBudgetServiceSchema.parse(args);
106
152
  const attributes = {};
107
153
  for (const [key, value] of Object.entries(fields)) {
108
154
  if (value !== undefined) {
109
155
  attributes[key] = value;
110
156
  }
111
157
  }
158
+ const sectionId = section_id === undefined ? undefined : toNumericId(section_id, 'section_id');
159
+ if (sectionId !== undefined) {
160
+ attributes.section_id = sectionId;
161
+ }
112
162
  if (Object.keys(attributes).length === 0) {
113
163
  throw new McpError(ErrorCode.InvalidParams, 'No fields to update provided.');
114
164
  }
@@ -121,11 +171,14 @@ export async function updateBudgetServiceTool(client, args) {
121
171
  };
122
172
  const response = await client.updateService(service_id, data);
123
173
  const service = response.data;
174
+ const sectionNote = sectionId === undefined
175
+ ? ''
176
+ : `\n${await confirmSection(client, service_id, String(sectionId), 'updated')}`;
124
177
  return {
125
178
  content: [
126
179
  {
127
180
  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'}`,
181
+ text: `Service ${service_id} updated.\n\nName: ${service.attributes.name}\nPrice: ${service.attributes.price ?? 'N/A'}\nQuantity: ${service.attributes.quantity ?? 'N/A'}${sectionNote}`,
129
182
  },
130
183
  ],
131
184
  };
@@ -137,7 +190,9 @@ export async function updateBudgetServiceTool(client, args) {
137
190
  export const updateBudgetServiceDefinition = {
138
191
  name: 'update_budget_service',
139
192
  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.',
193
+ 'unit_id, billing_type_id, budgeted_time and the section (section_id). Cannot move the ' +
194
+ 'service to a different budget, and cannot take it out of its section: Productive rejects ' +
195
+ 'an empty section, so move it to another section instead.',
141
196
  inputSchema: {
142
197
  type: 'object',
143
198
  required: ['service_id'],
@@ -156,6 +211,7 @@ export const updateBudgetServiceDefinition = {
156
211
  description: 'Billing type: 1 = Fixed, 2 = Actuals, 3 = None, 4 = Percentage',
157
212
  },
158
213
  budgeted_time: { type: 'number', description: 'Allocated hours for this service' },
214
+ section_id: sectionIdProperty,
159
215
  },
160
216
  },
161
217
  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.53",
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.53",
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.53",
4
4
  "type": "module",
5
5
  "main": "./build/index.js",
6
6
  "bin": {