@baseworks/invoice 1.2.2 → 1.2.3

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
@@ -155,6 +155,8 @@ optional peer.
155
155
  | `invoice_record_payment` | write | `invoice.record_payment` |
156
156
  | `invoice_void` (irreversible) | write | `invoice.void` |
157
157
 
158
+ The list tools are paged: `limit` (default 100, max 500) and `cursor` in, `next` out (null when there is nothing more). `offset` is still accepted for one release (not together with `cursor`).
159
+
158
160
  `invoice_create` and `invoice_finalize` take `external_number`; `invoice_list` takes the same filters as the client (`external_number` too); `invoice_record_payment` takes `payment_id`. There is no tool for the mirror upsert or the fiscal state: those are for services and for the tax-system extension. `invoice_set_external_number` takes the fiscal permission, as that is fiscal identity.
159
161
 
160
162
  A tool is a thin wrapper over the same client, so it can never do what the API would refuse, and `permission` is the name
package/dist/client.d.ts CHANGED
@@ -372,6 +372,11 @@ declare class InvoiceClient {
372
372
  /** Generic ApiClient (get/post/patch/del) — used by the CLI plugin. */
373
373
  get http(): HttpClient;
374
374
  list(opts?: ListInvoicesOptions): Promise<Invoice[]>;
375
+ /** One page and `next_offset` (null on the last page): pass it back as `offset` to read on. */
376
+ listPage(opts?: ListInvoicesOptions): Promise<{
377
+ invoices: Invoice[];
378
+ next_offset?: number | null;
379
+ }>;
375
380
  get(ref: string): Promise<Invoice>;
376
381
  create(input: CreateInvoiceInput): Promise<Invoice>;
377
382
  update(ref: string, input: UpdateInvoiceInput): Promise<Invoice>;
@@ -402,8 +407,25 @@ declare class InvoiceClient {
402
407
  limit?: number;
403
408
  offset?: number;
404
409
  }): Promise<Transaction[]>;
405
- /** Transactions recorded against one invoice. */
410
+ /** One page of the organization's transactions and `next_offset` (null on the last page). */
411
+ transactionsPage(opts?: {
412
+ limit?: number;
413
+ offset?: number;
414
+ }): Promise<{
415
+ transactions: Transaction[];
416
+ next_offset?: number | null;
417
+ }>;
418
+ private transactionList;
419
+ /** Transactions recorded against one invoice: its first 100. `invoiceTransactionsPage` reads on. */
406
420
  invoiceTransactions(ref: string): Promise<Transaction[]>;
421
+ /** One page of an invoice's transactions and `next_offset` (null on the last page). */
422
+ invoiceTransactionsPage(ref: string, opts?: {
423
+ limit?: number;
424
+ offset?: number;
425
+ }): Promise<{
426
+ transactions: Transaction[];
427
+ next_offset?: number | null;
428
+ }>;
407
429
  }
408
430
  /** Factory used by the SDK capability registry. */
409
431
  declare function createInvoiceClient(opts: InvoiceClientOptions): InvoiceClient;
package/dist/client.js CHANGED
@@ -115,6 +115,10 @@ var InvoiceClient = class _InvoiceClient {
115
115
  }
116
116
  // ── invoices ──────────────────────────────────────────────────────────────
