openvibers/openvibe.finance servermcp.js

mcp.js

main 19.2 KB · 238 lines · javascript

1'use strict';
2/**
3 * Finance's MCP server, POST /mcp (plan §L.2: "all through an SDK, with Finance Experts on top … an Expert gets narrow
4 * permissions (transactions.read), never a bank login"). An agent the person allowed reads their money as them, and
5 * nothing more:
6 *
7 * - **Read, and with a write grant a little writing.** Seven tools are readOnlyHint. Four write (v0.10): import a bank's
8 * download, add a transaction, categorise, add a rule; they need the person's own sign-in or a delegated token whose
9 * scope is write (a write grant in OpenVibe Finance on the Apps page; Network lists them only then). Nothing deletes;
10 * nothing moves money. A category an agent sets is marked ('ai') and never overwrites one the person set.
11 * - **As the person, by a Bearer token only:** their own session's, or a delegated person token (SDK 0.187) that names
12 * this service, which OpenVibe.Network mints per call for a key with a grant in OpenVibe Finance (Connect, /mcp/all).
13 * Cookies are never read here, so a page elsewhere cannot use a signed-in browser. The pages and the JSON API keep
14 * refusing delegated tokens (their sign-in client does not take them).
15 * - **Both MCP eras on one endpoint** (openvibe-sdk/mcp): 2026-07-28 (stateless, _meta version) and the handshake era.
16 * - tools/list answers anyone (names and schemas only); tools/call without a person says to connect Finance.
17 *
18 * createMcp({ store, aheadFor, now }) → { tools, handler(req, res) } req.user is the person (or nobody)
19 */
20const mcp = require('openvibe-sdk/mcp');
21const { isDelegated } = require('openvibe-sdk/auth/delegated');
22const { FinanceError, CATEGORIES } = require('./store');
23const { readCsv } = require('./csv');
24const { isOfx, readOfx } = require('./ofx');
25const { findRecurring } = require('./recurring');
26const { payoff } = require('./plan');
27
28const SERVER_INFO = { name: 'openvibe-finance', title: 'OpenVibe Finance', version: require('../package.json').version };
29const INSTRUCTIONS = 'Read one person\'s money on OpenVibe Finance, as them: accounts and balances, a month by category with budgets, '
30 + 'transactions, recurring bills and income, goals and debt payoff, net worth over time, and what-if ("can I afford this?"). '
31 + 'Amounts are integer cents; months are YYYY-MM. With a write grant it can also import a bank\'s download, add a transaction, '
32 + 'categorise transactions and add a rule. Nothing here deletes anything or moves money.';
33const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
34const WRITE = (idempotent) => ({ readOnlyHint: false, destructiveHint: false, idempotentHint: idempotent, openWorldHint: false });
35const DAY = { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}$', description: 'A day, YYYY-MM-DD.' };
36const ACCOUNT = { type: 'string', maxLength: 64, description: 'The account (from accounts).' };
37const CATEGORY = { type: 'string', minLength: 1, maxLength: 60, description: `A category: ${CATEGORIES.join(', ')} (or your own).` };
38const MONTH = { type: 'string', pattern: '^\\d{4}-(0[1-9]|1[0-2])$', description: 'A month, YYYY-MM.' };
39const tool = (name, title, description, properties = {}, { required = [], annotations = READ } = {}) => ({
40 name, title, description,
41 inputSchema: { type: 'object', properties, ...(required.length ? { required } : {}), additionalProperties: false },
42 annotations: { title, ...annotations },
43});
44
45const TOOLS = [
46 tool('accounts', 'Your accounts', 'Every account with its kind, currency, balance (cents), and for a loan or card its yearly rate (basis points) and monthly payment.'),
47 tool('month', 'A month by category', 'Money in and out for a month (this month by default) by category, with each category\'s monthly budget, what is left of it or how much over. Transfers between the person\'s accounts are left out.', { month: MONTH }),
48 tool('transactions', 'Transactions', 'Transactions, newest first: date, amount (cents; negative is money out), payee, memo, category and where the category came from (none, you, rule, file). One account or all; one month or the latest.', {
49 account_id: { type: 'string', maxLength: 64, description: 'One account (from accounts); all accounts when left out.' },
50 month: MONTH, limit: { type: 'integer', minimum: 1, maximum: 500, description: 'At most this many (100 by default).' },
51 }),
52 tool('recurring', 'Recurring bills and income', 'Bills, subscriptions and regular income found in the last year: payee, cadence, typical amount, the next date, what it costs a month, and whether it is overdue.'),
53 tool('goals', 'Goals and debt', 'Goals (target, by when, how much there is) and debts (loans and cards owed, their rate and payment, when they are paid off and the interest it costs).'),
54 tool('net_worth', 'Net worth over time', 'Net worth at the end of each month since the data starts (assets, owed, net, in cents).'),
55 tool('what_if', 'What if', 'The person\'s average month (the last three, transfers left out) repeated a year ahead from what they can spend now, with an optional one-off cost ("can I afford this?") and an optional monthly change ("what if rent rises?"). Answers each month\'s money to spend with and without it, the lowest point, the first month below zero, and when a cost that does not fit yet would.', {
56 cost_cents: { type: 'integer', minimum: 0, maximum: 1e11, description: 'A one-off cost.' },
57 cost_on: { ...MONTH, description: 'The month it is paid (next month by default), within the next twelve.' },
58 change_cents: { type: 'integer', minimum: 0, maximum: 1e11, description: 'A change every month.' },
59 direction: { type: 'string', enum: ['out', 'in'], description: 'out: more going out (rent rises); in: more coming in. out by default.' },
60 from: { ...MONTH, description: 'The month the change starts (next month by default).' },
61 }),
62 // ── Writing, with a write grant (v0.10) ──
63 tool('import_statement', 'Import a bank download', 'Import a bank\'s download into one account: CSV (the columns read from its header), OFX or QFX. The same file twice, or two that overlap, add each transaction once. Answers how many were added and how many were already there.', {
64 account_id: ACCOUNT, text: { type: 'string', minLength: 1, maxLength: 4000000, description: 'The file\'s text.' },
65 }, { required: ['account_id', 'text'], annotations: WRITE(true) }),
66 tool('add_transaction', 'Add a transaction', 'Add one transaction to an account: the day, the amount in cents (negative is money out), the payee, and optionally a memo and a category.', {
67 account_id: ACCOUNT, posted_on: DAY, amount_cents: { type: 'integer', minimum: -1e11, maximum: 1e11, description: 'Cents; negative is money out.' },
68 payee: { type: 'string', minLength: 1, maxLength: 300 }, memo: { type: 'string', maxLength: 500 }, category: CATEGORY,
69 }, { required: ['account_id', 'posted_on', 'amount_cents', 'payee'], annotations: WRITE(false) }),
70 tool('categorize', 'Categorise transactions', 'Put transactions in categories (up to 200 at once). A category the person set themselves is left as it is; one an agent sets is marked as an agent\'s, for them to check.', {
71 items: { type: 'array', minItems: 1, maxItems: 200, description: '[{ transaction_id, category }]', items: { type: 'object', properties: { transaction_id: { type: 'string', maxLength: 64 }, category: CATEGORY }, required: ['transaction_id', 'category'], additionalProperties: false } },
72 }, { required: ['items'], annotations: WRITE(true) }),
73 tool('add_rule', 'Add a category rule', 'Always put a payee in a category: words of the payee (numbers in it are ignored) and the category. It applies to every uncategorised transaction now and to every import after.', {
74 match: { type: 'string', minLength: 2, maxLength: 120, description: 'Words of the payee, such as "streamflix".' }, category: CATEGORY,
75 }, { required: ['match', 'category'], annotations: WRITE(true) }),
76];
77
78function createMcp({ store, aheadFor, now = () => new Date() }) {
79 const today = () => now().toISOString().slice(0, 10);
80
81 const RUN = {
82 async accounts(me) {
83 return { accounts: (await store.accounts(me)).map((a) => ({ id: a.id, name: a.name, kind: a.kind, currency: a.currency, balance_cents: a.balance_cents, apr_bps: a.apr_bps, payment_cents: a.payment_cents, transactions: a.count, last_on: a.last_on })) };
84 },
85 async month(me, args) {
86 const m = await store.month(me, args.month || today().slice(0, 7));
87 const limit = new Map((await store.budgets(me)).map((b) => [b.category, b.monthly_cents]));
88 return {
89 month: m.month, income_cents: m.income_cents, spent_cents: m.spent_cents,
90 by_category: m.by_category.map((c) => ({ category: c.category, in_cents: c.in_cents, out_cents: c.out_cents, count: c.count,
91 ...(limit.has(c.category) ? { budget_cents: limit.get(c.category), left_cents: limit.get(c.category) - c.out_cents } : {}) })),
92 budgets_unspent: [...limit].filter(([cat]) => !m.by_category.some((c) => c.category === cat)).map(([category, cents]) => ({ category, budget_cents: cents, left_cents: cents })),
93 };
94 },
95 async transactions(me, args) {
96 const limit = args.limit || 100;
97 const ids = args.account_id ? [String(args.account_id)] : (await store.accounts(me)).map((a) => a.id);
98 if (args.account_id && !(await store.account(me, args.account_id))) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');
99 const all = [];
100 for (const id of ids) all.push(...await store.transactions(me, id, { month: args.month || null, limit }));
101 all.sort((a, b) => (a.posted_on < b.posted_on ? 1 : a.posted_on > b.posted_on ? -1 : 0));
102 return { transactions: all.slice(0, limit).map((t) => ({ id: t.id, account_id: t.account_id, posted_on: t.posted_on, amount_cents: t.amount_cents, payee: t.payee, memo: t.memo, category: t.category, category_from: t.category_from })) };
103 },
104 async recurring(me) {
105 return { recurring: findRecurring(await store.recent(me), { today: today() }).map(({ key, ...r }) => r) };
106 },
107 async goals(me) {
108 const accounts = await store.accounts(me);
109 return {
110 goals: (await store.goals(me)).map((g) => ({ name: g.name, target_cents: g.target_cents, target_on: g.target_on, have_cents: g.have_cents, tracks_account_id: g.account_id })),
111 debts: accounts.filter((a) => a.kind === 'loan' || a.kind === 'credit').map((a) => {
112 const owed = Math.max(0, -a.balance_cents);
113 const p = owed && a.apr_bps != null && a.payment_cents ? payoff({ owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents }) : null;
114 return { account_id: a.id, name: a.name, owed_cents: owed, apr_bps: a.apr_bps, payment_cents: a.payment_cents, payoff_months: p && !p.never ? p.months : null, interest_cents: p && !p.never ? p.interest_cents : null, never_paid_off: Boolean(p && p.never) };
115 }),
116 };
117 },
118 async net_worth(me) {
119 return { net_worth: (await aheadFor(me)).net_worth };
120 },
121 async import_statement(me, args) {
122 if (!(await store.account(me, args.account_id))) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');
123 const read = isOfx(args.text) ? readOfx(args.text) : readCsv(args.text);
124 if (read.problem) throw new FinanceError(422, 'finance.import.unreadable', read.problem);
125 const out = await store.importRows(me, args.account_id, read.rows);
126 return { added: out.added, already_there: out.skipped, unreadable_lines: read.skipped.length };
127 },
128 async add_transaction(me, args) {
129 const t = await store.addTransaction(me, args.account_id, { posted_on: args.posted_on, amount_cents: args.amount_cents, payee: args.payee, memo: args.memo || '', category: args.category || '' });
130 return { transaction: { id: t.id, posted_on: t.posted_on, amount_cents: t.amount_cents, payee: t.payee, category: t.category } };
131 },
132 async categorize(me, args, ctx) {
133 const out = { changed: 0, kept_yours: 0, not_found: 0 };
134 for (const it of args.items) {
135 if (!it || typeof it !== 'object' || typeof it.transaction_id !== 'string' || typeof it.category !== 'string' || !it.category.trim()) throw new FinanceError(422, 'finance.mcp.items', 'Each item is { transaction_id, category }.');
136 try { await store.setCategory(me, it.transaction_id, it.category, { from: ctx.agent ? 'ai' : 'you' }); out.changed += 1; } catch (err) {
137 if (!(err instanceof FinanceError)) throw err;
138 if (err.status === 409) out.kept_yours += 1;
139 else if (err.status === 404) out.not_found += 1;
140 else throw err;
141 }
142 }
143 return out;
144 },
145 async add_rule(me, args) {
146 const r = await store.addRule(me, { match: args.match, category: args.category });
147 return { rule: { match: r.match, category: r.category }, applied_now: r.applied };
148 },
149 async what_if(me, args) {
150 const q = {};
151 if (args.cost_cents) q.cost = (args.cost_cents / 100).toFixed(2);
152 if (args.cost_on) q.cost_on = args.cost_on;
153 if (args.change_cents) q.change = (args.change_cents / 100).toFixed(2);
154 if (args.direction) q.dir = args.direction;
155 if (args.from) q.from = args.from;
156 const a = await aheadFor(me, q);
157 if (a.error) throw new FinanceError(422, 'finance.ahead.ask', a.error);
158 if (!a.plan) return { average: a.average, plan: null, note: 'Not enough history: the months before this one have no transactions.' };
159 return { average: a.average, spendable_cents: a.spendable_cents, goals_need_cents: a.goals_need_cents, plan: a.plan };
160 },
161 };
162
163 /** The arguments against the tool's schema: only its own keys, the right types, in range. → a message or null. */
164 function badArgs(def, args) {
165 if (!args || typeof args !== 'object' || Array.isArray(args)) return 'The arguments are an object.';
166 const props = def.inputSchema.properties;
167 for (const k of def.inputSchema.required || []) if (args[k] === undefined || args[k] === null) return `${def.name} needs "${k}".`;
168 for (const [k, v] of Object.entries(args)) {
169 const p = props[k];
170 if (!p) return `${def.name} takes no "${k}".`;
171 if (p.type === 'integer' && (!Number.isSafeInteger(v) || v < (p.minimum ?? -Infinity) || v > (p.maximum ?? Infinity))) return `"${k}" is a whole number${p.maximum ? ` from ${p.minimum} to ${p.maximum}` : ''}.`;
172 if (p.type === 'array' && (!Array.isArray(v) || v.length < (p.minItems || 0) || v.length > (p.maxItems || Infinity))) return `"${k}" is a list of ${p.minItems || 0} to ${p.maxItems} items.`;
173 if (p.type === 'string' && (typeof v !== 'string' || (p.minLength && v.length < p.minLength) || (p.maxLength && v.length > p.maxLength) || (p.pattern && !new RegExp(p.pattern).test(v)) || (p.enum && !p.enum.includes(v)))) return `"${k}" is not right: ${p.description || 'see the schema'}`;
174 }
175 return null;
176 }
177
178 const asResult = (value) => ({ content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value, isError: false });
179 const asError = (message) => ({ content: [{ type: 'text', text: message }], isError: true });
180
181 async function call(req, params) {
182 const def = TOOLS.find((t) => t.name === String(params && params.name));
183 if (!def) return { error: { code: mcp.ERRORS.invalidParams, message: `No tool named ${String(params && params.name)}.` } };
184 const me = req.user && /^usr_/.test(String(req.user.subject_id || '')) ? String(req.user.subject_id) : null;
185 if (!me) return { result: asError('Finance reads your money as you: connect OpenVibe Finance (a grant on your Apps page) or call with your own sign-in.') };
186 const args = params.arguments == null ? {} : params.arguments;
187 const bad = badArgs(def, args);
188 if (bad) return { result: asError(bad) };
189 // Something acting for the person (a delegated token) writes only with a write grant; the person themselves may.
190 const agent = isDelegated(req.user);
191 const scope = agent ? String((req.user.delegated && req.user.delegated.scope) || (req.user.scope) || 'read') : 'write';
192 if (!def.annotations.readOnlyHint && scope !== 'write') return { result: asError('This changes your Finance data, and this agent may only read: give it read and write in OpenVibe Finance on your Apps page (https://openvibe.network/apps).') };
193 try { return { result: asResult(await RUN[def.name](me, args, { agent })) }; } catch (err) {
194 if (err instanceof FinanceError) return { result: asError(err.message) };
195 throw err;
196 }
197 }
198
199 async function handler(req, res) {
200 const body = req.body && typeof req.body === 'object' ? req.body : {};
201 const id = Object.prototype.hasOwnProperty.call(body, 'id') ? body.id : null;
202 const method = body.method;
203 const params = body.params && typeof body.params === 'object' ? body.params : {};
204 const reply = (result, status = 200) => res.status(status).json({ jsonrpc: '2.0', id, result });
205 const fail = (status, error) => res.status(status).json({ jsonrpc: '2.0', id, error });
206 if (body.jsonrpc !== '2.0' || typeof method !== 'string') return fail(400, { code: mcp.ERRORS.invalidRequest, message: 'A JSON-RPC 2.0 request.' });
207 const modern = mcp.requestVersion(params);
208 if (modern) {
209 const bad = mcp.checkRequest({ header: (n) => req.get(n), method, params });
210 if (bad) return fail(bad.status, bad.error);
211 }
212 if (!Object.prototype.hasOwnProperty.call(body, 'id') || method.startsWith('notifications/')) return res.status(202).end();
213 switch (method) {
214 case 'initialize':
215 return reply({ protocolVersion: mcp.legacyVersion(params.protocolVersion), capabilities: { tools: { listChanged: false } }, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS });
216 case 'server/discover':
217 return reply(mcp.discoverResult({ serverInfo: SERVER_INFO, capabilities: { tools: { listChanged: false } }, instructions: INSTRUCTIONS }));
218 case 'ping':
219 return reply(modern ? mcp.complete({}) : {});
220 case 'tools/list':
221 return reply(modern ? mcp.listResult('tools', TOOLS, { cacheScope: 'public' }) : { tools: TOOLS });
222 case 'tools/call': {
223 const out = await call(req, params);
224 if (out.error) return fail(200, out.error);
225 return reply(modern ? mcp.complete(out.result) : out.result);
226 }
227 default: {
228 const nf = mcp.methodNotFound(method);
229 return fail(nf.status, nf.error);
230 }
231 }
232 }
233
234 return { tools: TOOLS, handler };
235}
236
237module.exports = { createMcp, TOOLS };
238