@neuctra/finance-mcp 0.0.0-stage → 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/README.md +43 -2
- package/package.json +31 -4
- package/src/docs.js +458 -0
- package/src/errors.js +36 -0
- package/src/index.js +6 -0
- package/src/methods.js +139 -0
- package/src/server.js +89 -0
package/README.md
CHANGED
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @neuctra/finance-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An [MCP](https://modelcontextprotocol.io) server that tells AI assistants how to use Neuctra
|
|
4
|
+
Finance: how to record expenses and income, move money, track debts, reserve money with holds,
|
|
5
|
+
ask for approval, fix mistakes and handle errors, using the `@neuctra/finance` SDK.
|
|
6
|
+
|
|
7
|
+
It is documentation only. It never connects to a Finance account, needs no key and cannot move
|
|
8
|
+
money; the assistant uses it to write correct code for your app.
|
|
9
|
+
|
|
10
|
+
## Tools
|
|
11
|
+
|
|
12
|
+
All read-only guides. None of them connects to a Finance account or moves money.
|
|
13
|
+
|
|
14
|
+
| Tool | What it gives the AI |
|
|
15
|
+
| --- | --- |
|
|
16
|
+
| `get_setup_guide` | How it fits together, install, client, keys and permissions, testing. Call first. |
|
|
17
|
+
| `list_sdk_methods` | Every SDK method with its permission. Only these exist. Optional `group`. |
|
|
18
|
+
| `get_sdk_method` | One method: params, return value, errors, example (`expenses.record`, `income.record`...). |
|
|
19
|
+
| `get_example` | A full workflow: `record-expense`, `record-income`, `transfer-money`, `read-transactions`, `manage-debts`, `reserve-money`, `request-approval`, `fix-a-mistake`, `handle-webhooks`, `safe-retries`, `rest-api`. |
|
|
20
|
+
| `get_error_reference` | What an error code means and what to do. No code returns the whole list. |
|
|
21
|
+
|
|
22
|
+
## Setup
|
|
23
|
+
|
|
24
|
+
```json
|
|
25
|
+
{
|
|
26
|
+
"mcpServers": {
|
|
27
|
+
"neuctra-finance": {
|
|
28
|
+
"command": "node",
|
|
29
|
+
"args": ["/path/to/neuctra-finance-mcp/src/index.js"]
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Claude Code: `claude mcp add neuctra-finance -- node /path/to/neuctra-finance-mcp/src/index.js`
|
|
36
|
+
|
|
37
|
+
## Development
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm install
|
|
41
|
+
npm test
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The docs live in [src/docs.js](src/docs.js). Update them when the SDK changes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neuctra/finance-mcp",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "MCP server that teaches AI assistants how to manage expenses, income and more with the Neuctra Finance SDK.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"neuctra-finance-mcp": "./src/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"start": "node src/index.js",
|
|
16
|
+
"test": "node --test test/*.test.js"
|
|
17
|
+
},
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=18"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"neuctra",
|
|
23
|
+
"finance",
|
|
24
|
+
"mcp",
|
|
25
|
+
"model-context-protocol",
|
|
26
|
+
"ledger"
|
|
27
|
+
],
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@modelcontextprotocol/sdk": "^1.12.0",
|
|
31
|
+
"zod": "^3.25.0"
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/docs.js
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
// Neuctra Finance SDK and API guide, split into topics an AI can ask for one at a time.
|
|
2
|
+
// Source of truth: the "SDK and API reference" page of Neuctra Finance.
|
|
3
|
+
|
|
4
|
+
export const TOPICS = {
|
|
5
|
+
overview: {
|
|
6
|
+
title: "How it fits together",
|
|
7
|
+
summary: "What Neuctra Finance is and how a key, the SDK and the API relate.",
|
|
8
|
+
body: `# @neuctra/finance: how it fits together
|
|
9
|
+
|
|
10
|
+
Record where business money goes from any JavaScript app, and read it back.
|
|
11
|
+
|
|
12
|
+
1. The owner signs in to the dashboard, creates accounts and adds money. **Investments and withdrawals can only be made there**, never through the SDK.
|
|
13
|
+
2. The owner creates a key on the Integrations page and gives it to the IT team.
|
|
14
|
+
3. Your software calls the Neuctra Finance API through the SDK. The API checks the key, then records the movement in the owner's books.
|
|
15
|
+
4. **Spending stops at zero.** An account only pays out what it holds, until the owner adds more.
|
|
16
|
+
|
|
17
|
+
Rules that hold everywhere:
|
|
18
|
+
- Amounts are **major units**: \`12000\` means 12,000.00. Decimals follow the currency (2 for USD, 0 for JPY, 3 for KWD).
|
|
19
|
+
- Transactions are **never edited or deleted**. Mistakes are fixed with a reversal (topic \`reversals\`).
|
|
20
|
+
- Every write carries an idempotency key, so retries never record twice (topic \`retries\`).
|
|
21
|
+
- Use topics \`expenses\`, \`income\`, \`transfers\` for the everyday work, and \`errors\` for what to do when a call fails.`,
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
quickstart: {
|
|
25
|
+
title: "Install and connect",
|
|
26
|
+
summary: "Install the SDK and create the client.",
|
|
27
|
+
body: `# Quickstart
|
|
28
|
+
|
|
29
|
+
Install. Zero dependencies; Node.js 18+, browsers, React and Next.js.
|
|
30
|
+
|
|
31
|
+
\`\`\`bash
|
|
32
|
+
npm install @neuctra/finance
|
|
33
|
+
\`\`\`
|
|
34
|
+
|
|
35
|
+
Keep the API address and key in environment variables, never in source control:
|
|
36
|
+
|
|
37
|
+
\`\`\`
|
|
38
|
+
NEUCTRA_FINANCE_URL=https://finance-api.yourcompany.com
|
|
39
|
+
NEUCTRA_FINANCE_KEY=nf_sk_...
|
|
40
|
+
\`\`\`
|
|
41
|
+
|
|
42
|
+
\`\`\`js
|
|
43
|
+
import { NeuctraFinance } from "@neuctra/finance";
|
|
44
|
+
|
|
45
|
+
export const finance = new NeuctraFinance({
|
|
46
|
+
serverUrl: process.env.NEUCTRA_FINANCE_URL,
|
|
47
|
+
apiKey: process.env.NEUCTRA_FINANCE_KEY,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const { business, key } = await finance.me();
|
|
51
|
+
console.log(\`Connected to \${business.name} as \${key.name}\`);
|
|
52
|
+
\`\`\`
|
|
53
|
+
|
|
54
|
+
Constructor options: \`serverUrl\` and \`apiKey\` (required), \`timeoutMs\` (default 15000), \`retries\` (default 2), \`fetch\`.
|
|
55
|
+
Call \`finance.me()\` first to see which permissions and accounts the key has.`,
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
keys: {
|
|
59
|
+
title: "Keys and permissions",
|
|
60
|
+
summary: "nf_sk_ vs nf_pk_ keys and the permission list.",
|
|
61
|
+
body: `# Keys and permissions
|
|
62
|
+
|
|
63
|
+
- \`nf_sk_\` **server keys** are for back-end code and are **refused from browsers** (the SDK throws if one is used in a browser).
|
|
64
|
+
- \`nf_pk_\` **public keys** only work from the websites listed on the key. Give them the fewest permissions and a per-transaction limit.
|
|
65
|
+
|
|
66
|
+
| Permission | Allows |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| \`read\` | Read accounts, balances, transactions, debts and the summary. |
|
|
69
|
+
| \`expenses:write\` | Record expenses. Refused when the account would go below zero. |
|
|
70
|
+
| \`income:write\` | Record income into an account. |
|
|
71
|
+
| \`transfers:write\` | Move money between two accounts of the business. |
|
|
72
|
+
| \`debts:write\` | Create debts and record payments or collections. |
|
|
73
|
+
| \`holds:write\` | Reserve money, then capture or release it. **Server keys only.** |
|
|
74
|
+
| \`requests:write\` | Ask for approval to spend above an account's approval line. |
|
|
75
|
+
| \`reversals:write\` | Undo a transaction with an opposite entry. |
|
|
76
|
+
|
|
77
|
+
A key can also be limited to some accounts or a max amount. Revoking a key in the dashboard stops it within 30 seconds.
|
|
78
|
+
A \`MISSING_SCOPE\` error means the key lacks the permission the call needs.`,
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
expenses: {
|
|
82
|
+
title: "Record an expense",
|
|
83
|
+
summary: "How to record spending (finance.expenses.record), its fields, and checking funds first.",
|
|
84
|
+
body: `# Record an expense
|
|
85
|
+
|
|
86
|
+
\`\`\`js
|
|
87
|
+
const { transaction, account } = await finance.expenses.record({
|
|
88
|
+
accountId: "acc_3f9a1c", // copy it from the account page
|
|
89
|
+
amount: 12000, // major units: 12000 means 12,000.00
|
|
90
|
+
category: "Rent",
|
|
91
|
+
description: "November office rent",
|
|
92
|
+
reference: "RENT-2026-11", // your own invoice or order id
|
|
93
|
+
counterparty: "Blue Tower Properties",
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
transaction.balanceAfter; // what is left in the account
|
|
97
|
+
account.spent; // everything spent from it so far
|
|
98
|
+
\`\`\`
|
|
99
|
+
|
|
100
|
+
Needs \`expenses:write\`. Result: \`{ transaction, account, replayed }\`.
|
|
101
|
+
|
|
102
|
+
| Field | Required | What it is |
|
|
103
|
+
| --- | --- | --- |
|
|
104
|
+
| accountId | Yes | The account to take the money from. |
|
|
105
|
+
| amount | Yes | Positive number in the business currency, with its decimals. |
|
|
106
|
+
| category | No | Groups spending, e.g. Rent, Ads, Salaries. Some businesses require a known category (\`CATEGORY_REQUIRED\`). |
|
|
107
|
+
| description | No | What the money was for. |
|
|
108
|
+
| reference | No | Your own id: invoice, order or payroll run. |
|
|
109
|
+
| counterparty | No | Who was paid. |
|
|
110
|
+
| occurredAt | No | When it happened, if not now. ISO date or date-time. Not before the books' lock date (\`PERIOD_LOCKED\`). |
|
|
111
|
+
| metadata | No | Small JSON object, up to 2,000 characters. |
|
|
112
|
+
| idempotencyKey | No | Generated for you. Pass your own to make retries across restarts safe. |
|
|
113
|
+
|
|
114
|
+
## When an account runs out
|
|
115
|
+
|
|
116
|
+
An expense larger than the balance is refused and **nothing is deducted**. Same while the owner has frozen the account.
|
|
117
|
+
|
|
118
|
+
\`\`\`js
|
|
119
|
+
import { NeuctraFinanceError } from "@neuctra/finance";
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
await finance.expenses.record({ accountId, amount: 6000, category: "Stock" });
|
|
123
|
+
} catch (err) {
|
|
124
|
+
if (err instanceof NeuctraFinanceError && err.isInsufficientFunds) {
|
|
125
|
+
const { balance, requested, shortBy } = err.details; // nothing was deducted
|
|
126
|
+
await alertOwner(\`Short by \${shortBy}. Please add money.\`);
|
|
127
|
+
} else if (err.code === "ACCOUNT_FROZEN") {
|
|
128
|
+
await alertOwner("Spending from this account is paused.");
|
|
129
|
+
} else {
|
|
130
|
+
throw err;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Or check first, for a friendlier UI (held money counts as spent):
|
|
135
|
+
if (!(await finance.accounts.canSpend(accountId, 6000))) showMessage("Not enough left.");
|
|
136
|
+
\`\`\`
|
|
137
|
+
|
|
138
|
+
If the amount is above the account's approval line you get \`APPROVAL_REQUIRED\`: see topic \`approvals\`.`,
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
income: {
|
|
142
|
+
title: "Record income",
|
|
143
|
+
summary: "How to record money received (finance.income.record).",
|
|
144
|
+
body: `# Record income
|
|
145
|
+
|
|
146
|
+
Needs \`income:write\`. Same fields as an expense (accountId, amount, category, description, reference, counterparty, occurredAt, metadata, idempotencyKey).
|
|
147
|
+
|
|
148
|
+
\`\`\`js
|
|
149
|
+
await finance.income.record({
|
|
150
|
+
accountId: "acc_sales01",
|
|
151
|
+
amount: 4200,
|
|
152
|
+
category: "Online sales",
|
|
153
|
+
reference: "ORDER-88213",
|
|
154
|
+
});
|
|
155
|
+
\`\`\`
|
|
156
|
+
|
|
157
|
+
Result: \`{ transaction, account, replayed }\`. The account's balance goes up by \`amount\`.
|
|
158
|
+
Use your order or invoice number as \`reference\` and \`idempotencyKey\` so a re-run never records a sale twice.
|
|
159
|
+
|
|
160
|
+
Money the owner puts in as capital ("investment") and withdrawals can only be made in the dashboard, not with income.record.`,
|
|
161
|
+
},
|
|
162
|
+
|
|
163
|
+
transfers: {
|
|
164
|
+
title: "Transfer between accounts",
|
|
165
|
+
summary: "Moving money between two accounts (finance.transfers.create).",
|
|
166
|
+
body: `# Transfers
|
|
167
|
+
|
|
168
|
+
Needs \`transfers:write\`. Moves money between two accounts of the same business.
|
|
169
|
+
|
|
170
|
+
\`\`\`js
|
|
171
|
+
await finance.transfers.create({
|
|
172
|
+
fromAccountId: "acc_sales01",
|
|
173
|
+
toAccountId: "acc_payroll",
|
|
174
|
+
amount: 3000,
|
|
175
|
+
description: "Move sales to payroll",
|
|
176
|
+
});
|
|
177
|
+
\`\`\`
|
|
178
|
+
|
|
179
|
+
Result: \`{ transferId, from, to, transactions: [out, in], replayed }\`. The source must hold the amount (\`INSUFFICIENT_FUNDS\` otherwise) and is subject to the approval line (\`APPROVAL_REQUIRED\`). Reversing either side undoes both.`,
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
transactions: {
|
|
183
|
+
title: "See where money went",
|
|
184
|
+
summary: "Reading transactions, paging, and the business summary.",
|
|
185
|
+
body: `# See where money went
|
|
186
|
+
|
|
187
|
+
Needs \`read\`. Every transaction keeps its category, reference, the key that recorded it and the balance right after it.
|
|
188
|
+
|
|
189
|
+
\`\`\`js
|
|
190
|
+
// One account, newest first. Follows every page for you.
|
|
191
|
+
for await (const t of finance.transactions.iterate({ accountId, kind: "expense" })) {
|
|
192
|
+
console.log(t.occurredAt, t.category, t.amount, t.source.keyName ?? "Dashboard");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// One page at a time
|
|
196
|
+
const page = await finance.transactions.list({ accountId, limit: 50 });
|
|
197
|
+
const next = await finance.transactions.list({ accountId, cursor: page.nextCursor });
|
|
198
|
+
|
|
199
|
+
await finance.transactions.get(transactionId);
|
|
200
|
+
|
|
201
|
+
// The whole business at a glance
|
|
202
|
+
const summary = await finance.summary();
|
|
203
|
+
summary.balance; // available across every account
|
|
204
|
+
summary.invested; // everything the owner put in
|
|
205
|
+
summary.spent; // everything recorded as expenses
|
|
206
|
+
summary.lowAccounts; // ids of accounts that are empty or running low
|
|
207
|
+
\`\`\`
|
|
208
|
+
|
|
209
|
+
\`transactions.list\` query: \`accountId\`, \`kind\`, \`limit\` (max 100), \`cursor\`. Kinds: investment, income, loan_received, debt_collected, transfer_in, expense, withdrawal, loan_given, debt_paid, transfer_out, reversal.
|
|
210
|
+
|
|
211
|
+
Accounts: \`finance.accounts.list()\` and \`finance.accounts.get(id)\` return \`balance\`, \`held\` (reserved by holds) and \`available\` (balance minus held).`,
|
|
212
|
+
},
|
|
213
|
+
|
|
214
|
+
debts: {
|
|
215
|
+
title: "Debts",
|
|
216
|
+
summary: "Payables (owed by you) and receivables (owed to you): create and pay.",
|
|
217
|
+
body: `# Debts
|
|
218
|
+
|
|
219
|
+
\`payable\` = money the business owes. \`receivable\` = money owed to the business. Needs \`debts:write\`. Payments move real money, so paying a debt needs the account to cover it.
|
|
220
|
+
|
|
221
|
+
\`\`\`js
|
|
222
|
+
// A bank loan paid into an account: the balance goes up, the debt is tracked.
|
|
223
|
+
const { debt } = await finance.debts.create({
|
|
224
|
+
direction: "payable", // you owe
|
|
225
|
+
counterparty: "City Bank",
|
|
226
|
+
amount: 50000,
|
|
227
|
+
accountId: "acc_operations", // optional: where the cash landed
|
|
228
|
+
dueDate: "2027-06-30",
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// Each installment leaves the account and lowers what is outstanding.
|
|
232
|
+
await finance.debts.pay(debt.id, { amount: 5000, description: "Installment 1" });
|
|
233
|
+
|
|
234
|
+
// Money a customer owes you, collected later into an account.
|
|
235
|
+
const invoice = await finance.debts.create({
|
|
236
|
+
direction: "receivable",
|
|
237
|
+
counterparty: "Globex Ltd",
|
|
238
|
+
amount: 7500,
|
|
239
|
+
});
|
|
240
|
+
await finance.debts.pay(invoice.debt.id, { amount: 7500, accountId: "acc_sales01" });
|
|
241
|
+
|
|
242
|
+
await finance.debts.list({ status: "open", direction: "payable" });
|
|
243
|
+
await finance.debts.get(debtId);
|
|
244
|
+
\`\`\`
|
|
245
|
+
|
|
246
|
+
Paying more than what is outstanding fails with \`OVERPAYMENT\`. A debt has \`principal\`, \`outstanding\`, \`paid\`, \`status\` (open | settled | cancelled), \`dueDate\` and \`isOverdue\`.`,
|
|
247
|
+
},
|
|
248
|
+
|
|
249
|
+
holds: {
|
|
250
|
+
title: "Reserve money first (holds)",
|
|
251
|
+
summary: "Authorize, capture or void a hold so money is reserved before paying.",
|
|
252
|
+
body: `# Reserve money first (holds)
|
|
253
|
+
|
|
254
|
+
Recording a spend after it happened cannot stop it. A hold reserves the money **before** you pay: the account's \`available\` drops at once, so nothing else can spend it. Capture what you really paid (the held amount or less), or void it. Forgotten holds are released when they expire (7 days by default, up to 30).
|
|
255
|
+
|
|
256
|
+
Needs \`holds:write\`. **Server keys only.**
|
|
257
|
+
|
|
258
|
+
\`\`\`js
|
|
259
|
+
// 1. Reserve the money before you pay.
|
|
260
|
+
const { hold } = await finance.holds.authorize({
|
|
261
|
+
accountId: "acc_8f2c...",
|
|
262
|
+
amount: 800,
|
|
263
|
+
description: "Coffee beans order",
|
|
264
|
+
expiresInMinutes: 60 * 24, // a day
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
// 2. Pay your supplier, then record what it really cost (800 or less).
|
|
268
|
+
const { transaction, account } = await finance.holds.capture(hold.id, { amount: 750 });
|
|
269
|
+
|
|
270
|
+
// Or, if the order fell through, give the money back.
|
|
271
|
+
await finance.holds.void(hold.id);
|
|
272
|
+
|
|
273
|
+
await finance.holds.get(hold.id);
|
|
274
|
+
\`\`\`
|
|
275
|
+
|
|
276
|
+
Capturing twice returns the first result. Capturing more than held fails with \`CAPTURE_TOO_LARGE\`; an ended hold fails with \`HOLD_EXPIRED\` / \`HOLD_NOT_ACTIVE\`.`,
|
|
277
|
+
},
|
|
278
|
+
|
|
279
|
+
approvals: {
|
|
280
|
+
title: "Big spends need approval",
|
|
281
|
+
summary: "APPROVAL_REQUIRED and how to send a spend request.",
|
|
282
|
+
body: `# Big spends need approval
|
|
283
|
+
|
|
284
|
+
An owner can set an **approval line** on an account. Above it, integrations get \`APPROVAL_REQUIRED\` for expenses, transfers, loans and holds alike. Send a spend request instead; when an approver accepts it, the money is held for you to capture. Nobody can approve their own request, including requests sent with a key they created.
|
|
285
|
+
|
|
286
|
+
Needs \`requests:write\`.
|
|
287
|
+
|
|
288
|
+
\`\`\`js
|
|
289
|
+
try {
|
|
290
|
+
await finance.expenses.record({ accountId, amount: 2500, category: "Equipment" });
|
|
291
|
+
} catch (err) {
|
|
292
|
+
if (!err.isApprovalRequired) throw err;
|
|
293
|
+
const request = await finance.spendRequests.create({
|
|
294
|
+
accountId,
|
|
295
|
+
amount: 2500,
|
|
296
|
+
description: "Espresso machine", // required
|
|
297
|
+
receiptUrl: "https://supplier.example/quote/77",
|
|
298
|
+
});
|
|
299
|
+
// Later (or when the spend_request.approved webhook arrives):
|
|
300
|
+
const decided = await finance.spendRequests.get(request.id);
|
|
301
|
+
if (decided.status === "approved") await finance.holds.capture(decided.holdId);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
await finance.spendRequests.cancel(request.id); // withdraw a pending request
|
|
305
|
+
\`\`\`
|
|
306
|
+
|
|
307
|
+
Status: pending | approved | denied | cancelled | expired. \`holdId\` is set once approved. If denied, \`reason\` says why.`,
|
|
308
|
+
},
|
|
309
|
+
|
|
310
|
+
reversals: {
|
|
311
|
+
title: "Fixing mistakes",
|
|
312
|
+
summary: "Undo a transaction with an opposite entry.",
|
|
313
|
+
body: `# Fixing mistakes
|
|
314
|
+
|
|
315
|
+
Transactions are **never edited or deleted**. A reversal adds an opposite entry dated today, undoes both sides of a transfer, and reopens a debt if it reverses a payment. Taking back money that was already spent is refused. Needs \`reversals:write\`.
|
|
316
|
+
|
|
317
|
+
\`\`\`js
|
|
318
|
+
await finance.transactions.reverse("txn_51ab...", { reason: "Charged twice by the POS" });
|
|
319
|
+
// -> { reversals: Transaction[], accounts: Account[] }
|
|
320
|
+
\`\`\`
|
|
321
|
+
|
|
322
|
+
\`reason\` is required.`,
|
|
323
|
+
},
|
|
324
|
+
|
|
325
|
+
webhooks: {
|
|
326
|
+
title: "Webhooks",
|
|
327
|
+
summary: "Receive and verify signed events.",
|
|
328
|
+
body: `# Webhooks
|
|
329
|
+
|
|
330
|
+
Add an https address on the Integrations page and choose events. Each POST carries \`Neuctra-Signature: t=…,v1=…\`, an HMAC-SHA256 of \`t.body\` with your \`nf_whsec_\` secret. Verify with \`verifyWebhook()\`, answer any 2xx, and ignore event ids you already handled. Each delivery is sent once; resend a failed one from the delivery log.
|
|
331
|
+
|
|
332
|
+
\`\`\`js
|
|
333
|
+
import express from "express";
|
|
334
|
+
import { verifyWebhook } from "@neuctra/finance";
|
|
335
|
+
|
|
336
|
+
const app = express();
|
|
337
|
+
// Keep the raw body: the signature is over the exact bytes sent.
|
|
338
|
+
app.post("/neuctra", express.text({ type: "application/json" }), async (req, res) => {
|
|
339
|
+
try {
|
|
340
|
+
const event = await verifyWebhook(req.get("Neuctra-Signature"), req.body, process.env.NEUCTRA_WEBHOOK_SECRET);
|
|
341
|
+
if (await alreadyHandled(event.id)) return res.sendStatus(200);
|
|
342
|
+
if (event.type === "account.low_balance") alertTheTeam(event.data);
|
|
343
|
+
res.sendStatus(200);
|
|
344
|
+
} catch {
|
|
345
|
+
res.sendStatus(400);
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
\`\`\`
|
|
349
|
+
|
|
350
|
+
Event types: transaction.created, transaction.reversed, hold.authorized, hold.captured, hold.voided, spend_request.created, spend_request.approved, spend_request.denied, account.low_balance, budget.threshold.`,
|
|
351
|
+
},
|
|
352
|
+
|
|
353
|
+
retries: {
|
|
354
|
+
title: "Retries and idempotency",
|
|
355
|
+
summary: "Why an expense is never recorded twice, and how to pass your own key.",
|
|
356
|
+
body: `# Retries and idempotency
|
|
357
|
+
|
|
358
|
+
Every write carries an idempotency key. The SDK makes one and reuses it when it retries a timeout, a 502/503/504 or \`BUSY\`, so an expense is never recorded twice. If your own job may run again after a crash, pass a key that stays the same for that piece of work. A repeat returns the original transaction with \`replayed: true\`.
|
|
359
|
+
|
|
360
|
+
\`\`\`js
|
|
361
|
+
await finance.expenses.record({
|
|
362
|
+
accountId,
|
|
363
|
+
amount: 899,
|
|
364
|
+
reference: "PO-2041",
|
|
365
|
+
idempotencyKey: "po-2041", // stable for this purchase order
|
|
366
|
+
});
|
|
367
|
+
\`\`\`
|
|
368
|
+
|
|
369
|
+
Reusing a key for a different request fails with \`IDEMPOTENCY_MISMATCH\`.
|
|
370
|
+
Rate limit: per key per minute (\`RATE_LIMITED\`, wait for \`Retry-After\`). The owner's plan also caps API requests per month (\`PLAN_LIMIT\`, \`err.isPlanLimit\`), resetting on the 1st (UTC).`,
|
|
371
|
+
},
|
|
372
|
+
|
|
373
|
+
errors: {
|
|
374
|
+
title: "Error codes",
|
|
375
|
+
summary: "Every error code, what it means and what to do.",
|
|
376
|
+
body: `# Errors
|
|
377
|
+
|
|
378
|
+
Errors are \`NeuctraFinanceError\` with \`status\`, \`code\`, \`message\`, \`hint\` and \`details\`. Helpers: \`err.isInsufficientFunds\`, \`err.isApprovalRequired\`, \`err.isPlanLimit\`.
|
|
379
|
+
|
|
380
|
+
| Code | Status | Meaning / what to do |
|
|
381
|
+
| --- | --- | --- |
|
|
382
|
+
| INSUFFICIENT_FUNDS | 402 | Account cannot cover the amount. \`details\`: balance, requested, shortBy. Nothing was deducted. |
|
|
383
|
+
| ACCOUNT_FROZEN | 423 | Owner paused spending from this account. |
|
|
384
|
+
| ACCOUNT_CLOSED | 409 | Account no longer accepts money in or out. |
|
|
385
|
+
| OVERPAYMENT | 422 | More than the outstanding amount was paid on a debt. |
|
|
386
|
+
| VALIDATION_ERROR | 400 | A field is missing or malformed. The message names it. |
|
|
387
|
+
| NOT_FOUND | 404 | Account, transaction or debt does not exist in this business. |
|
|
388
|
+
| INVALID_API_KEY / KEY_REVOKED | 401 | Key is wrong or revoked. |
|
|
389
|
+
| MISSING_SCOPE | 403 | Key lacks this permission. |
|
|
390
|
+
| OWNER_NOT_VERIFIED | 403 | Owner has not verified their email yet. |
|
|
391
|
+
| ACCOUNT_NOT_ALLOWED / AMOUNT_LIMIT | 403 | Key is limited to other accounts or a lower amount. |
|
|
392
|
+
| SERVER_KEY_IN_BROWSER / ORIGIN_NOT_ALLOWED | 403 | Server key used in a browser, or public key from an unlisted site. |
|
|
393
|
+
| APPROVAL_REQUIRED | 403 | Above the approval line. Send a spend request (topic approvals). |
|
|
394
|
+
| BUDGET_EXCEEDED / CATEGORY_REQUIRED | 422 / 400 | Category's monthly budget used up, or a known category is required. |
|
|
395
|
+
| PERIOD_LOCKED | 409 | Books are closed for that date. Use a later date. |
|
|
396
|
+
| IDEMPOTENCY_MISMATCH | 422 | Key already used for a different request. |
|
|
397
|
+
| HOLD_EXPIRED / HOLD_NOT_ACTIVE / CAPTURE_TOO_LARGE | 409 / 422 | Hold ended, or capture exceeds the held amount. |
|
|
398
|
+
| KEY_EXPIRED / IP_NOT_ALLOWED | 401 / 403 | Key's end date passed, or used from an address not on its list. |
|
|
399
|
+
| RATE_LIMITED | 429 | Too many requests. Wait for Retry-After. |
|
|
400
|
+
| PLAN_LIMIT | 429 | Owner's monthly API allowance used up; resets on the 1st (UTC). |
|
|
401
|
+
| BUSY / UPSTREAM_ERROR | 409 / 502 | Temporary. The SDK retries with the same idempotency key. |`,
|
|
402
|
+
},
|
|
403
|
+
|
|
404
|
+
"rest-api": {
|
|
405
|
+
title: "REST API",
|
|
406
|
+
summary: "Calling the API directly without the SDK; the endpoint table.",
|
|
407
|
+
body: `# REST API
|
|
408
|
+
|
|
409
|
+
Not on JavaScript? Call the API directly with \`Authorization: Bearer nf_...\`. Amounts are in major units. Errors come back as \`{ error: { code, message, hint, details } }\`.
|
|
410
|
+
|
|
411
|
+
\`\`\`bash
|
|
412
|
+
curl -X POST https://finance-api.yourcompany.com/v1/expenses \\
|
|
413
|
+
-H "Authorization: Bearer $NEUCTRA_FINANCE_KEY" \\
|
|
414
|
+
-H "Content-Type: application/json" \\
|
|
415
|
+
-H "Idempotency-Key: po-2041" \\
|
|
416
|
+
-d '{"accountId":"acc_3f9a1c","amount":899,"category":"Supplies"}'
|
|
417
|
+
\`\`\`
|
|
418
|
+
|
|
419
|
+
| Method | Path | Permission | Does |
|
|
420
|
+
| --- | --- | --- | --- |
|
|
421
|
+
| GET | /v1/me | any key | Business and this key's permissions. |
|
|
422
|
+
| GET | /v1/summary | read | Balances, invested, spent, debts, low accounts. |
|
|
423
|
+
| GET | /v1/accounts | read | Every account this key can use. |
|
|
424
|
+
| GET | /v1/accounts/:id | read | One account with its balance. |
|
|
425
|
+
| GET | /v1/transactions | read | Newest first. Query: accountId, kind, limit, cursor. |
|
|
426
|
+
| GET | /v1/transactions/:id | read | One transaction. |
|
|
427
|
+
| POST | /v1/expenses | expenses:write | Take money out of an account. |
|
|
428
|
+
| POST | /v1/income | income:write | Put money into an account. |
|
|
429
|
+
| POST | /v1/transfers | transfers:write | fromAccountId, toAccountId, amount. |
|
|
430
|
+
| GET | /v1/debts | read | Query: status, direction. |
|
|
431
|
+
| GET | /v1/debts/:id | read | One debt. |
|
|
432
|
+
| POST | /v1/debts | debts:write | direction, counterparty, amount, accountId, dueDate. |
|
|
433
|
+
| POST | /v1/debts/:id/payments | debts:write | amount, accountId. |
|
|
434
|
+
| POST | /v1/holds | holds:write | accountId, amount, expiresInMinutes. |
|
|
435
|
+
| GET | /v1/holds/:id | read | One hold. |
|
|
436
|
+
| POST | /v1/holds/:id/capture | holds:write | amount (optional, at most the held amount). |
|
|
437
|
+
| POST | /v1/holds/:id/void | holds:write | Give the money back. |
|
|
438
|
+
| POST | /v1/spend-requests | requests:write | accountId, amount, description, receiptUrl. |
|
|
439
|
+
| GET | /v1/spend-requests/:id | read | Status, and holdId once approved. |
|
|
440
|
+
| POST | /v1/spend-requests/:id/cancel | requests:write | Withdraw a pending request. |
|
|
441
|
+
| POST | /v1/transactions/:id/reverse | reversals:write | reason. |
|
|
442
|
+
| GET | /v1/openapi.json | none | Full OpenAPI 3.1 description. |`,
|
|
443
|
+
},
|
|
444
|
+
|
|
445
|
+
testing: {
|
|
446
|
+
title: "Testing safely",
|
|
447
|
+
summary: "Use a separate test business.",
|
|
448
|
+
body: `# Testing safely
|
|
449
|
+
|
|
450
|
+
Create a separate business, for example "Acme (test)", with its own accounts and keys, and point your development setup at it. Businesses are free and nothing in one can touch another. Delete it when you are done. The full API description is at \`/v1/openapi.json\` for code generators and Postman.`,
|
|
451
|
+
},
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
export const TOPIC_IDS = Object.keys(TOPICS);
|
|
455
|
+
|
|
456
|
+
export function topicIndex() {
|
|
457
|
+
return TOPIC_IDS.map((id) => `- \`${id}\`: ${TOPICS[id].summary}`).join("\n");
|
|
458
|
+
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export const ERRORS = [
|
|
2
|
+
["INSUFFICIENT_FUNDS", 402, "The account cannot cover the amount. Nothing was deducted. details: balance, held, available, requested, shortBy.", "Tell the owner to add money, or lower the amount. Check first with accounts.canSpend."],
|
|
3
|
+
["ACCOUNT_FROZEN", 423, "The owner paused spending from this account.", "Alert the owner; do not retry."],
|
|
4
|
+
["ACCOUNT_CLOSED", 409, "The account no longer accepts money in or out.", "Use another account."],
|
|
5
|
+
["OVERPAYMENT", 422, "More than the outstanding amount was paid on a debt.", "Pay at most debt.outstanding."],
|
|
6
|
+
["VALIDATION_ERROR", 400, "A field is missing or malformed. The message names it.", "Fix the field and resend."],
|
|
7
|
+
["NOT_FOUND", 404, "The account, transaction, debt, hold or request does not exist in this business.", "Check the id and that the key belongs to this business."],
|
|
8
|
+
["INVALID_API_KEY", 401, "The key is wrong.", "Check NEUCTRA_FINANCE_KEY."],
|
|
9
|
+
["KEY_REVOKED", 401, "The owner revoked the key.", "Create a new key in the dashboard."],
|
|
10
|
+
["KEY_EXPIRED", 401, "The key's end date passed.", "Create a new key."],
|
|
11
|
+
["MISSING_SCOPE", 403, "The key was not given this permission.", "Add the permission to the key (see keys topic), or use another key."],
|
|
12
|
+
["OWNER_NOT_VERIFIED", 403, "The business owner has not verified their email yet.", "Keys work once the owner verifies."],
|
|
13
|
+
["ACCOUNT_NOT_ALLOWED", 403, "The key is limited to other accounts.", "Use an allowed account or widen the key."],
|
|
14
|
+
["AMOUNT_LIMIT", 403, "The amount is above the key's per-transaction limit.", "Lower the amount or raise the limit."],
|
|
15
|
+
["SERVER_KEY_IN_BROWSER", 403, "An nf_sk_ key was used in a browser.", "Use a server key only in back-end code; use nf_pk_ in browsers."],
|
|
16
|
+
["ORIGIN_NOT_ALLOWED", 403, "A public key was used from a site not on its list.", "Add the website to the key."],
|
|
17
|
+
["IP_NOT_ALLOWED", 403, "The key was used from an address not on its list.", "Add the address or use another key."],
|
|
18
|
+
["APPROVAL_REQUIRED", 403, "The amount is above the account's approval line (applies to expenses, transfers, loans and holds).", "Send finance.spendRequests.create, then capture the hold once approved."],
|
|
19
|
+
["BUDGET_EXCEEDED", 422, "The category's monthly budget is used up.", "Ask the owner to raise the budget, or use another category."],
|
|
20
|
+
["CATEGORY_REQUIRED", 400, "The business requires a known category.", "Pass an existing category."],
|
|
21
|
+
["PERIOD_LOCKED", 409, "The owner closed the books for that date.", "Use a later occurredAt."],
|
|
22
|
+
["IDEMPOTENCY_MISMATCH", 422, "The idempotency key was already used for a different request.", "Use a new key for different work."],
|
|
23
|
+
["HOLD_EXPIRED", 409, "The hold ended.", "Authorize a new hold."],
|
|
24
|
+
["HOLD_NOT_ACTIVE", 409, "The hold was already captured or voided.", "Read it with holds.get."],
|
|
25
|
+
["CAPTURE_TOO_LARGE", 422, "Tried to capture more than was held.", "Capture the held amount or less."],
|
|
26
|
+
["RATE_LIMITED", 429, "Too many requests per minute for this key.", "Wait for the Retry-After header."],
|
|
27
|
+
["PLAN_LIMIT", 429, "The owner's monthly API allowance is used up. err.isPlanLimit.", "Resets on the 1st (UTC); the owner can upgrade."],
|
|
28
|
+
["BUSY", 409, "Temporary. The SDK retries with the same idempotency key.", "Usually nothing to do."],
|
|
29
|
+
["UPSTREAM_ERROR", 502, "Temporary upstream failure. The SDK retries.", "Usually nothing to do."],
|
|
30
|
+
["INVALID_SIGNATURE", 0, "verifyWebhook: signature missing, malformed, wrong, or older than the tolerance.", "Pass the raw body string and the nf_whsec_ secret; answer 400."],
|
|
31
|
+
["NETWORK_ERROR", 0, "The SDK could not reach serverUrl.", "Check serverUrl and that the API is running."],
|
|
32
|
+
].map(([code, status, meaning, fix]) => ({ code, status, meaning, fix }));
|
|
33
|
+
|
|
34
|
+
export function formatError(e) {
|
|
35
|
+
return `## ${e.code}${e.status ? ` (HTTP ${e.status})` : ""}\n${e.meaning}\n**What to do:** ${e.fix}`;
|
|
36
|
+
}
|
package/src/index.js
ADDED
package/src/methods.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Every @neuctra/finance SDK method, so an AI can look one up instead of guessing.
|
|
2
|
+
// If a method is not listed here, it does not exist.
|
|
3
|
+
|
|
4
|
+
const MOVE = "category?, description?, reference?, counterparty?, occurredAt?, metadata?, idempotencyKey?";
|
|
5
|
+
|
|
6
|
+
export const METHODS = [
|
|
7
|
+
{ name: "me", call: "finance.me()", scope: "any key", group: "Connect",
|
|
8
|
+
does: "The business and this key's permissions (scopes, allowed accounts, max amount). Call it first.",
|
|
9
|
+
params: "none", returns: "{ business, key: { id, name, type, scopes, accountIds, maxAmount } }", errors: "INVALID_API_KEY, KEY_REVOKED, KEY_EXPIRED",
|
|
10
|
+
example: `const { business, key } = await finance.me();\nconsole.log(\`Connected to \${business.name} as \${key.name}\`);` },
|
|
11
|
+
{ name: "summary", call: "finance.summary()", scope: "read", group: "Read",
|
|
12
|
+
does: "Business totals: balance, invested, spent, owed, owedToYou, lowAccounts.",
|
|
13
|
+
params: "none", returns: "Summary { balance, invested, spent, totalIn, totalOut, owed, owedToYou, netPosition, accounts, lowAccounts, openDebts, currency }", errors: "MISSING_SCOPE",
|
|
14
|
+
example: `const s = await finance.summary();\ns.balance; s.spent; s.lowAccounts;` },
|
|
15
|
+
{ name: "accounts.list", call: "finance.accounts.list()", scope: "read", group: "Read",
|
|
16
|
+
does: "Every account this key can use, with balance, held and available.",
|
|
17
|
+
params: "none", returns: "Account[]", errors: "MISSING_SCOPE",
|
|
18
|
+
example: `const accounts = await finance.accounts.list();` },
|
|
19
|
+
{ name: "accounts.get", call: "finance.accounts.get(accountId)", scope: "read", group: "Read",
|
|
20
|
+
does: "One account: balance, held (reserved by holds), available (balance minus held), approvalAbove, spent, invested.",
|
|
21
|
+
params: "accountId (required)", returns: "Account", errors: "NOT_FOUND, ACCOUNT_NOT_ALLOWED",
|
|
22
|
+
example: `const account = await finance.accounts.get("acc_3f9a1c");\naccount.available;` },
|
|
23
|
+
{ name: "accounts.canSpend", call: "finance.accounts.canSpend(accountId, amount)", scope: "read", group: "Read",
|
|
24
|
+
does: "True when the account is active and at least `amount` is available. Held money counts as spent. Use before recording an expense.",
|
|
25
|
+
params: "accountId, amount", returns: "boolean", errors: "NOT_FOUND",
|
|
26
|
+
example: `if (!(await finance.accounts.canSpend(accountId, 6000))) showMessage("Not enough left.");` },
|
|
27
|
+
|
|
28
|
+
{ name: "expenses.record", call: "finance.expenses.record(input)", scope: "expenses:write", group: "Money",
|
|
29
|
+
does: "Deducts money from an account (an expense). Refused and nothing deducted if the balance is too low, the account is frozen, or the amount is above the approval line.",
|
|
30
|
+
params: `accountId (required), amount (required, major units), ${MOVE}`, returns: "{ transaction, account, replayed }",
|
|
31
|
+
errors: "INSUFFICIENT_FUNDS, ACCOUNT_FROZEN, ACCOUNT_CLOSED, APPROVAL_REQUIRED, BUDGET_EXCEEDED, CATEGORY_REQUIRED, PERIOD_LOCKED, MISSING_SCOPE, AMOUNT_LIMIT",
|
|
32
|
+
example: `const { transaction, account } = await finance.expenses.record({\n accountId: "acc_3f9a1c",\n amount: 12000,\n category: "Rent",\n description: "November office rent",\n reference: "RENT-2026-11",\n counterparty: "Blue Tower Properties",\n});\ntransaction.balanceAfter;` },
|
|
33
|
+
{ name: "income.record", call: "finance.income.record(input)", scope: "income:write", group: "Money",
|
|
34
|
+
does: "Adds money received to an account (a sale, a payment). Owner capital (investment) and withdrawals are dashboard-only.",
|
|
35
|
+
params: `accountId (required), amount (required), ${MOVE}`, returns: "{ transaction, account, replayed }",
|
|
36
|
+
errors: "ACCOUNT_CLOSED, PERIOD_LOCKED, MISSING_SCOPE, VALIDATION_ERROR",
|
|
37
|
+
example: `await finance.income.record({\n accountId: "acc_sales01",\n amount: 4200,\n category: "Online sales",\n reference: "ORDER-88213",\n});` },
|
|
38
|
+
{ name: "transfers.create", call: "finance.transfers.create(input)", scope: "transfers:write", group: "Money",
|
|
39
|
+
does: "Moves money between two accounts of the same business. Reversing either side undoes both.",
|
|
40
|
+
params: `fromAccountId, toAccountId, amount (all required), ${MOVE}`, returns: "{ transferId, from, to, transactions: [out, in], replayed }",
|
|
41
|
+
errors: "INSUFFICIENT_FUNDS, APPROVAL_REQUIRED, ACCOUNT_FROZEN, ACCOUNT_CLOSED, MISSING_SCOPE",
|
|
42
|
+
example: `await finance.transfers.create({\n fromAccountId: "acc_sales01",\n toAccountId: "acc_payroll",\n amount: 3000,\n description: "Move sales to payroll",\n});` },
|
|
43
|
+
{ name: "transactions.reverse", call: "finance.transactions.reverse(transactionId, { reason })", scope: "reversals:write", group: "Money",
|
|
44
|
+
does: "Undoes a transaction with an opposite entry dated today. Never edits or deletes. Undoes both sides of a transfer; reopens a debt if it reverses a payment. Money already spent cannot be taken back.",
|
|
45
|
+
params: "transactionId (required), reason (required)", returns: "{ reversals: Transaction[], accounts: Account[] }", errors: "NOT_FOUND, MISSING_SCOPE, INSUFFICIENT_FUNDS, PERIOD_LOCKED",
|
|
46
|
+
example: `await finance.transactions.reverse("txn_51ab...", { reason: "Charged twice by the POS" });` },
|
|
47
|
+
|
|
48
|
+
{ name: "transactions.list", call: "finance.transactions.list(query?)", scope: "read", group: "Read",
|
|
49
|
+
does: "One page of transactions, newest first.",
|
|
50
|
+
params: "accountId?, kind?, limit? (max 100), cursor?", returns: "{ data: Transaction[], nextCursor }", errors: "MISSING_SCOPE",
|
|
51
|
+
example: `const page = await finance.transactions.list({ accountId, limit: 50 });\nconst next = await finance.transactions.list({ accountId, cursor: page.nextCursor });` },
|
|
52
|
+
{ name: "transactions.get", call: "finance.transactions.get(transactionId)", scope: "read", group: "Read",
|
|
53
|
+
does: "One transaction with category, reference, the key that recorded it and balanceAfter.",
|
|
54
|
+
params: "transactionId (required)", returns: "Transaction", errors: "NOT_FOUND",
|
|
55
|
+
example: `const t = await finance.transactions.get("txn_51ab...");` },
|
|
56
|
+
{ name: "transactions.iterate", call: "finance.transactions.iterate(query?)", scope: "read", group: "Read",
|
|
57
|
+
does: "Async iterator that walks every page for you.",
|
|
58
|
+
params: "accountId?, kind?", returns: "AsyncGenerator<Transaction>", errors: "MISSING_SCOPE",
|
|
59
|
+
example: `for await (const t of finance.transactions.iterate({ accountId, kind: "expense" })) {\n console.log(t.occurredAt, t.category, t.amount);\n}` },
|
|
60
|
+
|
|
61
|
+
{ name: "debts.list", call: "finance.debts.list(query?)", scope: "read", group: "Debts",
|
|
62
|
+
does: "Debts, filtered. payable = the business owes; receivable = the business is owed.",
|
|
63
|
+
params: "status? (open|settled|cancelled), direction? (payable|receivable)", returns: "Debt[]", errors: "MISSING_SCOPE",
|
|
64
|
+
example: `const open = await finance.debts.list({ status: "open", direction: "payable" });` },
|
|
65
|
+
{ name: "debts.get", call: "finance.debts.get(debtId)", scope: "read", group: "Debts",
|
|
66
|
+
does: "One debt: principal, outstanding, paid, status, dueDate, isOverdue.",
|
|
67
|
+
params: "debtId (required)", returns: "Debt", errors: "NOT_FOUND", example: `const debt = await finance.debts.get(debtId);` },
|
|
68
|
+
{ name: "debts.create", call: "finance.debts.create(input)", scope: "debts:write", group: "Debts",
|
|
69
|
+
does: "Opens a debt. With accountId the cash moves too: a loan lands in (payable) or leaves (receivable) that account.",
|
|
70
|
+
params: "direction (payable|receivable), counterparty, amount (required); accountId?, dueDate?, notes?, description?, idempotencyKey?", returns: "{ debt, transaction | null, account | null, replayed }",
|
|
71
|
+
errors: "INSUFFICIENT_FUNDS (receivable with accountId), MISSING_SCOPE, VALIDATION_ERROR",
|
|
72
|
+
example: `const { debt } = await finance.debts.create({\n direction: "payable",\n counterparty: "City Bank",\n amount: 50000,\n accountId: "acc_operations",\n dueDate: "2027-06-30",\n});` },
|
|
73
|
+
{ name: "debts.pay", call: "finance.debts.pay(debtId, input)", scope: "debts:write", group: "Debts",
|
|
74
|
+
does: "Pays a payable or collects a receivable, fully or in part. accountId defaults to the account the debt was opened with.",
|
|
75
|
+
params: `debtId (required), amount (required), accountId?, ${MOVE}`, returns: "{ debt, transaction, account, replayed }", errors: "OVERPAYMENT, INSUFFICIENT_FUNDS, NOT_FOUND, MISSING_SCOPE",
|
|
76
|
+
example: `await finance.debts.pay(debt.id, { amount: 5000, description: "Installment 1" });` },
|
|
77
|
+
|
|
78
|
+
{ name: "holds.authorize", call: "finance.holds.authorize(input)", scope: "holds:write (server keys only)", group: "Holds",
|
|
79
|
+
does: "Reserves money before you pay. Available drops at once so nothing else can spend it. Expires after 7 days by default (max 30).",
|
|
80
|
+
params: "accountId, amount (required); expiresInMinutes? (default 10080, max 43200), category?, description?, reference?, counterparty?, idempotencyKey?", returns: "{ hold, replayed }",
|
|
81
|
+
errors: "INSUFFICIENT_FUNDS, APPROVAL_REQUIRED, ACCOUNT_FROZEN, MISSING_SCOPE",
|
|
82
|
+
example: `const { hold } = await finance.holds.authorize({\n accountId: "acc_8f2c...",\n amount: 800,\n description: "Coffee beans order",\n expiresInMinutes: 60 * 24,\n});` },
|
|
83
|
+
{ name: "holds.get", call: "finance.holds.get(holdId)", scope: "read", group: "Holds",
|
|
84
|
+
does: "One hold: status (authorized|captured|voided|expired), amount, captured, expiresAt.",
|
|
85
|
+
params: "holdId (required)", returns: "Hold", errors: "NOT_FOUND", example: `const hold = await finance.holds.get(holdId);` },
|
|
86
|
+
{ name: "holds.capture", call: "finance.holds.capture(holdId, input?)", scope: "holds:write", group: "Holds",
|
|
87
|
+
does: "Spends the held amount, or less. Capturing twice returns the first result.",
|
|
88
|
+
params: `holdId (required), amount? (default the held amount, never more), ${MOVE}`, returns: "{ hold, transaction, account, replayed }",
|
|
89
|
+
errors: "CAPTURE_TOO_LARGE, HOLD_EXPIRED, HOLD_NOT_ACTIVE, MISSING_SCOPE",
|
|
90
|
+
example: `const { transaction } = await finance.holds.capture(hold.id, { amount: 750 });` },
|
|
91
|
+
{ name: "holds.void", call: "finance.holds.void(holdId)", scope: "holds:write", group: "Holds",
|
|
92
|
+
does: "Gives the held money back without spending it.",
|
|
93
|
+
params: "holdId (required)", returns: "Hold", errors: "HOLD_NOT_ACTIVE, NOT_FOUND, MISSING_SCOPE", example: `await finance.holds.void(hold.id);` },
|
|
94
|
+
|
|
95
|
+
{ name: "spendRequests.create", call: "finance.spendRequests.create(input)", scope: "requests:write", group: "Approvals",
|
|
96
|
+
does: "Asks for approval to spend above an account's approval line. When approved, the money is held and request.holdId is set. Nobody can approve their own request.",
|
|
97
|
+
params: "accountId, amount, description (all required); category?, counterparty?, reference?, receiptUrl?, idempotencyKey?", returns: "SpendRequest { id, status, holdId, reason, ... }",
|
|
98
|
+
errors: "VALIDATION_ERROR, ACCOUNT_NOT_ALLOWED, MISSING_SCOPE",
|
|
99
|
+
example: `const request = await finance.spendRequests.create({\n accountId,\n amount: 2500,\n description: "Espresso machine",\n receiptUrl: "https://supplier.example/quote/77",\n});` },
|
|
100
|
+
{ name: "spendRequests.get", call: "finance.spendRequests.get(requestId)", scope: "read", group: "Approvals",
|
|
101
|
+
does: "Status: pending | approved | denied | cancelled | expired. holdId once approved; reason if denied.",
|
|
102
|
+
params: "requestId (required)", returns: "SpendRequest", errors: "NOT_FOUND",
|
|
103
|
+
example: `const d = await finance.spendRequests.get(request.id);\nif (d.status === "approved") await finance.holds.capture(d.holdId);` },
|
|
104
|
+
{ name: "spendRequests.cancel", call: "finance.spendRequests.cancel(requestId)", scope: "requests:write", group: "Approvals",
|
|
105
|
+
does: "Withdraws a pending request.", params: "requestId (required)", returns: "SpendRequest", errors: "NOT_FOUND, MISSING_SCOPE",
|
|
106
|
+
example: `await finance.spendRequests.cancel(request.id);` },
|
|
107
|
+
|
|
108
|
+
{ name: "verifyWebhook", call: "verifyWebhook(signatureHeader, rawBody, secret, options?)", scope: "n/a (uses your nf_whsec_ secret)", group: "Webhooks",
|
|
109
|
+
does: "Checks the Neuctra-Signature header against the raw body and returns the event. Throws INVALID_SIGNATURE if it does not match or is older than toleranceSeconds (default 300).",
|
|
110
|
+
params: "signatureHeader, rawBody (exact string, before JSON parsing), secret, { toleranceSeconds? }", returns: "WebhookEvent { id, type, createdAt, businessId, data }", errors: "INVALID_SIGNATURE",
|
|
111
|
+
example: `import { verifyWebhook } from "@neuctra/finance";\nconst event = await verifyWebhook(req.get("Neuctra-Signature"), req.body, process.env.NEUCTRA_WEBHOOK_SECRET);` },
|
|
112
|
+
];
|
|
113
|
+
|
|
114
|
+
export const methodNames = () => METHODS.map((m) => m.name);
|
|
115
|
+
|
|
116
|
+
export function findMethod(input) {
|
|
117
|
+
const q = String(input || "").trim().toLowerCase().replace(/^finance\./, "").replace(/\(.*$/, "");
|
|
118
|
+
return METHODS.find((m) => m.name.toLowerCase() === q);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function formatMethod(m) {
|
|
122
|
+
return [
|
|
123
|
+
`# ${m.call}`,
|
|
124
|
+
"",
|
|
125
|
+
m.does,
|
|
126
|
+
"",
|
|
127
|
+
`- **Permission:** ${m.scope}`,
|
|
128
|
+
`- **Params:** ${m.params}`,
|
|
129
|
+
`- **Returns:** ${m.returns}`,
|
|
130
|
+
`- **Can fail with:** ${m.errors}`,
|
|
131
|
+
m.group === "Money" || m.group === "Debts" || m.group === "Holds"
|
|
132
|
+
? "- Amounts are major units (1500.5 = 1,500.50). Writes carry an idempotency key automatically."
|
|
133
|
+
: "",
|
|
134
|
+
"",
|
|
135
|
+
"```js",
|
|
136
|
+
m.example,
|
|
137
|
+
"```",
|
|
138
|
+
].filter((l) => l !== "").join("\n");
|
|
139
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { TOPICS } from "./docs.js";
|
|
4
|
+
import { METHODS, findMethod, formatMethod, methodNames } from "./methods.js";
|
|
5
|
+
import { ERRORS, formatError } from "./errors.js";
|
|
6
|
+
|
|
7
|
+
const INSTRUCTIONS = `Neuctra Finance records where business money goes (expenses, income, transfers, debts, holds, approvals) through the @neuctra/finance SDK. Do not write Finance code from memory. Call get_setup_guide once, then list_sdk_methods, then get_sdk_method for each call you will write. Use get_example for a complete workflow (record an expense, record income...) and get_error_reference when a call fails. If a method is not listed, it does not exist.`;
|
|
8
|
+
|
|
9
|
+
const READ = { readOnlyHint: true, openWorldHint: false };
|
|
10
|
+
const text = (t) => ({ content: [{ type: "text", text: t }] });
|
|
11
|
+
const err = (t) => ({ isError: true, content: [{ type: "text", text: t }] });
|
|
12
|
+
|
|
13
|
+
// Workflow examples, each backed by a docs topic.
|
|
14
|
+
const EXAMPLES = {
|
|
15
|
+
"record-expense": "expenses",
|
|
16
|
+
"record-income": "income",
|
|
17
|
+
"transfer-money": "transfers",
|
|
18
|
+
"read-transactions": "transactions",
|
|
19
|
+
"manage-debts": "debts",
|
|
20
|
+
"reserve-money": "holds",
|
|
21
|
+
"request-approval": "approvals",
|
|
22
|
+
"fix-a-mistake": "reversals",
|
|
23
|
+
"handle-webhooks": "webhooks",
|
|
24
|
+
"safe-retries": "retries",
|
|
25
|
+
"rest-api": "rest-api",
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
/** An MCP server of guide tools that teach an AI how to use Neuctra Finance. */
|
|
29
|
+
export function createServer() {
|
|
30
|
+
const server = new McpServer({ name: "neuctra-finance", version: "1.0.0" }, { instructions: INSTRUCTIONS });
|
|
31
|
+
const tool = (name, title, description, inputSchema, run) =>
|
|
32
|
+
server.registerTool(name, { title, description, inputSchema, annotations: { title, ...READ } }, async (a) => run(a));
|
|
33
|
+
|
|
34
|
+
tool(
|
|
35
|
+
"get_setup_guide",
|
|
36
|
+
"Neuctra Finance setup guide",
|
|
37
|
+
"Start here. How Neuctra Finance fits together, installing @neuctra/finance, creating the client, keys and permissions, and testing safely. Call once before writing any Finance code.",
|
|
38
|
+
{},
|
|
39
|
+
() => text([TOPICS.overview.body, TOPICS.quickstart.body, TOPICS.keys.body, TOPICS.testing.body].join("\n\n---\n\n")),
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
tool(
|
|
43
|
+
"list_sdk_methods",
|
|
44
|
+
"List SDK methods",
|
|
45
|
+
"Every @neuctra/finance method with the permission it needs and what it does. Only these exist.",
|
|
46
|
+
{ group: z.enum(["Connect", "Read", "Money", "Debts", "Holds", "Approvals", "Webhooks"]).optional().describe("Limit to one group.") },
|
|
47
|
+
({ group }) => {
|
|
48
|
+
const list = METHODS.filter((m) => !group || m.group === group);
|
|
49
|
+
const out = list.map((m) => `- \`${m.call}\` [${m.scope}]: ${m.does.split(". ")[0].replace(/\.$/, "")}.`);
|
|
50
|
+
return text(`# @neuctra/finance methods\n\n${out.join("\n")}\n\nUse get_sdk_method for params, return value, errors and an example.`);
|
|
51
|
+
},
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
tool(
|
|
55
|
+
"get_sdk_method",
|
|
56
|
+
"Get SDK method",
|
|
57
|
+
"Full detail for one method: permission, params, return value, errors it can raise and an example. Example names: expenses.record, income.record, transfers.create, holds.capture.",
|
|
58
|
+
{ method: z.string().min(1).describe(`Method name. One of: ${methodNames().join(", ")}`) },
|
|
59
|
+
({ method }) => {
|
|
60
|
+
const m = findMethod(method);
|
|
61
|
+
return m ? text(formatMethod(m)) : err(`No method "${method}". Methods:\n${methodNames().map((n) => `- ${n}`).join("\n")}`);
|
|
62
|
+
},
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
tool(
|
|
66
|
+
"get_example",
|
|
67
|
+
"Get workflow example",
|
|
68
|
+
`A complete, correct example for a task, including handling the failure cases. Examples: ${Object.keys(EXAMPLES).join(", ")}.`,
|
|
69
|
+
{ example: z.string().min(1).describe(`One of: ${Object.keys(EXAMPLES).join(", ")}`) },
|
|
70
|
+
({ example }) => {
|
|
71
|
+
const topic = EXAMPLES[String(example).trim().toLowerCase()];
|
|
72
|
+
return topic ? text(TOPICS[topic].body) : err(`No example "${example}". Examples:\n${Object.keys(EXAMPLES).map((n) => `- ${n}`).join("\n")}`);
|
|
73
|
+
},
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
tool(
|
|
77
|
+
"get_error_reference",
|
|
78
|
+
"Neuctra Finance error codes",
|
|
79
|
+
"What an error code means and what to do about it. Omit `code` for the full list.",
|
|
80
|
+
{ code: z.string().optional().describe("e.g. INSUFFICIENT_FUNDS, APPROVAL_REQUIRED") },
|
|
81
|
+
({ code }) => {
|
|
82
|
+
if (!code) return text(`# Error codes\n\nErrors are NeuctraFinanceError with status, code, message, hint and details.\n\n${ERRORS.map(formatError).join("\n\n")}`);
|
|
83
|
+
const e = ERRORS.find((x) => x.code === code.trim().toUpperCase());
|
|
84
|
+
return e ? text(formatError(e)) : err(`Unknown code "${code}". Codes: ${ERRORS.map((x) => x.code).join(", ")}`);
|
|
85
|
+
},
|
|
86
|
+
);
|
|
87
|
+
|
|
88
|
+
return server;
|
|
89
|
+
}
|