@baseworks/invoice 0.1.1 → 1.0.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baseworks/invoice",
3
- "version": "0.1.1",
3
+ "version": "1.0.0",
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": {
@@ -11,7 +11,8 @@
11
11
  "./events": "./dist/events.js",
12
12
  "./projections": "./dist/projections.js",
13
13
  "./cli": "./dist/cli.js",
14
- "./graphql": "./dist/graphql.js"
14
+ "./graphql": "./dist/graphql.js",
15
+ "./mcp": "./dist/mcp.js"
15
16
  },
16
17
  "files": [
17
18
  "dist",
@@ -21,7 +22,8 @@
21
22
  "@baseworks/cli": "^0.2.0",
22
23
  "commander": "^15.0.0",
23
24
  "zod": "^3.25.76",
24
- "@baseworks/foldbase": "0.1.1"
25
+ "@baseworks/mcp": "^0.1.2",
26
+ "@baseworks/foldbase": "0.2.0"
25
27
  },
26
28
  "devDependencies": {
27
29
  "@types/node": "^22.20.0",
@@ -29,8 +31,17 @@
29
31
  "tsup": "^8.5.1",
30
32
  "typescript": "^5.9.3",
31
33
  "vitest": "^4.1.9",
34
+ "@modelcontextprotocol/sdk": "^1.32.2",
32
35
  "@baseworks/tsconfig": "0.1.0"
33
36
  },