117
117
  async list(opts = {}) {
118
+ return (await this.listPage(opts)).invoices;
119
+ }
120
+ /** One page and `next_offset` (null on the last page): pass it back as `offset` to read on. */
121
+ async listPage(opts = {}) {
118
122
  const q = new URLSearchParams();
119
123
  if (opts.limit !== void 0) q.set("limit", String(opts.limit));
120
124
  if (opts.offset !== void 0) q.set("offset", String(opts.offset));
@@ -126,8 +130,8 @@ var InvoiceClient = class _InvoiceClient {
126
130
  if (opts.customer_id) q.set("customer_id", opts.customer_id);
127
131
  if (opts.external_number) q.set("external_number", opts.external_number);
128
132
  const qs = q.toString();
129
- const { invoices } = await this.api("GET", `/invoices${qs ? `?${qs}` : ""}`);
130
- return invoices.map(oldNamesOnInvoice);
133
+ const { invoices, next_offset } = await this.api("GET", `/invoices${qs ? `?${qs}` : ""}`);
134
+ return { invoices: invoices.map(oldNamesOnInvoice), next_offset };
131
135
  }
132
136
  async get(ref) {
133
137
  const { invoice } = await this.api("GET", `/invoices/${ref}`);
@@ -190,17 +194,27 @@ var InvoiceClient = class _InvoiceClient {
190
194
  // ── transactions (the payment ledger) ───────────────────────────────────────
191
195
  /** All transactions for the org, newest first. */
192
196
  async transactions(opts = {}) {
197
+ return (await this.transactionsPage(opts)).transactions;
198
+ }
199
+ /** One page of the organization's transactions and `next_offset` (null on the last page). */
200
+ transactionsPage(opts = {}) {
201
+ return this.transactionList("/transactions", opts);
202
+ }
203
+ async transactionList(path, opts) {
193
204
  const q = new URLSearchParams();
194
205
  if (opts.limit !== void 0) q.set("limit", String(opts.limit));
195
206
  if (opts.offset !== void 0) q.set("offset", String(opts.offset));
196
207
  const qs = q.toString();
197
- const { transactions } = await this.api("GET", `/transactions${qs ? `?${qs}` : ""}`);
198
- return transactions.map(oldNamesOnTransaction);
208
+ const { transactions, next_offset } = await this.api("GET", `${path}${qs ? `?${qs}` : ""}`);
209
+ return { transactions: transactions.map(oldNamesOnTransaction), next_offset };
199
210
  }
200
- /** Transactions recorded against one invoice. */
211
+ /** Transactions recorded against one invoice: its first 100. `invoiceTransactionsPage` reads on. */
201
212
  async invoiceTransactions(ref) {
202
- const { transactions } = await this.api("GET", `/invoices/${ref}/payments`);
203
- return transactions.map(oldNamesOnTransaction);
213
+ return (await this.invoiceTransactionsPage(ref)).transactions;
214
+ }
215
+ /** One page of an invoice's transactions and `next_offset` (null on the last page). */
216
+ invoiceTransactionsPage(ref, opts = {}) {
217
+ return this.transactionList(`/invoices/${ref}/payments`, opts);
204
218
  }
205
219
  };
206
220
  function createInvoiceClient(opts) {
package/dist/mcp.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/mcp.ts
2
2
  import { z } from "zod";
3
- import { defineTool } from "@baseworks/mcp";
3
+ import { defineTool, encodeCursor, pageArgs, withPaging } from "@baseworks/mcp";
4
4
  var REF = z.string().min(1).describe("The invoice's id or its short id.");
5
5
  var Line = z.object({
6
6
  description: z.string().min(1).describe("What is being charged for."),
@@ -9,13 +9,23 @@ var Line = z.object({
9
9
  product_id: z.string().optional().describe("The id of a catalog product, if the line is one.")
10
10
  });
11
11
  var customer_id = z.string().min(1).describe("The customer: its id, short id or external id in the customer directory (see customers_list). It must exist.");
12
+ var PAGED = "Paged: at most `limit` (default 100, max 500); when `next` is not null there is more: call again with the same filters and `cursor: next`.";
13
+ var Offset = z.number().int().min(0).optional().describe("Deprecated: use `cursor`. How many to skip; not together with `cursor`.");
14
+ function pageOf(a) {
15
+ if (a.offset === void 0) return pageArgs(a);
16
+ if (a.cursor !== void 0) {
17
+ throw Object.assign(new Error("give `cursor` or `offset`, not both: `offset` is deprecated, pass the `next` of the previous page as `cursor`"), { code: "bad_request", status: 400 });
18
+ }
19
+ return { limit: pageArgs({ limit: a.limit }).limit, offset: a.offset };
20
+ }
21
+ var nextOf = (next_offset) => next_offset == null ? null : encodeCursor(next_offset);
12
22
  function invoiceTools() {
13
23
  return [
14
24
  defineTool({
15
25
  name: "invoice_list",
16
26
  title: "List invoices",
17
- description: 'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. Each invoice has its totals, the amount paid, the `balance_cents` still owed and a `payment_status` (unpaid, partially_paid, paid; not_due for a draft or void invoice), so the answer to "what is unpaid" is one call: filter with `payment_status`, `overdue`, `source`, `fiscal_status`, `customer_id` and `external_number` (exact: find the invoice a number belongs to); filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
18
- input: z.object({
27
+ description: `Lists the organization's invoices, newest first. Narrow with \`status\`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. Each invoice has its totals, the amount paid, the \`balance_cents\` still owed and a \`payment_status\` (unpaid, partially_paid, paid; not_due for a draft or void invoice), so the answer to "what is unpaid" is one call: filter with \`payment_status\`, \`overdue\`, \`source\`, \`fiscal_status\`, \`customer_id\` and \`external_number\` (exact: find the invoice a number belongs to); filters combine. Money is integer cents. Returns \`{ invoices, next }\`. ${PAGED} Read only.`,
28
+ input: z.object(withPaging(z, {
19
29
  status: z.enum(["draft", "finalized", "paid", "void"]).optional().describe("Only invoices in this status."),
20
30
  payment_status: z.array(z.enum(["unpaid", "partially_paid", "paid", "not_due"])).min(1).optional().describe("Only invoices in one of these payment states. `unpaid` and `partially_paid` are what is still owed; `not_due` is a draft or void invoice."),
21
31
  overdue: z.boolean().optional().describe("true: only what is owed and past its due date."),
@@ -23,15 +33,15 @@ function invoiceTools() {
23
33
  fiscal_status: z.enum(["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"]).optional().describe("Only invoices in this state with a tax system."),
24
34
  customer_id: z.string().optional().describe("Only this customer's invoices: the customer's id."),
25
35
  external_number: z.string().optional().describe("Only the invoice with this exact external number (the number another system gave it)."),
26
- limit: z.number().int().min(1).max(100).optional().describe("Page size, 1 to 100 (default 25)."),
27
- offset: z.number().int().min(0).optional().describe("How many to skip, for the next page.")
28
- }),
36
+ offset: Offset
37
+ })),
29
38
  access: "read",
30
39
  permission: "invoice.read",
31
- run: async (ctx, a) => ({
32
- invoices: await ctx.clients.invoice.list({
33
- limit: a.limit ?? 25,
34
- ...a.offset ? { offset: a.offset } : {},
40
+ run: async (ctx, a) => {
41
+ const page = pageOf(a);
42
+ const res = await ctx.clients.invoice.listPage({
43
+ limit: page.limit,
44
+ ...page.offset ? { offset: page.offset } : {},
35
45
  ...a.status ? { status: a.status } : {},
36
46
  ...a.payment_status ? { payment_status: a.payment_status } : {},
37
47
  ...a.overdue !== void 0 ? { overdue: a.overdue } : {},
@@ -39,8 +49,9 @@ function invoiceTools() {
39
49
  ...a.fiscal_status ? { fiscal_status: a.fiscal_status } : {},
40
50
  ...a.customer_id ? { customer_id: a.customer_id } : {},
41
51
  ...a.external_number ? { external_number: a.external_number } : {}
42
- })
43
- })
52
+ });
53
+ return { invoices: res.invoices, next: nextOf(res.next_offset) };
54
+ }
44
55
  }),
45
56
  defineTool({
46
57
  name: "invoice_get",
@@ -63,17 +74,19 @@ function invoiceTools() {
63
74
  defineTool({
64
75
  name: "invoice_transactions",
65
76
  title: "List payments",
66
- description: "The money ledger: one entry per payment recorded, newest first. Give `ref` for one invoice's payments, or leave it out for every payment of the organization. Each entry says the invoice number, the customer, the amount in cents, the method and the reference. Read only.",
67
- input: z.object({
77
+ description: `The money ledger: one entry per payment recorded, newest first. Give \`ref\` for one invoice's payments, or leave it out for every payment of the organization. Each entry says the invoice number, the customer, the amount in cents, the method and the reference. ${PAGED} Read only.`,
78
+ input: z.object(withPaging(z, {
68
79
  ref: REF.optional().describe("An invoice id or short id; leave out for the whole organization."),
69
- limit: z.number().int().min(1).max(100).optional().describe("Page size when listing the whole organization, 1 to 100 (default 25)."),
70
- offset: z.number().int().min(0).optional()
71
- }),
80
+ offset: Offset
81
+ })),
72
82
  access: "read",
73
83
  permission: "invoice.read",
74
- run: async (ctx, a) => ({
75
- transactions: a.ref ? await ctx.clients.invoice.invoiceTransactions(a.ref) : await ctx.clients.invoice.transactions({ limit: a.limit ?? 25, ...a.offset ? { offset: a.offset } : {} })
76
- })
84
+ run: async (ctx, a) => {
85
+ const page = pageOf(a);
86
+ const q = { limit: page.limit, ...page.offset ? { offset: page.offset } : {} };
87
+ const res = a.ref ? await ctx.clients.invoice.invoiceTransactionsPage(a.ref, q) : await ctx.clients.invoice.transactionsPage(q);
88
+ return { transactions: res.transactions, next: nextOf(res.next_offset) };
89
+ }
77
90
  }),
78
91
  defineTool({
79
92
  name: "invoice_create",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baseworks/invoice",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
4
4
  "description": "Invoice capability: typed HTTP client, event catalog, projections, and CLI plugin for invoice-service (AR ledger). Contract-first, versioned with the service.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -8,7 +8,7 @@ import { invoiceTools } from '../mcp.js'
8
8
 
9
9
  const calls: Array<[string, ...unknown[]]> = []
10
10
  const fake = {
11
- list: async (o: unknown) => { calls.push(['list', o]); return [{ id: 'i1' }] },
11
+ listPage: async (o: unknown) => { calls.push(['listPage', o]); return { invoices: [{ id: 'i1' }], next_offset: null } },
12
12
  get: async (ref: string) => { calls.push(['get', ref]); if (ref === 'gone') throw new InvoiceError(404, 'not_found', 'Invoice not found'); return { id: 'i2', short_id: ref } },
13
13
  create: async (a: unknown) => { calls.push(['create', a]); return { id: 'new', ...(a as object) } },
14
14
  update: async (ref: string, a: unknown) => { calls.push(['update', ref, a]); return { id: ref } },
@@ -18,8 +18,8 @@ const fake = {
18
18
  getNumbering: async () => { calls.push(['getNumbering']); return { prefix: 'BSF', digits: 9, yearly: true, next: 149, next_text: 'BSF2026000000149', updated_at: 1 } },
19
19
  setExternalNumber: async (ref: string, external_number: string) => { calls.push(['setExternalNumber', ref, external_number]); return { id: ref, external_number } },
20
20
  setNumbering: async (a: unknown) => { calls.push(['setNumbering', a]); return { ...(a as object), next: 1, next_text: 'x', updated_at: 2 } },
21
- transactions: async (o: unknown) => { calls.push(['transactions', o]); return [{ id: 't1' }] },
22
- invoiceTransactions: async (ref: string) => { calls.push(['invoiceTransactions', ref]); return [{ id: 't2' }] },
21
+ transactionsPage: async (o: unknown) => { calls.push(['transactionsPage', o]); return { transactions: [{ id: 't1' }], next_offset: null } },
22
+ invoiceTransactionsPage: async (ref: string, o: unknown) => { calls.push(['invoiceTransactionsPage', ref, o]); return { transactions: [{ id: 't2' }], next_offset: null } },
23
23
  }
24
24
 
25
25
  async function session(over: Partial<Parameters<typeof runStdio>[0]> = {}) {
@@ -80,7 +80,7 @@ describe('through a real MCP client', () => {
80
80
  it('list: the filters reach the client; payment_status is a list', async () => {
81
81
  const c = await session()
82
82
  await c.callTool({ name: 'invoice_list', arguments: { payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' } })
83
- expect(calls).toEqual([['list', { limit: 25, payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' }]])
83
+ expect(calls).toEqual([['listPage', { limit: 100, payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' }]])
84
84
  for (const bad of [{ payment_status: [] }, { payment_status: ['late'] }, { source: 'paypal' }]) expect(await refused(c, 'invoice_list', bad), JSON.stringify(bad)).toBeTruthy()
85
85
  })
86
86
 
@@ -106,7 +106,7 @@ describe('through a real MCP client', () => {
106
106
  await c.callTool({ name: 'invoice_create', arguments: args })
107
107
  await c.callTool({ name: 'invoice_finalize', arguments: { ref: 'i1', external_number: 'PORTAL-1' } })
108
108
  await c.callTool({ name: 'invoice_list', arguments: { external_number: 'PORTAL-1' } })
109
- expect(calls).toEqual([['create', args], ['finalize', 'i1', { external_number: 'PORTAL-1' }], ['list', { limit: 25, external_number: 'PORTAL-1' }]])
109
+ expect(calls).toEqual([['create', args], ['finalize', 'i1', { external_number: 'PORTAL-1' }], ['listPage', { limit: 100, external_number: 'PORTAL-1' }]])
110
110
  expect(await refused(c, 'invoice_create', { ...args, external_number: 'x'.repeat(65) })).toBeTruthy()
111
111
  const d = Object.fromEntries(invoiceTools().map((t) => [t.name, t.description]))
112
112
  expect(d['invoice_create']).toMatch(/takes none from the organization's series/)
@@ -138,15 +138,15 @@ describe('through a real MCP client', () => {
138
138
  expect(calls).toEqual([['recordPayment', 'i1', { amount_cents: 5, payment_id: 'pay_1' }]])
139
139
  })
140
140
 
141
- it('list: a status and a page; defaults to 25', async () => {
141
+ it('list: a status and a page; defaults to 100', async () => {
142
142
  const c = await session()
143
- expect(out(await c.callTool({ name: 'invoice_list', arguments: { status: 'finalized', limit: 5, offset: 10 } }))).toEqual({ invoices: [{ id: 'i1' }] })
144
- expect(calls).toEqual([['list', { limit: 5, offset: 10, status: 'finalized' }]])
143
+ expect(out(await c.callTool({ name: 'invoice_list', arguments: { status: 'finalized', limit: 5, offset: 10 } }))).toEqual({ invoices: [{ id: 'i1' }], next: null })
144
+ expect(calls).toEqual([['listPage', { limit: 5, offset: 10, status: 'finalized' }]])
145
145
  calls.length = 0
146
146
  await c.callTool({ name: 'invoice_list', arguments: {} })
147
- expect(calls).toEqual([['list', { limit: 25 }]])
147
+ expect(calls).toEqual([['listPage', { limit: 100 }]])
148
148
  calls.length = 0
149
- for (const args of [{ limit: 0 }, { limit: 101 }, { status: 'open' }]) expect(await refused(c, 'invoice_list', args), JSON.stringify(args)).toBeTruthy()
149
+ for (const args of [{ limit: 0 }, { limit: 501 }, { status: 'open' }]) expect(await refused(c, 'invoice_list', args), JSON.stringify(args)).toBeTruthy()
150
150
  expect(calls).toEqual([])
151
151
  })
152
152
 
@@ -160,9 +160,9 @@ describe('through a real MCP client', () => {
160
160
 
161
161
  it('transactions: one invoice\'s, or the organization\'s', async () => {
162
162
  const c = await session()
163
- expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { ref: 'i1' } }))).toEqual({ transactions: [{ id: 't2' }] })
164
- expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { limit: 3 } }))).toEqual({ transactions: [{ id: 't1' }] })
165
- expect(calls).toEqual([['invoiceTransactions', 'i1'], ['transactions', { limit: 3 }]])
163
+ expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { ref: 'i1' } }))).toEqual({ transactions: [{ id: 't2' }], next: null })
164
+ expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { limit: 3 } }))).toEqual({ transactions: [{ id: 't1' }], next: null })
165
+ expect(calls).toEqual([['invoiceTransactionsPage', 'i1', { limit: 100 }], ['transactionsPage', { limit: 3 }]])
166
166
  })
167
167
 
168
168
  it('create: lines in snake_case reach the client; what the API would refuse is refused here', async () => {
@@ -213,3 +213,64 @@ describe('through a real MCP client', () => {
213
213
  expect((await c.listTools()).tools.map((x) => x.name)).toEqual(['invoice_list', 'invoice_get', 'invoice_numbering', 'invoice_transactions', 'invoice_create', 'invoice_update'])
214
214
  })
215
215
  })
216
+
217
+ describe.each([
218
+ ['invoice_list', 'listPage', 'invoices', { status: 'finalized' }],
219
+ ['invoice_transactions', 'transactionsPage', 'transactions', {}],
220
+ ['invoice_transactions', 'invoiceTransactionsPage', 'transactions', { ref: 'i1' }],
221
+ ] as const)('%s is paged (%s)', (tool, method, key, filters) => {
222
+ const rows = Array.from({ length: 7 }, (_, i) => ({ id: `r${i}` }))
223
+ /** The service's paging over `rows`; the query is the last argument. */
224
+ const paged = { ...fake, [method]: async (...args: unknown[]) => {
225
+ const q = args[args.length - 1] as { limit: number; offset?: number }
226
+ calls.push([method, q])
227
+ const from = q.offset ?? 0
228
+ return { [key]: rows.slice(from, from + q.limit), next_offset: from + q.limit < rows.length ? from + q.limit : null }
229
+ } }
230
+ const open = () => session({ clients: () => ({ invoice: paged }) } as never)
231
+ const sent = () => calls.map((x) => x[1] as { limit: number; offset?: number })
232
+
233
+ it('asks for the first page of 100 by default', async () => {
234
+ const c = await open()
235
+ const page = out(await c.callTool({ name: tool, arguments: filters }))
236
+ expect(page[key].map((r: { id: string }) => r.id)).toEqual(rows.map((r) => r.id))
237
+ expect(page.next).toBeNull()
238
+ expect(sent()).toHaveLength(1)
239
+ expect(sent()[0]!.limit).toBe(100)
240
+ expect(sent()[0]!.offset ?? 0).toBe(0)
241
+ })
242
+ it('walks to the end with `next` as the cursor', async () => {
243
+ const c = await open()
244
+ const seen: string[] = []
245
+ let cursor: string | null = null
246
+ do {
247
+ const page: Record<string, unknown> = out(await c.callTool({ name: tool, arguments: { ...filters, limit: 3, ...(cursor ? { cursor } : {}) } }))
248
+ seen.push(...(page[key] as Array<{ id: string }>).map((r) => r.id))
249
+ cursor = page['next'] as string | null
250
+ } while (cursor)
251
+ expect(seen).toEqual(rows.map((r) => r.id))
252
+ expect(sent().map((q) => q.offset ?? 0)).toEqual([0, 3, 6])
253
+ })
254
+ it('takes 500, refuses 501 and a cursor it did not give', async () => {
255
+ const c = await open()
256
+ await c.callTool({ name: tool, arguments: { ...filters, limit: 500 } })
257
+ expect(sent()[0]!.limit).toBe(500)
258
+ calls.length = 0
259
+ expect(await refused(c, tool, { ...filters, limit: 501 })).toBeTruthy()
260
+ expect(out(await c.callTool({ name: tool, arguments: { ...filters, cursor: '100' } }))).toMatchObject({ error: 'invalid_cursor', status: 400 })
261
+ expect(calls).toEqual([])
262
+ })
263
+ it('still takes the deprecated `offset`, and refuses it together with `cursor`', async () => {
264
+ const c = await open()
265
+ const page = out(await c.callTool({ name: tool, arguments: { ...filters, offset: 2, limit: 3 } }))
266
+ expect(page[key].map((r: { id: string }) => r.id)).toEqual(['r2', 'r3', 'r4'])
267
+ calls.length = 0
268
+ const both = out(await c.callTool({ name: tool, arguments: { ...filters, offset: 0, cursor: page.next } }))
269
+ expect(both).toMatchObject({ error: 'bad_request', status: 400 })
270
+ expect(calls).toEqual([])
271
+ })
272
+ it('says how to page', () => {
273
+ const d = invoiceTools().find((t) => t.name === tool)!.description
274
+ for (const w of ['default 100', 'max 500', 'cursor: next']) expect(d, w).toContain(w)
275
+ })
276
+ })
package/src/client.ts CHANGED
@@ -148,6 +148,10 @@ export class InvoiceClient {
148
148
  // ── invoices ──────────────────────────────────────────────────────────────
149
149
 
150
150
  async list(opts: ListInvoicesOptions = {}): Promise<Invoice[]> {
151
+ return (await this.listPage(opts)).invoices
152
+ }
153
+ /** One page and `next_offset` (null on the last page): pass it back as `offset` to read on. */
154
+ async listPage(opts: ListInvoicesOptions = {}): Promise<{ invoices: Invoice[]; next_offset?: number | null }> {
151
155
  const q = new URLSearchParams()
152
156
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
153
157
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
@@ -159,8 +163,8 @@ export class InvoiceClient {
159
163
  if (opts.customer_id) q.set('customer_id', opts.customer_id)
160
164
  if (opts.external_number) q.set('external_number', opts.external_number)
161
165
  const qs = q.toString()
162
- const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
163
- return invoices.map(oldNamesOnInvoice)
166
+ const { invoices, next_offset } = await this.api<{ invoices: Invoice[]; next_offset?: number | null }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
167
+ return { invoices: invoices.map(oldNamesOnInvoice), next_offset }
164
168
  }
165
169
  async get(ref: string): Promise<Invoice> {
166
170
  const { invoice } = await this.api<{ invoice: Invoice }>('GET', `/invoices/${ref}`)
@@ -225,18 +229,31 @@ export class InvoiceClient {
225
229
 
226
230
  /** All transactions for the org, newest first. */
227
231
  async transactions(opts: { limit?: number; offset?: number } = {}): Promise<Transaction[]> {
232
+ return (await this.transactionsPage(opts)).transactions
233
+ }
234
+
235
+ /** One page of the organization's transactions and `next_offset` (null on the last page). */
236
+ transactionsPage(opts: { limit?: number; offset?: number } = {}): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
237
+ return this.transactionList('/transactions', opts)
238
+ }
239
+
240
+ private async transactionList(path: string, opts: { limit?: number; offset?: number }): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
228
241
  const q = new URLSearchParams()
229
242
  if (opts.limit !== undefined) q.set('limit', String(opts.limit))
230
243
  if (opts.offset !== undefined) q.set('offset', String(opts.offset))
231
244
  const qs = q.toString()
232
- const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/transactions${qs ? `?${qs}` : ''}`)
233
- return transactions.map(oldNamesOnTransaction)
245
+ const { transactions, next_offset } = await this.api<{ transactions: Transaction[]; next_offset?: number | null }>('GET', `${path}${qs ? `?${qs}` : ''}`)
246
+ return { transactions: transactions.map(oldNamesOnTransaction), next_offset }
234
247
  }
235
248
 
236
- /** Transactions recorded against one invoice. */
249
+ /** Transactions recorded against one invoice: its first 100. `invoiceTransactionsPage` reads on. */
237
250
  async invoiceTransactions(ref: string): Promise<Transaction[]> {
238
- const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/invoices/${ref}/payments`)
239
- return transactions.map(oldNamesOnTransaction)
251
+ return (await this.invoiceTransactionsPage(ref)).transactions
252
+ }
253
+
254
+ /** One page of an invoice's transactions and `next_offset` (null on the last page). */
255
+ invoiceTransactionsPage(ref: string, opts: { limit?: number; offset?: number } = {}): Promise<{ transactions: Transaction[]; next_offset?: number | null }> {
256
+ return this.transactionList(`/invoices/${ref}/payments`, opts)
240
257
  }
241
258
  }
242
259
 
package/src/mcp.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * give a model drafts and not the books.
14
14
  */
15
15
  import { z } from 'zod'
16
- import { defineTool, type McpTool } from '@baseworks/mcp'
16
+ import { defineTool, encodeCursor, pageArgs, withPaging, type McpTool } from '@baseworks/mcp'
17
17
  import type { FiscalStatus, InvoiceClient, InvoiceSource, PaymentStatus } from './client.js'
18
18
 
19
19
  /** What `ctx.clients` must hold for these tools. */
@@ -30,6 +30,18 @@ const Line = z.object({
30
30
 
31
31
  const customer_id = z.string().min(1).describe('The customer: its id, short id or external id in the customer directory (see customers_list). It must exist.')
32
32
 
33
+ const PAGED = 'Paged: at most `limit` (default 100, max 500); when `next` is not null there is more: call again with the same filters and `cursor: next`.'
34
+ /** `offset` is the input from before paging by cursor, kept for one release. */
35
+ const Offset = z.number().int().min(0).optional().describe('Deprecated: use `cursor`. How many to skip; not together with `cursor`.')
36
+ function pageOf(a: { limit?: number | undefined; cursor?: string | undefined; offset?: number | undefined }): { limit: number; offset: number } {
37
+ if (a.offset === undefined) return pageArgs(a)
38
+ if (a.cursor !== undefined) {
39
+ throw Object.assign(new Error('give `cursor` or `offset`, not both: `offset` is deprecated, pass the `next` of the previous page as `cursor`'), { code: 'bad_request', status: 400 })
40
+ }
41
+ return { limit: pageArgs({ limit: a.limit }).limit, offset: a.offset }
42
+ }
43
+ const nextOf = (next_offset: number | null | undefined) => (next_offset == null ? null : encodeCursor(next_offset))
44
+
33
45
  export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
34
46
  return [
35
47
  defineTool({
@@ -38,8 +50,9 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
38
50
  description:
39
51
  'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. ' +
40
52
  'Each invoice has its totals, the amount paid, the `balance_cents` still owed and a `payment_status` (unpaid, partially_paid, paid; not_due for a draft or void invoice), so the answer to "what is unpaid" is one call: ' +
41
- 'filter with `payment_status`, `overdue`, `source`, `fiscal_status`, `customer_id` and `external_number` (exact: find the invoice a number belongs to); filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
42
- input: z.object({
53
+ 'filter with `payment_status`, `overdue`, `source`, `fiscal_status`, `customer_id` and `external_number` (exact: find the invoice a number belongs to); filters combine. Money is integer cents. Returns `{ invoices, next }`. ' +
54
+ `${PAGED} Read only.`,
55
+ input: z.object(withPaging(z, {
43
56
  status: z.enum(['draft', 'finalized', 'paid', 'void']).optional().describe('Only invoices in this status.'),
44
57
  payment_status: z.array(z.enum(['unpaid', 'partially_paid', 'paid', 'not_due'])).min(1).optional().describe('Only invoices in one of these payment states. `unpaid` and `partially_paid` are what is still owed; `not_due` is a draft or void invoice.'),
45
58
  overdue: z.boolean().optional().describe('true: only what is owed and past its due date.'),
@@ -47,19 +60,20 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
47
60
  fiscal_status: z.enum(['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled']).optional().describe('Only invoices in this state with a tax system.'),
48
61
  customer_id: z.string().optional().describe('Only this customer\'s invoices: the customer\'s id.'),
49
62
  external_number: z.string().optional().describe('Only the invoice with this exact external number (the number another system gave it).'),
50
- limit: z.number().int().min(1).max(100).optional().describe('Page size, 1 to 100 (default 25).'),
51
- offset: z.number().int().min(0).optional().describe('How many to skip, for the next page.'),
52
- }),
63
+ offset: Offset,
64
+ })),
53
65
  access: 'read',
54
66
  permission: 'invoice.read',
55
- run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; payment_status?: PaymentStatus[]; overdue?: boolean; source?: InvoiceSource; fiscal_status?: FiscalStatus; customer_id?: string; external_number?: string; limit?: number; offset?: number }) => ({
56
- invoices: await ctx.clients.invoice.list({
57
- limit: a.limit ?? 25,
58
- ...(a.offset ? { offset: a.offset } : {}), ...(a.status ? { status: a.status } : {}),
67
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; payment_status?: PaymentStatus[]; overdue?: boolean; source?: InvoiceSource; fiscal_status?: FiscalStatus; customer_id?: string; external_number?: string; limit?: number; cursor?: string; offset?: number }) => {
68
+ const page = pageOf(a)
69
+ const res = await ctx.clients.invoice.listPage({
70
+ limit: page.limit,
71
+ ...(page.offset ? { offset: page.offset } : {}), ...(a.status ? { status: a.status } : {}),
59
72
  ...(a.payment_status ? { payment_status: a.payment_status } : {}), ...(a.overdue !== undefined ? { overdue: a.overdue } : {}),
60
73
  ...(a.source ? { source: a.source } : {}), ...(a.fiscal_status ? { fiscal_status: a.fiscal_status } : {}), ...(a.customer_id ? { customer_id: a.customer_id } : {}), ...(a.external_number ? { external_number: a.external_number } : {}),
61
- }),
62
- }),
74
+ })
75
+ return { invoices: res.invoices, next: nextOf(res.next_offset) }
76
+ },
63
77
  }),
64
78
 
65
79
  defineTool({
@@ -92,19 +106,20 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
92
106
  title: 'List payments',
93
107
  description:
94
108
  'The money ledger: one entry per payment recorded, newest first. Give `ref` for one invoice\'s payments, or leave it out for every payment of the organization. ' +
95
- 'Each entry says the invoice number, the customer, the amount in cents, the method and the reference. Read only.',
96
- input: z.object({
109
+ 'Each entry says the invoice number, the customer, the amount in cents, the method and the reference. ' +
110
+ `${PAGED} Read only.`,
111
+ input: z.object(withPaging(z, {
97
112
  ref: REF.optional().describe('An invoice id or short id; leave out for the whole organization.'),
98
- limit: z.number().int().min(1).max(100).optional().describe('Page size when listing the whole organization, 1 to 100 (default 25).'),
99
- offset: z.number().int().min(0).optional(),
100
- }),
113
+ offset: Offset,
114
+ })),
101
115
  access: 'read',
102
116
  permission: 'invoice.read',
103
- run: async (ctx: { clients: InvoiceMcpClients }, a: { ref?: string; limit?: number; offset?: number }) => ({
104
- transactions: a.ref
105
- ? await ctx.clients.invoice.invoiceTransactions(a.ref)
106
- : await ctx.clients.invoice.transactions({ limit: a.limit ?? 25, ...(a.offset ? { offset: a.offset } : {}) }),
107
- }),
117
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref?: string; limit?: number; cursor?: string; offset?: number }) => {
118
+ const page = pageOf(a)
119
+ const q = { limit: page.limit, ...(page.offset ? { offset: page.offset } : {}) }
120
+ const res = a.ref ? await ctx.clients.invoice.invoiceTransactionsPage(a.ref, q) : await ctx.clients.invoice.transactionsPage(q)
121
+ return { transactions: res.transactions, next: nextOf(res.next_offset) }
122
+ },
108
123
  }),
109
124
 
110
125
  defineTool({