37
+ "peerDependencies": {
38
+ "@modelcontextprotocol/sdk": "^1.32.0"
39
+ },
40
+ "peerDependenciesMeta": {
41
+ "@modelcontextprotocol/sdk": {
42
+ "optional": true
43
+ }
44
+ },
34
45
  "scripts": {
35
46
  "build": "tsup",
36
47
  "typecheck": "tsc --noEmit",
@@ -10,28 +10,28 @@ afterAll(() => server.close())
10
10
 
11
11
  const DRAFT = {
12
12
  id: '019f6a3e-1111-7c71-beff-496d1be3fd1f',
13
- shortId: 'inv9x2',
13
+ short_id: 'inv9x2',
14
14
  number: null,
15
15
  status: 'draft',
16
- customerId: 'cst1',
17
- customerName: 'Acme Co',
16
+ customer_id: 'cst1',
17
+ customer_name: 'Acme Co',
18
18
  currency: 'USD',
19
- lines: [{ description: 'Consulting', quantity: 10, unitPriceCents: 15000, amountCents: 150000, productId: null }],
20
- subtotalCents: 150000,
21
- totalCents: 150000,
22
- amountPaidCents: 0,
23
- balanceCents: 150000,
24
- issuedAt: null,
25
- dueAt: null,
26
- createdAt: 1784200000000,
19
+ lines: [{ description: 'Consulting', quantity: 10, unit_price_cents: 15000, amount_cents: 150000, product_id: null }],
20
+ subtotal_cents: 150000,
21
+ total_cents: 150000,
22
+ amount_paid_cents: 0,
23
+ balance_cents: 150000,
24
+ issued_at: null,
25
+ due_at: null,
26
+ created_at: 1784200000000,
27
27
  updatedAt: 1784200000000,
28
28
  }
29
- const FINAL = { ...DRAFT, number: 1, status: 'finalized', issuedAt: 1784200000000 }
30
- const PAID = { ...FINAL, status: 'paid', amountPaidCents: 150000, balanceCents: 0 }
29
+ const FINAL = { ...DRAFT, number: 1, status: 'finalized', issued_at: 1784200000000 }
30
+ const PAID = { ...FINAL, status: 'paid', amount_paid_cents: 150000, balance_cents: 0 }
31
31
 
32
32
  describe('dtab invoices (list)', () => {
33
33
  it('columns incl. NO/STATUS/TOTAL/BALANCE, draft NO shows —', async () => {
34
- mocks.mockGet('/v1/invoices', { invoices: [DRAFT, FINAL] })
34
+ mocks.mockGet('/invoices', { invoices: [DRAFT, FINAL] })
35
35
  const r = await run(['invoices'])
36
36
  expect(r.exitCode).toBe(0)
37
37
  expect(r.stdout).toContain('inv9x2')
@@ -42,15 +42,15 @@ describe('dtab invoices (list)', () => {
42
42
  })
43
43
 
44
44
  it('inv + invoice aliases list', async () => {
45
- mocks.mockGet('/v1/invoices', { invoices: [DRAFT] })
45
+ mocks.mockGet('/invoices', { invoices: [DRAFT] })
46
46
  expect((await run(['inv'])).stdout).toContain('inv9x2')
47
- mocks.mockGet('/v1/invoices', { invoices: [DRAFT] })
47
+ mocks.mockGet('/invoices', { invoices: [DRAFT] })
48
48
  expect((await run(['invoice'])).stdout).toContain('inv9x2')
49
49
  })
50
50
 
51
51
  it('--status filter passes through', async () => {
52
52
  let seen = ''
53
- server.use(http.get(`${TEST_BASE}/v1/invoices`, ({ request }) => {
53
+ server.use(http.get(`${TEST_BASE}/invoices`, ({ request }) => {
54
54
  seen = new URL(request.url).search
55
55
  return HttpResponse.json({ invoices: [] })
56
56
  }))
@@ -61,13 +61,13 @@ describe('dtab invoices (list)', () => {
61
61
 
62
62
  describe('dtab invoices create', () => {
63
63
  it('parses --line "desc|qty|price" → cents, sends customer + currency', async () => {
64
- const cap = mocks.mockPostCapture('/v1/invoices', { invoice: DRAFT })
64
+ const cap = mocks.mockPostCapture('/invoices', { invoice: DRAFT })
65
65
  const r = await run(['invoices', 'create', '--customer', 'cst1', '--currency', 'USD', '--line', 'Consulting|10|150.00'])
66
66
  expect(r.exitCode).toBe(0)
67
67
  const body = cap.body as Record<string, unknown>
68
- expect(body.customerId).toBe('cst1')
68
+ expect(body.customer_id).toBe('cst1')
69
69
  expect(body.currency).toBe('USD')
70
- expect(body.lines).toEqual([{ description: 'Consulting', quantity: 10, unitPriceCents: 15000 }])
70
+ expect(body.lines).toEqual([{ description: 'Consulting', quantity: 10, unit_price_cents: 15000 }])
71
71
  })
72
72
 
73
73
  it('rejects malformed --line', async () => {
@@ -85,7 +85,7 @@ describe('dtab invoices create', () => {
85
85
 
86
86
  describe('dtab invoices get / finalize / pay / void', () => {
87
87
  it('get shows lines table + totals + balance', async () => {
88
- mocks.mockGet('/v1/invoices/inv9x2', { invoice: FINAL })
88
+ mocks.mockGet('/invoices/inv9x2', { invoice: FINAL })
89
89
  const r = await run(['invoices', 'get', 'inv9x2'])
90
90
  expect(r.stdout).toContain('Consulting')
91
91
  expect(r.stdout).toContain('1500.00 USD')
@@ -93,23 +93,23 @@ describe('dtab invoices get / finalize / pay / void', () => {
93
93
  })
94
94
 
95
95
  it('finalize posts to /finalize, shows number', async () => {
96
- mocks.mockPost('/v1/invoices/inv9x2/finalize', { invoice: FINAL })
96
+ mocks.mockPost('/invoices/inv9x2/finalize', { invoice: FINAL })
97
97
  const r = await run(['invoices', 'finalize', 'inv9x2'])
98
98
  expect(r.stdout).toContain('#1')
99
99
  })
100
100
 
101
101
  it('pay converts --amount to cents, posts payment', async () => {
102
- const cap = mocks.mockPostCapture('/v1/invoices/inv9x2/payments', { invoice: PAID })
102
+ const cap = mocks.mockPostCapture('/invoices/inv9x2/payments', { invoice: PAID })
103
103
  const r = await run(['invoices', 'pay', 'inv9x2', '--amount', '1500.00', '--method', 'bank'])
104
104
  expect(r.exitCode).toBe(0)
105
105
  const body = cap.body as Record<string, unknown>
106
- expect(body.amountCents).toBe(150000)
106
+ expect(body.amount_cents).toBe(150000)
107
107
  expect(body.method).toBe('bank')
108
108
  expect(r.stdout).toContain('paid')
109
109
  })
110
110
 
111
111
  it('void posts to /void', async () => {
112
- mocks.mockPost('/v1/invoices/inv9x2/void', { invoice: { ...FINAL, status: 'void' } })
112
+ mocks.mockPost('/invoices/inv9x2/void', { invoice: { ...FINAL, status: 'void' } })
113
113
  const r = await run(['invoices', 'void', 'inv9x2', '--reason', 'mistake'])
114
114
  expect(r.exitCode).toBe(0)
115
115
  expect(r.stdout).toContain('inv9x2')
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @baseworks/invoice 0.3.0: the wire is snake_case. Options are `base_url` and `org_id` (`baseUrl`, `orgId`
3
+ * still read, deprecated). A caller that still speaks camelCase (billing, stripe) is sent as snake_case, and
4
+ * reads the old names on what comes back, without the old names appearing in the data.
5
+ */
6
+ import { describe, expect, it } from 'vitest'
7
+ import { InvoiceClient, createInvoiceClient } from '../client.js'
8
+
9
+ const seen: Array<{ method: string; url: string; org: string | null; auth: string | null; body: unknown }> = []
10
+ const INVOICE = {
11
+ id: 'i1', short_id: 'sh1', number: 7, status: 'finalized', customer_id: 'c1', customer_name: 'Acme', currency: 'EUR',
12
+ lines: [{ description: 'x', quantity: 2, unit_price_cents: 500, amount_cents: 1000, product_id: null }],
13
+ subtotal_cents: 1000, total_cents: 1000, amount_paid_cents: 250, balance_cents: 750, issued_at: 5, due_at: null, created_at: 1, updated_at: 2,
14
+ }
15
+ const TXN = { id: 't1', invoice_id: 'i1', invoice_number: 7, customer_id: 'c1', customer_name: 'Acme', kind: 'payment', amount_cents: 250, currency: 'EUR', method: null, reference: 'R', created_at: 3 }
16
+ const f = (async (url: string, init?: RequestInit) => {
17
+ const h = new Headers(init?.headers)
18
+ seen.push({ method: init?.method ?? 'GET', url: String(url), org: h.get('x-org-id'), auth: h.get('authorization'), body: init?.body ? JSON.parse(String(init.body)) : undefined })
19
+ const path = new URL(String(url)).pathname
20
+ if (path.endsWith('/payments') && init?.method === 'GET') return new Response(JSON.stringify({ transactions: [TXN] }))
21
+ if (path.endsWith('/transactions')) return new Response(JSON.stringify({ transactions: [TXN] }))
22
+ if (path.endsWith('/invoices') && init?.method === 'GET') return new Response(JSON.stringify({ invoices: [INVOICE] }))
23
+ return new Response(JSON.stringify({ invoice: INVOICE }), { status: init?.method === 'POST' && path.endsWith('/invoices') ? 201 : 200 })
24
+ }) as unknown as typeof fetch
25
+
26
+ describe('options', () => {
27
+ it.each([
28
+ ['snake_case', { base_url: 'http://i.test/api/', org_id: 'org-1' }],
29
+ ['deprecated camelCase', { baseUrl: 'http://i.test/api/', orgId: 'org-1' }],
30
+ ])('%s: the base, the org header and the token are the same', async (_n, o) => {
31
+ seen.length = 0
32
+ await createInvoiceClient({ ...o, token: 't', fetch: f }).list()
33
+ expect(seen).toEqual([{ method: 'GET', url: 'http://i.test/api/invoices', org: 'org-1', auth: 'Bearer t', body: undefined }])
34
+ })
35
+ it('withOrg moves to another org, whichever spelling the client was built with', async () => {
36
+ for (const o of [{ base_url: 'http://i.test' }, { baseUrl: 'http://i.test' }]) {
37
+ seen.length = 0
38
+ await new InvoiceClient({ ...o, org_id: 'org-1', fetch: f }).withOrg('org-2').list()
39
+ expect(seen[0]!.org).toBe('org-2')
40
+ }
41
+ })
42
+ it('needs a base', () => { expect(() => new InvoiceClient({})).toThrow(/base_url/) })
43
+ })
44
+
45
+ describe('what comes back', () => {
46
+ it('is the service\'s snake_case, and the old names read the same values', async () => {
47
+ const c = new InvoiceClient({ base_url: 'http://i.test', fetch: f })
48
+ const inv = await c.get('i1')
49
+ expect(inv.total_cents).toBe(1000)
50
+ expect(inv.totalCents).toBe(1000) // deprecated
51
+ expect(inv.shortId).toBe('sh1')
52
+ expect(inv.customerName).toBe('Acme')
53
+ expect(inv.balanceCents).toBe(750)
54
+ expect(inv.dueAt).toBeNull()
55
+ expect(inv.lines[0]!.unitPriceCents).toBe(500)
56
+ expect(inv.lines[0]!.unit_price_cents).toBe(500)
57
+ expect((await c.list())[0]!.createdAt).toBe(1)
58
+ const [t] = await c.invoiceTransactions('i1')
59
+ expect([t!.amountCents, t!.invoiceNumber, t!.customerId, t!.createdAt]).toEqual([250, 7, 'c1', 3])
60
+ expect((await c.transactions())[0]!.amount_cents).toBe(250)
61
+ })
62
+ it('the old names are not data: JSON and equality see the snake_case object only', async () => {
63
+ const inv = await new InvoiceClient({ base_url: 'http://i.test', fetch: f }).get('i1')
64
+ expect(JSON.parse(JSON.stringify(inv))).toEqual(INVOICE)
65
+ expect(inv).toEqual(INVOICE)
66
+ expect(Object.keys(inv).some((k) => /[A-Z]/.test(k))).toBe(false)
67
+ })
68
+ })
69
+
70
+ describe('what goes out', () => {
71
+ const c = () => new InvoiceClient({ base_url: 'http://i.test', fetch: f })
72
+ it('camelCase input is sent as snake_case', async () => {
73
+ seen.length = 0
74
+ await c().create({ customerId: 'c1', currency: 'EUR', lines: [{ description: 'x', quantity: 2, unitPriceCents: 500, productId: 'p' }] })
75
+ await c().update('i1', { customerId: 'c2', lines: [{ description: 'y', quantity: 1, unitPriceCents: 1 }] })
76
+ await c().finalize('i1', { issuedAt: 5, dueAt: 9 })
77
+ await c().recordPayment('i1', { amountCents: 100, method: 'bank' })
78
+ expect(seen.map((s) => s.body)).toEqual([
79
+ { customer_id: 'c1', currency: 'EUR', lines: [{ description: 'x', quantity: 2, unit_price_cents: 500, product_id: 'p' }] },
80
+ { customer_id: 'c2', lines: [{ description: 'y', quantity: 1, unit_price_cents: 1 }] },
81
+ { issued_at: 5, due_at: 9 },
82
+ { amount_cents: 100, method: 'bank' },
83
+ ])
84
+ })
85
+ it('snake_case input is sent as it is, and the new name wins when both are given', async () => {
86
+ seen.length = 0
87
+ await c().create({ customer_id: 'c1', customerId: 'old', currency: 'EUR', lines: [{ description: 'x', quantity: 1, unit_price_cents: 5, unitPriceCents: 9 }] })
88
+ await c().recordPayment('i1', { amount_cents: 7, amountCents: 8 })
89
+ expect(seen.map((s) => s.body)).toEqual([
90
+ { customer_id: 'c1', currency: 'EUR', lines: [{ description: 'x', quantity: 1, unit_price_cents: 5 }] },
91
+ { amount_cents: 7 },
92
+ ])
93
+ })
94
+ })
95
+
96
+ describe('the source is snake_case', () => {
97
+ it('compat.ts is the only place the old names live', async () => {
98
+ const { readdirSync, readFileSync } = await import('node:fs')
99
+ const { resolve, join, dirname } = await import('node:path')
100
+ const { fileURLToPath } = await import('node:url')
101
+ const src = resolve(dirname(fileURLToPath(import.meta.url)), '..')
102
+ const OLD = /\.(customerId|customerName|shortId|subtotalCents|totalCents|amountPaidCents|balanceCents|issuedAt|dueAt|createdAt|updatedAt|unitPriceCents|amountCents|productId|invoiceId|invoiceNumber|userId|orgId|baseUrl)\b/
103
+ for (const f of readdirSync(src).filter((x) => x.endsWith('.ts') && !['compat.ts', 'graphql.ts'].includes(x))) {
104
+ const hits = readFileSync(join(src, f), 'utf8').split('\n').map((l, i) => [i + 1, l] as const).filter(([, l]) => OLD.test(l) && !/deprecated|Deprecated/i.test(l))
105
+ expect(hits, f).toEqual([])
106
+ }
107
+ })
108
+ })
@@ -0,0 +1,75 @@
1
+ import { execSync } from 'node:child_process'
2
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
3
+ import { dirname, join, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { beforeAll, describe, expect, it } from 'vitest'
6
+ import ts from 'typescript'
7
+
8
+ /**
9
+ * A consumer sees the .d.ts, not the sources. A type named in an exported signature that the package does not export
10
+ * cannot be named by the consumer (it had to be re-declared, as `AddressPatch` was). For every entry's declaration
11
+ * file: whatever the exported declarations reference, in the same file, must itself be exported.
12
+ */
13
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..')
14
+ const dist = join(root, 'dist')
15
+
16
+ beforeAll(() => { execSync('npx tsup', { cwd: root, stdio: 'ignore' }) }, 180_000)
17
+
18
+ function unexportedButReferenced(file: string): string[] {
19
+ const sf = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.ES2022, true)
20
+ const declared = new Map<string, ts.Node>()
21
+ const exported = new Set<string>()
22
+ const hasExport = (n: ts.Node) => !!(ts.canHaveModifiers(n) && ts.getModifiers(n)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword))
23
+ for (const st of sf.statements) {
24
+ if (ts.isExportDeclaration(st) && st.exportClause && ts.isNamedExports(st.exportClause)) {
25
+ if (!st.moduleSpecifier) for (const e of st.exportClause.elements) exported.add((e.propertyName ?? e.name).text)
26
+ } else if (ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isClassDeclaration(st) || ts.isFunctionDeclaration(st) || ts.isEnumDeclaration(st)) {
27
+ if (st.name) { declared.set(st.name.text, st); if (hasExport(st)) exported.add(st.name.text) }
28
+ } else if (ts.isVariableStatement(st)) {
29
+ for (const d of st.declarationList.declarations) if (ts.isIdentifier(d.name)) { declared.set(d.name.text, st); if (hasExport(st)) exported.add(d.name.text) }
30
+ }
31
+ }
32
+ // names used by a declaration (types and `typeof x`), ignoring its own type parameters
33
+ const refs = (node: ts.Node): string[] => {
34
+ const out: string[] = []
35
+ const visit = (n: ts.Node) => {
36
+ if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) out.push(n.typeName.text)
37
+ if (ts.isExpressionWithTypeArguments(n) && ts.isIdentifier(n.expression)) out.push(n.expression.text)
38
+ if (ts.isTypeQueryNode(n) && ts.isIdentifier(n.exprName)) out.push(n.exprName.text)
39
+ ts.forEachChild(n, visit)
40
+ }
41
+ visit(node)
42
+ return out
43
+ }
44
+ const bad = new Set<string>()
45
+ const seen = new Set<string>()
46
+ const queue = [...exported]
47
+ while (queue.length) {
48
+ const name = queue.pop()!
49
+ if (seen.has(name)) continue
50
+ seen.add(name)
51
+ const node = declared.get(name)
52
+ if (!node) continue
53
+ for (const r of refs(node)) {
54
+ if (!declared.has(r)) continue // a global, a type parameter, or imported from another package
55
+ if (!exported.has(r)) bad.add(r)
56
+ queue.push(r)
57
+ }
58
+ }
59
+ return [...bad].sort()
60
+ }
61
+
62
+ describe('the declaration files', () => {
63
+ it('every entry exports every type its exported signatures name', () => {
64
+ const files = readdirSync(dist).filter((f) => f.endsWith('.d.ts'))
65
+ expect(files.length).toBeGreaterThan(3)
66
+ const report: Record<string, string[]> = {}
67
+ for (const f of files) { const bad = unexportedButReferenced(join(dist, f)); if (bad.length) report[f] = bad }
68
+ expect(report).toEqual({})
69
+ })
70
+
71
+ it('the deprecated aliases are types a caller can name', () => {
72
+ const d = readFileSync(join(dist, 'client.d.ts'), 'utf8')
73
+ for (const n of ['InvoiceDeprecated', 'InvoiceLineDeprecated', 'TransactionDeprecated']) expect(d).toMatch(new RegExp(`export \\{[^}]*\\b${n}\\b`))
74
+ })
75
+ })
@@ -0,0 +1,150 @@
1
+ /** The invoice tools: names, access, permissions, inputs, what they call, what a model is told. */
2
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
3
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
4
+ import { describe, expect, it } from 'vitest'
5
+ import { composeTools, runStdio } from '@baseworks/mcp'
6
+ import { InvoiceError } from '../client.js'
7
+ import { invoiceTools } from '../mcp.js'
8
+
9
+ const calls: Array<[string, ...unknown[]]> = []
10
+ const fake = {
11
+ list: async (o: unknown) => { calls.push(['list', o]); return [{ id: 'i1' }] },
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
+ create: async (a: unknown) => { calls.push(['create', a]); return { id: 'new', ...(a as object) } },
14
+ update: async (ref: string, a: unknown) => { calls.push(['update', ref, a]); return { id: ref } },
15
+ finalize: async (ref: string, a: unknown) => { calls.push(['finalize', ref, a]); return { id: ref, status: 'finalized' } },
16
+ recordPayment: async (ref: string, a: unknown) => { calls.push(['recordPayment', ref, a]); return { id: ref, status: 'paid' } },
17
+ void: async (ref: string, reason?: string) => { calls.push(['void', ref, reason]); return { id: ref, status: 'void' } },
18
+ transactions: async (o: unknown) => { calls.push(['transactions', o]); return [{ id: 't1' }] },
19
+ invoiceTransactions: async (ref: string) => { calls.push(['invoiceTransactions', ref]); return [{ id: 't2' }] },
20
+ }
21
+
22
+ async function session(over: Partial<Parameters<typeof runStdio>[0]> = {}) {
23
+ const [a, b] = InMemoryTransport.createLinkedPair()
24
+ await runStdio({ tools: composeTools(invoiceTools()), token: 'x.y.z', transport: a, clients: () => ({ invoice: fake }), ...over } as never)
25
+ const client = new Client({ name: 'c', version: '1' })
26
+ await client.connect(b)
27
+ calls.length = 0
28
+ return client
29
+ }
30
+ const out = (r: { content?: unknown }) => JSON.parse(((r.content as Array<{ text: string }>)[0]!).text)
31
+ const refused = async (c: Client, name: string, args: Record<string, unknown>) => {
32
+ const r = await c.callTool({ name, arguments: args }).catch((e) => e)
33
+ return r instanceof Error || (r as { isError?: boolean }).isError
34
+ }
35
+
36
+ describe('the tool set', () => {
37
+ it('is invoice_<verb>, composes with itself once, and says read or write with the permission the service registered', () => {
38
+ const tools = invoiceTools()
39
+ expect(tools.map((t) => [t.name, t.access, t.permission])).toEqual([
40
+ ['invoice_list', 'read', 'invoice.read'], ['invoice_get', 'read', 'invoice.read'], ['invoice_transactions', 'read', 'invoice.read'],
41
+ ['invoice_create', 'write', 'invoice.write'], ['invoice_update', 'write', 'invoice.write'],
42
+ ['invoice_finalize', 'write', 'invoice.finalize'], ['invoice_record_payment', 'write', 'invoice.record_payment'], ['invoice_void', 'write', 'invoice.void'],
43
+ ])
44
+ expect(composeTools(tools)).toHaveLength(8)
45
+ expect(() => composeTools(tools, invoiceTools())).toThrow(/duplicate/)
46
+ })
47
+ it('permission names are the ones invoice-service registers', async () => {
48
+ const { INVOICE_ACTIONS } = await import('../../../../src/lib/org.js')
49
+ for (const t of invoiceTools()) expect(Object.keys(INVOICE_ACTIONS)).toContain(t.permission)
50
+ // and the access each tool declares is the one the manifest declares for it
51
+ for (const t of invoiceTools()) expect(INVOICE_ACTIONS[t.permission as keyof typeof INVOICE_ACTIONS].access, t.name).toBe(t.access)
52
+ })
53
+ it('descriptions are written for a model: what it returns, what it writes, what needs a confirmation', () => {
54
+ const d = Object.fromEntries(invoiceTools().map((t) => [t.name, t.description]))
55
+ expect(d['invoice_list']).toMatch(/balance_cents/)
56
+ expect(d['invoice_create']).toMatch(/WRITES/)
57
+ expect(d['invoice_create']).toMatch(/customer_not_found/)
58
+ expect(d['invoice_create']).toMatch(/integer cents/)
59
+ expect(d['invoice_finalize']).toMatch(/cannot be undone/)
60
+ expect(d['invoice_finalize']).toMatch(/confirm/i)
61
+ expect(d['invoice_record_payment']).toMatch(/reference/)
62
+ expect(d['invoice_void']).toMatch(/cannot be undone/)
63
+ for (const t of invoiceTools()) expect(t.description.length, t.name).toBeGreaterThan(120)
64
+ })
65
+ })
66
+
67
+ describe('through a real MCP client', () => {
68
+ it('lists the eight tools; reads are hinted read-only, writes are not', async () => {
69
+ const t = (await (await session()).listTools()).tools
70
+ expect(t).toHaveLength(8)
71
+ expect(t.find((x) => x.name === 'invoice_get')!.annotations).toMatchObject({ readOnlyHint: true })
72
+ for (const n of ['invoice_create', 'invoice_finalize', 'invoice_record_payment', 'invoice_void']) expect(t.find((x) => x.name === n)!.annotations, n).toMatchObject({ readOnlyHint: false })
73
+ expect((t.find((x) => x.name === 'invoice_create')!.inputSchema as { required?: string[] }).required).toEqual(['customer_id', 'currency', 'lines'])
74
+ })
75
+
76
+ it('list: a status and a page; defaults to 25', async () => {
77
+ const c = await session()
78
+ expect(out(await c.callTool({ name: 'invoice_list', arguments: { status: 'finalized', limit: 5, offset: 10 } }))).toEqual({ invoices: [{ id: 'i1' }] })
79
+ expect(calls).toEqual([['list', { limit: 5, offset: 10, status: 'finalized' }]])
80
+ calls.length = 0
81
+ await c.callTool({ name: 'invoice_list', arguments: {} })
82
+ expect(calls).toEqual([['list', { limit: 25 }]])
83
+ calls.length = 0
84
+ for (const args of [{ limit: 0 }, { limit: 101 }, { status: 'open' }]) expect(await refused(c, 'invoice_list', args), JSON.stringify(args)).toBeTruthy()
85
+ expect(calls).toEqual([])
86
+ })
87
+
88
+ it('get: a miss is a tool error carrying the service\'s code', async () => {
89
+ const c = await session()
90
+ expect(out(await c.callTool({ name: 'invoice_get', arguments: { ref: 'abc' } }))).toEqual({ invoice: { id: 'i2', short_id: 'abc' } })
91
+ const r = await c.callTool({ name: 'invoice_get', arguments: { ref: 'gone' } })
92
+ expect(r.isError).toBe(true)
93
+ expect(out(r)).toEqual({ error: 'not_found', status: 404, message: 'Invoice not found' })
94
+ })
95
+
96
+ it('transactions: one invoice\'s, or the organization\'s', async () => {
97
+ const c = await session()
98
+ expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { ref: 'i1' } }))).toEqual({ transactions: [{ id: 't2' }] })
99
+ expect(out(await c.callTool({ name: 'invoice_transactions', arguments: { limit: 3 } }))).toEqual({ transactions: [{ id: 't1' }] })
100
+ expect(calls).toEqual([['invoiceTransactions', 'i1'], ['transactions', { limit: 3 }]])
101
+ })
102
+
103
+ it('create: lines in snake_case reach the client; what the API would refuse is refused here', async () => {
104
+ const c = await session()
105
+ const args = { customer_id: 'cus-1', currency: 'EUR', lines: [{ description: 'Consulting', quantity: 2.5, unit_price_cents: 15000, product_id: 'p1' }] }
106
+ expect(out(await c.callTool({ name: 'invoice_create', arguments: args })).invoice).toMatchObject({ id: 'new', customer_id: 'cus-1' })
107
+ expect(calls).toEqual([['create', args]])
108
+ calls.length = 0
109
+ for (const bad of [{}, { ...args, lines: [] }, { ...args, currency: 'EURO' }, { ...args, lines: [{ description: 'x', quantity: 0, unit_price_cents: 1 }] },
110
+ { ...args, lines: [{ description: 'x', quantity: 1, unit_price_cents: 1.5 }] }, { ...args, lines: [{ description: 'x', quantity: 1, unit_price_cents: -1 }] }, { ...args, customer_id: '' }]) {
111
+ expect(await refused(c, 'invoice_create', bad), JSON.stringify(bad)).toBeTruthy()
112
+ }
113
+ expect(calls).toEqual([])
114
+ })
115
+ it('create: an unknown customer is the service\'s error', async () => {
116
+ const c = await session({ clients: () => ({ invoice: { ...fake, create: async () => { throw new InvoiceError(404, 'customer_not_found', 'Customer not found: x') } } }) } as never)
117
+ const r = await c.callTool({ name: 'invoice_create', arguments: { customer_id: 'x', currency: 'EUR', lines: [{ description: 'a', quantity: 1, unit_price_cents: 1 }] } })
118
+ expect(r.isError).toBe(true)
119
+ expect(out(r)).toMatchObject({ error: 'customer_not_found', status: 404 })
120
+ })
121
+
122
+ it('update: the ref is split from the patch; nothing to change is refused', async () => {
123
+ const c = await session()
124
+ await c.callTool({ name: 'invoice_update', arguments: { ref: 'i1', customer_id: 'cus-2' } })
125
+ expect(calls).toEqual([['update', 'i1', { customer_id: 'cus-2' }]])
126
+ calls.length = 0
127
+ const none = await c.callTool({ name: 'invoice_update', arguments: { ref: 'i1' } })
128
+ expect(none.isError).toBe(true)
129
+ expect(out(none).error).toBe('nothing_to_update')
130
+ expect(calls).toEqual([])
131
+ })
132
+
133
+ it('finalize, record_payment, void: each calls the one client method with the rest of the arguments', async () => {
134
+ const c = await session()
135
+ await c.callTool({ name: 'invoice_finalize', arguments: { ref: 'i1', due_at: 5 } })
136
+ await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 100, method: 'bank', reference: 'R1' } })
137
+ await c.callTool({ name: 'invoice_void', arguments: { ref: 'i1', reason: 'oops' } })
138
+ expect(calls).toEqual([['finalize', 'i1', { due_at: 5 }], ['recordPayment', 'i1', { amount_cents: 100, method: 'bank', reference: 'R1' }], ['void', 'i1', 'oops']])
139
+ calls.length = 0
140
+ for (const bad of [{ ref: 'i1' }, { ref: 'i1', amount_cents: 0 }, { ref: 'i1', amount_cents: 1.5 }, { ref: 'i1', amount_cents: -5 }]) {
141
+ expect(await refused(c, 'invoice_record_payment', bad), JSON.stringify(bad)).toBeTruthy()
142
+ }
143
+ expect(calls).toEqual([])
144
+ })
145
+
146
+ it('a permission reader hides what the person may not do', async () => {
147
+ const c = await session({ permissions: async () => ['invoice.read', 'invoice.write'] })
148
+ expect((await c.listTools()).tools.map((x) => x.name)).toEqual(['invoice_list', 'invoice_get', 'invoice_transactions', 'invoice_create', 'invoice_update'])
149
+ })
150
+ })