openvibers/openvibe.finance Commits
Agents may import, add and categorise, with a write grant (v0.10) (#10)
Changes
@@@ -10,7 +10,7 @@ to connect.- **No money moves.** It reads and plans; it never pays, transfers or cancels anything.- **Yours to take.** Download everything as one JSON file, or delete everything, at `/data`.--## What it does today (v0.9)++## What it does today (v0.10)- Accounts (checking, savings, credit card, cash, loan, investments) with an opening balance and a running balance.- Transactions typed in, or imported from a bank's download:@@@ -45,8 +45,10 @@ OpenVibe's money Experts on Actor (Budget coach, Can I afford it?, Debt planner,person allows Actor in OpenVibe Finance on their Apps page; the home page links them.`POST https://openvibe.finance/mcp` is an MCP server (both eras: the 2026-07-28 stateless protocol and the handshake--one) with seven tools, every one read only: `accounts`, `month`, `transactions`, `recurring`, `goals`, `net_worth`,--`what_if`. Amounts are integer cents; months are `YYYY-MM`.++one). Seven tools read: `accounts`, `month`, `transactions`, `recurring`, `goals`, `net_worth`, `what_if`. Four write,++with the person's own sign-in or a write grant (v0.10): `import_statement` (CSV, OFX or QFX text), `add_transaction`,++`categorize` (up to 200; a category an agent sets is marked "agent" on the page and never overwrites one the person++set), `add_rule`. Nothing deletes; nothing moves money. Amounts are integer cents; months are `YYYY-MM`.- Anyone may list the tools. A call reads the person from a **Bearer token only**, never a cookie: their own sign-in,or a delegated person token naming `finance` (openvibe-sdk 0.187), which OpenVibe.Network mints per call for a keynnew file mode 100644@@@ -0,0 +1,8 @@++-- phase: expand++-- A category an agent set (plan §L.2: "every category says whether it came from the provider, you, a rule or AI"):++-- category_from 'ai', written only through /mcp by something the person allowed to write (a delegated token with a++-- write grant in OpenVibe Finance). It never overwrites one the person set themselves ('you'). Older code never writes++-- it and reads it as any other origin.++ALTER TABLE finance_transactions DROP CONSTRAINT IF EXISTS finance_transactions_category_from_check;++ALTER TABLE finance_transactions ADD CONSTRAINT finance_transactions_category_from_check++ CHECK (category_from IN ('none', 'you', 'rule', 'file', 'ai'));@@@ -1,12 +1,12 @@{"name": "openvibe-finance",-- "version": "0.9.0",++ "version": "0.10.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "openvibe-finance",-- "version": "0.9.0",++ "version": "0.10.0","license": "AGPL-3.0-only","dependencies": {"@electric-sql/pglite": "^0.5.8",@@@ -1,6 +1,6 @@{"name": "openvibe-finance",-- "version": "0.9.0",++ "version": "0.10.0","private": true,"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you","main": "server/index.js",@@@ -176,3 +176,5 @@ html[data-ov-motion="off"] .fin-result { animation: none; }.fin-expert:hover { border-color: var(--accent, #5b8cff); }.fin-expert:active { transform: scale(.98); }html[data-ov-motion="off"] .fin-expert { transition: none; }++/* A category an agent set (v0.10): marked, so it is easy to check and change. */++.fin-by-agent { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 12px; color: var(--accent, #5b8cff); border: 1px solid color-mix(in srgb, var(--accent, #5b8cff) 45%, transparent); }@@@ -51,7 +51,7 @@ function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvibconst finMcp = require('./mcp').createMcp({ store, aheadFor: (me, q) => aheadFor(me, q), now });const bearerOnly = (req, _res, next) => { if (!/^Bearer\s+\S/i.test(String(req.get('authorization') || ''))) { delete req.headers.cookie; req.user = undefined; } next(); };const mcpWho = mcpAuth || auth;-- app.post('/mcp', express.json({ limit: '64kb' }), bearerOnly, (req, res, next) => (mcpWho && /^Bearer\s/i.test(String(req.get('authorization') || '')) ? mcpWho.optionalAuth()(req, res, next) : next()),++ app.post('/mcp', express.json({ limit: '5mb' }), bearerOnly, (req, res, next) => (mcpWho && /^Bearer\s/i.test(String(req.get('authorization') || '')) ? mcpWho.optionalAuth()(req, res, next) : next()),(req, res, next) => { res.set('Cache-Control', 'private, no-store'); Promise.resolve(finMcp.handler(req, res)).catch(next); });app.all('/mcp', (_req, res) => res.status(405).set('Allow', 'POST').json({ error: 'POST a JSON-RPC request.' }));app.use(auth ? auth.optionalAuth() : (_req, _res, next) => next());@@@ -4,7 +4,10 @@* permissions (transactions.read), never a bank login"). An agent the person allowed reads their money as them, and* nothing more:*-- * - **Read only.** Every tool is readOnlyHint; none writes, imports, deletes or moves money. "No money moves."++ * - **Read, and with a write grant a little writing.** Seven tools are readOnlyHint. Four write (v0.10): import a bank's++ * download, add a transaction, categorise, add a rule; they need the person's own sign-in or a delegated token whose++ * scope is write (a write grant in OpenVibe Finance on the Apps page; Network lists them only then). Nothing deletes;++ * nothing moves money. A category an agent sets is marked ('ai') and never overwrites one the person set.* - **As the person, by a Bearer token only:** their own session's, or a delegated person token (SDK 0.187) that names* this service, which OpenVibe.Network mints per call for a key with a grant in OpenVibe Finance (Connect, /mcp/all).* Cookies are never read here, so a page elsewhere cannot use a signed-in browser. The pages and the JSON API keep@@@ -15,20 +18,28 @@* createMcp({ store, aheadFor, now }) → { tools, handler(req, res) } req.user is the person (or nobody)*/const mcp = require('openvibe-sdk/mcp');--const { FinanceError } = require('./store');++const { isDelegated } = require('openvibe-sdk/auth/delegated');++const { FinanceError, CATEGORIES } = require('./store');++const { readCsv } = require('./csv');++const { isOfx, readOfx } = require('./ofx');const { findRecurring } = require('./recurring');const { payoff } = require('./plan');const SERVER_INFO = { name: 'openvibe-finance', title: 'OpenVibe Finance', version: require('../package.json').version };const INSTRUCTIONS = 'Read one person\'s money on OpenVibe Finance, as them: accounts and balances, a month by category with budgets, '+ 'transactions, recurring bills and income, goals and debt payoff, net worth over time, and what-if ("can I afford this?"). '-- + 'Amounts are integer cents; months are YYYY-MM. Read only: nothing here moves money or changes anything.';++ + 'Amounts are integer cents; months are YYYY-MM. With a write grant it can also import a bank\'s download, add a transaction, '++ + 'categorise transactions and add a rule. Nothing here deletes anything or moves money.';const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };++const WRITE = (idempotent) => ({ readOnlyHint: false, destructiveHint: false, idempotentHint: idempotent, openWorldHint: false });++const DAY = { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}$', description: 'A day, YYYY-MM-DD.' };++const ACCOUNT = { type: 'string', maxLength: 64, description: 'The account (from accounts).' };++const CATEGORY = { type: 'string', minLength: 1, maxLength: 60, description: `A category: ${CATEGORIES.join(', ')} (or your own).` };const MONTH = { type: 'string', pattern: '^\\d{4}-(0[1-9]|1[0-2])$', description: 'A month, YYYY-MM.' };--const tool = (name, title, description, properties = {}) => ({++const tool = (name, title, description, properties = {}, { required = [], annotations = READ } = {}) => ({name, title, description,-- inputSchema: { type: 'object', properties, additionalProperties: false },-- annotations: { title, ...READ },++ inputSchema: { type: 'object', properties, ...(required.length ? { required } : {}), additionalProperties: false },++ annotations: { title, ...annotations },});const TOOLS = [@@@ -48,6 +59,20 @@ const TOOLS = [direction: { type: 'string', enum: ['out', 'in'], description: 'out: more going out (rent rises); in: more coming in. out by default.' },from: { ...MONTH, description: 'The month the change starts (next month by default).' },}),++ // ── Writing, with a write grant (v0.10) ──++ 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.', {++ account_id: ACCOUNT, text: { type: 'string', minLength: 1, maxLength: 4000000, description: 'The file\'s text.' },++ }, { required: ['account_id', 'text'], annotations: WRITE(true) }),++ 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.', {++ account_id: ACCOUNT, posted_on: DAY, amount_cents: { type: 'integer', minimum: -1e11, maximum: 1e11, description: 'Cents; negative is money out.' },++ payee: { type: 'string', minLength: 1, maxLength: 300 }, memo: { type: 'string', maxLength: 500 }, category: CATEGORY,++ }, { required: ['account_id', 'posted_on', 'amount_cents', 'payee'], annotations: WRITE(false) }),++ 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.', {++ 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 } },++ }, { required: ['items'], annotations: WRITE(true) }),++ 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.', {++ match: { type: 'string', minLength: 2, maxLength: 120, description: 'Words of the payee, such as "streamflix".' }, category: CATEGORY,++ }, { required: ['match', 'category'], annotations: WRITE(true) }),];function createMcp({ store, aheadFor, now = () => new Date() }) {@@@ -93,6 +118,34 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {async net_worth(me) {return { net_worth: (await aheadFor(me)).net_worth };},++ async import_statement(me, args) {++ if (!(await store.account(me, args.account_id))) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');++ const read = isOfx(args.text) ? readOfx(args.text) : readCsv(args.text);++ if (read.problem) throw new FinanceError(422, 'finance.import.unreadable', read.problem);++ const out = await store.importRows(me, args.account_id, read.rows);++ return { added: out.added, already_there: out.skipped, unreadable_lines: read.skipped.length };++ },++ async add_transaction(me, args) {++ 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 || '' });++ return { transaction: { id: t.id, posted_on: t.posted_on, amount_cents: t.amount_cents, payee: t.payee, category: t.category } };++ },++ async categorize(me, args, ctx) {++ const out = { changed: 0, kept_yours: 0, not_found: 0 };++ for (const it of args.items) {++ 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 }.');++ try { await store.setCategory(me, it.transaction_id, it.category, { from: ctx.agent ? 'ai' : 'you' }); out.changed += 1; } catch (err) {++ if (!(err instanceof FinanceError)) throw err;++ if (err.status === 409) out.kept_yours += 1;++ else if (err.status === 404) out.not_found += 1;++ else throw err;++ }++ }++ return out;++ },++ async add_rule(me, args) {++ const r = await store.addRule(me, { match: args.match, category: args.category });++ return { rule: { match: r.match, category: r.category }, applied_now: r.applied };++ },async what_if(me, args) {const q = {};if (args.cost_cents) q.cost = (args.cost_cents / 100).toFixed(2);@@@ -111,11 +164,13 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {function badArgs(def, args) {if (!args || typeof args !== 'object' || Array.isArray(args)) return 'The arguments are an object.';const props = def.inputSchema.properties;++ for (const k of def.inputSchema.required || []) if (args[k] === undefined || args[k] === null) return `${def.name} needs "${k}".`;for (const [k, v] of Object.entries(args)) {const p = props[k];if (!p) return `${def.name} takes no "${k}".`;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}` : ''}.`;-- if (p.type === 'string' && (typeof v !== 'string' || (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'}`;++ 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.`;++ 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'}`;}return null;}@@@ -131,7 +186,11 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {const args = params.arguments == null ? {} : params.arguments;const bad = badArgs(def, args);if (bad) return { result: asError(bad) };-- try { return { result: asResult(await RUN[def.name](me, args)) }; } catch (err) {++ // Something acting for the person (a delegated token) writes only with a write grant; the person themselves may.++ const agent = isDelegated(req.user);++ const scope = agent ? String((req.user.delegated && req.user.delegated.scope) || (req.user.scope) || 'read') : 'write';++ 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).') };++ try { return { result: asResult(await RUN[def.name](me, args, { agent })) }; } catch (err) {if (err instanceof FinanceError) return { result: asError(err.message) };throw err;}@@@ -10,7 +10,8 @@* addAccount(owner, { name, kind, currency, opening_cents })* transactions(owner, accountId, { month }) → [{ id, posted_on, amount_cents, payee, memo, category, category_from }]* addTransaction(owner, accountId, { posted_on, amount_cents, payee, memo, category })-- * setCategory(owner, id, category) a correction: a new revision, category_from 'you'++ * setCategory(owner, id, category, { from }) a correction: a new revision, category_from 'you' (or 'ai': an agent the++ * person allowed to write; it never overwrites one they set themselves)* removeTransaction(owner, id)* importRows(owner, accountId, rows) → { import_id, read, added, skipped } (the same row twice is one)* month(owner, 'YYYY-MM') → { month, income_cents, spent_cents, by_category: [{ category, cents, count }] }@@@ -131,12 +132,17 @@ function createStore({ db, vault }) {return open(owner, await db.one('SELECT * FROM finance_transactions WHERE id = $1', [id]));}-- async function setCategory(owner, id, category) {++ async function setCategory(owner, id, category, { from = 'you' } = {}) {own(owner);const c = cleanCategory(category);-- const n = await db.exec(`UPDATE finance_transactions SET category = $3, category_from = 'you', revision = revision + 1, updated_at = now()-- WHERE id = $1 AND owner = $2`, [String(id || ''), owner, c]);-- if (!n) fail(404, 'finance.transaction.not_found', 'No such transaction of yours.');++ const by = from === 'ai' ? 'ai' : 'you';++ const n = await db.exec(`UPDATE finance_transactions SET category = $3, category_from = $4, revision = revision + 1, updated_at = now()++ WHERE id = $1 AND owner = $2 AND ($4 = 'you' OR category_from <> 'you')`, [String(id || ''), owner, c, by]);++ if (!n) {++ const row = await db.maybe('SELECT category_from FROM finance_transactions WHERE id = $1 AND owner = $2', [String(id || ''), owner]);++ if (!row) fail(404, 'finance.transaction.not_found', 'No such transaction of yours.');++ fail(409, 'finance.transaction.yours', 'You set this category yourself: an agent leaves it as it is.');++ }return open(owner, await db.one('SELECT * FROM finance_transactions WHERE id = $1', [String(id)]));}@@@ -262,7 +262,7 @@ function accountPage({ account, balance, txns, month, o = {} }) {const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;const row = (t) => `<li class="fin-txn"><span class="fin-txn-date">${esc(t.posted_on.slice(5))}</span><span class="fin-txn-what"><b>${esc(t.payee || 'No payee')}</b>${t.memo ? `<small>${esc(t.memo)}</small>` : ''}--<form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category"><input name="category" list="fin-cats" value="${esc(t.category)}" aria-label="Category" maxlength="60">${t.payee ? `<label class="fin-always" title="Every transaction from ${esc(t.payee)} goes here, now and in future imports"><input type="checkbox" name="always" value="yes"><span>Always</span></label>` : ''}<button type="submit" class="fin-mini">Save</button></form>${t.category_from === 'rule' ? '<small class="fin-by-rule">by a rule</small>' : ''}</span>++<form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category">${t.category_from === 'ai' ? '<span class="fin-by-agent" title="An agent you allowed set this category. Change it and it is yours.">agent</span>' : ''}<input name="category" list="fin-cats" value="${esc(t.category)}" aria-label="Category" maxlength="60">${t.payee ? `<label class="fin-always" title="Every transaction from ${esc(t.payee)} goes here, now and in future imports"><input type="checkbox" name="always" value="yes"><span>Always</span></label>` : ''}<button type="submit" class="fin-mini">Save</button></form>${t.category_from === 'rule' ? '<small class="fin-by-rule">by a rule</small>' : ''}</span><span class="fin-txn-amount${t.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(t.amount_cents, account.currency))}</span></li>`;const today = new Date().toISOString().slice(0, 10);return page({@@@ -27,10 +27,10 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';if (u) req.user = req.get('x-test-delegated') ? { subject_id: u, typ: 'delegated', delegated: { by: 'key_1', scope: 'read', services: ['finance'] } } : { subject_id: u };next();} };-- // /mcp's sign-in: "Bearer person:<subject>" or "Bearer delegated:<subject>"; anything else is nobody.++ // /mcp's sign-in: "Bearer person:<subject>", "Bearer delegated:<subject>" (a read grant) or "Bearer delegated-write:<subject>".const mcpAuth = { optionalAuth: () => (req, _res, next) => {-- const m = /^Bearer (person|delegated):(\S+)$/.exec(String(req.get('authorization') || ''));-- if (m) req.user = m[1] === 'delegated' ? { subject_id: m[2], typ: 'delegated', delegated: { by: 'key_1', scope: 'read', services: ['finance'] } } : { subject_id: m[2] };++ const m = /^Bearer (person|delegated|delegated-write):(\S+)$/.exec(String(req.get('authorization') || ''));++ if (m) req.user = m[1] === 'person' ? { subject_id: m[2] } : { subject_id: m[2], typ: 'delegated', delegated: { by: 'key_1', scope: m[1] === 'delegated-write' ? 'write' : 'read', services: ['finance'] } };next();} };const server = createApp({ db, vault, auth, mcpAuth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');@@@ -65,8 +65,10 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';assert.strictEqual(note.status, 202, 'a notification is accepted with nothing to say');r = await rpc('tools/list');const names = r.body.result.tools.map((t) => t.name);-- assert.deepStrictEqual(names, ['accounts', 'month', 'transactions', 'recurring', 'goals', 'net_worth', 'what_if'], 'anyone may list them');-- assert.ok(r.body.result.tools.every((t) => t.annotations.readOnlyHint === true && t.annotations.destructiveHint === false), 'every tool is read only');++ assert.deepStrictEqual(names, ['accounts', 'month', 'transactions', 'recurring', 'goals', 'net_worth', 'what_if', 'import_statement', 'add_transaction', 'categorize', 'add_rule'], 'anyone may list them');++ const reads = r.body.result.tools.filter((t) => t.annotations.readOnlyHint === true).map((t) => t.name);++ assert.deepStrictEqual(reads, names.slice(0, 7), 'seven read; four write (Network lists those only for a write grant)');++ assert.ok(r.body.result.tools.every((t) => t.annotations.destructiveHint === false), 'nothing deletes or moves money');// Nobody, or a cookie-style sign-in, is not a person here.assert.match((await call('accounts', {}, null)).content[0].text, /connect OpenVibe Finance/);@@@ -115,7 +117,7 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';assert.ok(r.body.result.supportedVersions.includes('2026-07-28'));r = await modern('tools/list', {});assert.strictEqual(r.body.result.resultType, 'complete');-- assert.strictEqual(r.body.result.tools.length, 7);++ assert.strictEqual(r.body.result.tools.length, 11);r = await modern('tools/call', { name: 'accounts', arguments: {} }, `Bearer delegated:${ADA}`);assert.strictEqual(r.body.result.resultType, 'complete');assert.strictEqual(r.body.result.structuredContent.accounts.length, 2);@@@ -124,6 +126,49 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';r = await modern('resources/list', {});assert.strictEqual(r.status, 404);++ // ── Writing (v0.10): only with a write grant (or the person's own sign-in) ──++ const OFX = '<OFX><BANKMSGSRSV1><STMTTRNRS><STMTRS><CURDEF>USD<BANKTRANLIST>'++ + '<STMTTRN><TRNTYPE>DEBIT<DTPOSTED>20261112<TRNAMT>-42.10<FITID>F-1<NAME>CORNER GROCER</STMTTRN>'++ + '<STMTTRN><TRNTYPE>DEBIT<DTPOSTED>20261113<TRNAMT>-9.99<FITID>F-2<NAME>MOVIE PASS 4421</STMTTRN>'++ + '</BANKTRANLIST></STMTRS></STMTTRNRS></BANKMSGSRSV1></OFX>';++ out = await call('import_statement', { account_id: checking.id, text: OFX });++ assert.strictEqual(out.isError, true, 'a read grant may not write');++ assert.match(out.content[0].text, /may only read: give it read and write in OpenVibe Finance/);++ const W = `delegated-write:${ADA}`;++ out = await call('import_statement', { account_id: checking.id, text: OFX }, W);++ assert.deepStrictEqual(out.structuredContent, { added: 2, already_there: 0, unreadable_lines: 0 });++ out = await call('import_statement', { account_id: checking.id, text: OFX }, W);++ assert.deepStrictEqual(out.structuredContent, { added: 0, already_there: 2, unreadable_lines: 0 }, 'the same download twice adds nothing');++ out = await call('import_statement', { account_id: boAcc.id, text: OFX }, W);++ assert.match(out.content[0].text, /No such account of yours/, 'never another person\'s account');++ out = await call('import_statement', { account_id: checking.id }, W);++ assert.match(out.content[0].text, /import_statement needs "text"/);++++ const novTx = (await store.transactions(ADA, checking.id, { month: '2026-11' }));++ const grocer = novTx.find((t) => t.payee === 'CORNER GROCER');++ const movie = novTx.find((t) => t.payee === 'MOVIE PASS 4421');++ const rent = novTx.find((t) => t.payee === 'Rent');++ await store.setCategory(ADA, rent.id, 'Housing'); // the person's own choice++ out = await call('categorize', { items: [{ transaction_id: grocer.id, category: 'Groceries' }, { transaction_id: rent.id, category: 'Shopping' }, { transaction_id: 'txn_nope', category: 'Fees' }] }, W);++ assert.deepStrictEqual(out.structuredContent, { changed: 1, kept_yours: 1, not_found: 1 }, 'an agent never overwrites the person\'s own category');++ const after = await store.transactions(ADA, checking.id, { month: '2026-11' });++ assert.deepStrictEqual([after.find((t) => t.id === grocer.id).category_from, after.find((t) => t.id === rent.id).category], ['ai', 'Housing']);++ const acctPage = await fetch(`${base}/accounts/${checking.id}?m=2026-11`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());++ assert.match(acctPage, /class="fin-by-agent"[^>]*>agent<\/span>/, 'the page marks what an agent set');++ out = await call('categorize', { items: [{ transaction_id: grocer.id, category: 'Eating out' }] }, `person:${ADA}`);++ assert.strictEqual((await store.transactions(ADA, checking.id, { month: '2026-11' })).find((t) => t.id === grocer.id).category_from, 'you', 'the person\'s own sign-in sets it as theirs');++ out = await call('categorize', { items: [] }, W);++ assert.match(out.content[0].text, /"items" is a list of 1 to 200 items/);++++ out = await call('add_rule', { match: 'movie pass', category: 'Subscriptions' }, W);++ assert.deepStrictEqual(out.structuredContent.rule, { match: 'movie pass', category: 'Subscriptions' });++ assert.ok(out.structuredContent.applied_now >= 1, 'it applies to what is uncategorised now');++ assert.strictEqual((await store.transactions(ADA, checking.id, { month: '2026-11' })).find((t) => t.id === movie.id).category, 'Subscriptions');++ out = await call('add_transaction', { account_id: checking.id, posted_on: '2026-11-17', amount_cents: -1250, payee: 'Bakery', category: 'Eating out' }, W);++ assert.strictEqual(out.structuredContent.transaction.payee, 'Bakery');++ out = await call('add_transaction', { account_id: checking.id, posted_on: '17 Nov', amount_cents: -1, payee: 'x' }, W);++ assert.match(out.content[0].text, /"posted_on" is not right/);++// The pages and the API never take a delegated person.const api = await fetch(`${base}/api/v1/accounts`, { headers: { 'x-test-user': ADA, 'x-test-delegated': '1' } });assert.strictEqual(api.status, 401, 'the API refuses something acting for the person');@@@ -134,5 +179,5 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';server.close();await close();}-- console.log('mcp: seven read-only tools, Bearer only (delegated included), the person\'s own data, schemas checked, both eras; pages and API refuse delegated');++ console.log('mcp: seven read-only tools and four that write with a write grant, Bearer only (delegated included), the person\'s own data, schemas checked, both eras; pages and API refuse delegated');})().catch((err) => { console.error(err); process.exit(1); });
@@ -10,7 +10,7 @@ to connect.
@@ -10,7 +10,7 @@ to connect.
- **No money moves.** It reads and plans; it never pays, transfers or cancels anything.
- **No money moves.** It reads and plans; it never pays, transfers or cancels anything.
- **Yours to take.** Download everything as one JSON file, or delete everything, at `/data`.
- **Yours to take.** Download everything as one JSON file, or delete everything, at `/data`.
-## What it does today (v0.9)
+## What it does today (v0.10)
- Accounts (checking, savings, credit card, cash, loan, investments) with an opening balance and a running balance.
- Accounts (checking, savings, credit card, cash, loan, investments) with an opening balance and a running balance.
- Transactions typed in, or imported from a bank's download:
- Transactions typed in, or imported from a bank's download:
@@ -45,8 +45,10 @@ OpenVibe's money Experts on Actor (Budget coach, Can I afford it?, Debt planner,
@@ -45,8 +45,10 @@ OpenVibe's money Experts on Actor (Budget coach, Can I afford it?, Debt planner,
person allows Actor in OpenVibe Finance on their Apps page; the home page links them.
person allows Actor in OpenVibe Finance on their Apps page; the home page links them.
`POST https://openvibe.finance/mcp` is an MCP server (both eras: the 2026-07-28 stateless protocol and the handshake
`POST https://openvibe.finance/mcp` is an MCP server (both eras: the 2026-07-28 stateless protocol and the handshake
-one) with seven tools, every one read only: `accounts`, `month`, `transactions`, `recurring`, `goals`, `net_worth`,
-`what_if`. Amounts are integer cents; months are `YYYY-MM`.
+one). Seven tools read: `accounts`, `month`, `transactions`, `recurring`, `goals`, `net_worth`, `what_if`. Four write,
+with the person's own sign-in or a write grant (v0.10): `import_statement` (CSV, OFX or QFX text), `add_transaction`,
+`categorize` (up to 200; a category an agent sets is marked "agent" on the page and never overwrites one the person
+set), `add_rule`. Nothing deletes; nothing moves money. Amounts are integer cents; months are `YYYY-MM`.
- Anyone may list the tools. A call reads the person from a **Bearer token only**, never a cookie: their own sign-in,
- Anyone may list the tools. A call reads the person from a **Bearer token only**, never a cookie: their own sign-in,
or a delegated person token naming `finance` (openvibe-sdk 0.187), which OpenVibe.Network mints per call for a key
or a delegated person token naming `finance` (openvibe-sdk 0.187), which OpenVibe.Network mints per call for a key
new file mode 100644
new file mode 100644
@@ -0,0 +1,8 @@
@@ -0,0 +1,8 @@
+-- phase: expand
+-- A category an agent set (plan §L.2: "every category says whether it came from the provider, you, a rule or AI"):
+-- category_from 'ai', written only through /mcp by something the person allowed to write (a delegated token with a
+-- write grant in OpenVibe Finance). It never overwrites one the person set themselves ('you'). Older code never writes
+-- it and reads it as any other origin.
+ALTER TABLE finance_transactions DROP CONSTRAINT IF EXISTS finance_transactions_category_from_check;
+ALTER TABLE finance_transactions ADD CONSTRAINT finance_transactions_category_from_check
+ CHECK (category_from IN ('none', 'you', 'rule', 'file', 'ai'));
@@ -1,12 +1,12 @@
@@ -1,12 +1,12 @@
{
{
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.9.0",
+ "version": "0.10.0",
"lockfileVersion": 3,
"lockfileVersion": 3,
"requires": true,
"requires": true,
"packages": {
"packages": {
"": {
"": {
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.9.0",
+ "version": "0.10.0",
"license": "AGPL-3.0-only",
"license": "AGPL-3.0-only",
"dependencies": {
"dependencies": {
"@electric-sql/pglite": "^0.5.8",
"@electric-sql/pglite": "^0.5.8",
@@ -1,6 +1,6 @@
@@ -1,6 +1,6 @@
{
{
"name": "openvibe-finance",
"name": "openvibe-finance",
- "version": "0.9.0",
+ "version": "0.10.0",
"private": true,
"private": true,
"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you",
"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you",
"main": "server/index.js",
"main": "server/index.js",
@@ -176,3 +176,5 @@ html[data-ov-motion="off"] .fin-result { animation: none; }
@@ -176,3 +176,5 @@ html[data-ov-motion="off"] .fin-result { animation: none; }
.fin-expert:hover { border-color: var(--accent, #5b8cff); }
.fin-expert:hover { border-color: var(--accent, #5b8cff); }
.fin-expert:active { transform: scale(.98); }
.fin-expert:active { transform: scale(.98); }
html[data-ov-motion="off"] .fin-expert { transition: none; }
html[data-ov-motion="off"] .fin-expert { transition: none; }
+/* A category an agent set (v0.10): marked, so it is easy to check and change. */
+.fin-by-agent { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 12px; color: var(--accent, #5b8cff); border: 1px solid color-mix(in srgb, var(--accent, #5b8cff) 45%, transparent); }
@@ -51,7 +51,7 @@ function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvib
@@ -51,7 +51,7 @@ function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvib
const finMcp = require('./mcp').createMcp({ store, aheadFor: (me, q) => aheadFor(me, q), now });
const finMcp = require('./mcp').createMcp({ store, aheadFor: (me, q) => aheadFor(me, q), now });
const bearerOnly = (req, _res, next) => { if (!/^Bearer\s+\S/i.test(String(req.get('authorization') || ''))) { delete req.headers.cookie; req.user = undefined; } next(); };
const bearerOnly = (req, _res, next) => { if (!/^Bearer\s+\S/i.test(String(req.get('authorization') || ''))) { delete req.headers.cookie; req.user = undefined; } next(); };
const mcpWho = mcpAuth || auth;
const mcpWho = mcpAuth || auth;
- app.post('/mcp', express.json({ limit: '64kb' }), bearerOnly, (req, res, next) => (mcpWho && /^Bearer\s/i.test(String(req.get('authorization') || '')) ? mcpWho.optionalAuth()(req, res, next) : next()),
+ app.post('/mcp', express.json({ limit: '5mb' }), bearerOnly, (req, res, next) => (mcpWho && /^Bearer\s/i.test(String(req.get('authorization') || '')) ? mcpWho.optionalAuth()(req, res, next) : next()),
(req, res, next) => { res.set('Cache-Control', 'private, no-store'); Promise.resolve(finMcp.handler(req, res)).catch(next); });
(req, res, next) => { res.set('Cache-Control', 'private, no-store'); Promise.resolve(finMcp.handler(req, res)).catch(next); });
app.all('/mcp', (_req, res) => res.status(405).set('Allow', 'POST').json({ error: 'POST a JSON-RPC request.' }));
app.all('/mcp', (_req, res) => res.status(405).set('Allow', 'POST').json({ error: 'POST a JSON-RPC request.' }));
app.use(auth ? auth.optionalAuth() : (_req, _res, next) => next());
app.use(auth ? auth.optionalAuth() : (_req, _res, next) => next());
@@ -4,7 +4,10 @@
@@ -4,7 +4,10 @@
* permissions (transactions.read), never a bank login"). An agent the person allowed reads their money as them, and
* permissions (transactions.read), never a bank login"). An agent the person allowed reads their money as them, and
* nothing more:
* nothing more:
*
*
- * - **Read only.** Every tool is readOnlyHint; none writes, imports, deletes or moves money. "No money moves."
+ * - **Read, and with a write grant a little writing.** Seven tools are readOnlyHint. Four write (v0.10): import a bank's
+ * download, add a transaction, categorise, add a rule; they need the person's own sign-in or a delegated token whose
+ * scope is write (a write grant in OpenVibe Finance on the Apps page; Network lists them only then). Nothing deletes;
+ * nothing moves money. A category an agent sets is marked ('ai') and never overwrites one the person set.
* - **As the person, by a Bearer token only:** their own session's, or a delegated person token (SDK 0.187) that names
* - **As the person, by a Bearer token only:** their own session's, or a delegated person token (SDK 0.187) that names
* this service, which OpenVibe.Network mints per call for a key with a grant in OpenVibe Finance (Connect, /mcp/all).
* this service, which OpenVibe.Network mints per call for a key with a grant in OpenVibe Finance (Connect, /mcp/all).
* Cookies are never read here, so a page elsewhere cannot use a signed-in browser. The pages and the JSON API keep
* Cookies are never read here, so a page elsewhere cannot use a signed-in browser. The pages and the JSON API keep
@@ -15,20 +18,28 @@
@@ -15,20 +18,28 @@
* createMcp({ store, aheadFor, now }) → { tools, handler(req, res) } req.user is the person (or nobody)
* createMcp({ store, aheadFor, now }) → { tools, handler(req, res) } req.user is the person (or nobody)
*/
*/
const mcp = require('openvibe-sdk/mcp');
const mcp = require('openvibe-sdk/mcp');
-const { FinanceError } = require('./store');
+const { isDelegated } = require('openvibe-sdk/auth/delegated');
+const { FinanceError, CATEGORIES } = require('./store');
+const { readCsv } = require('./csv');
+const { isOfx, readOfx } = require('./ofx');
const { findRecurring } = require('./recurring');
const { findRecurring } = require('./recurring');
const { payoff } = require('./plan');
const { payoff } = require('./plan');
const SERVER_INFO = { name: 'openvibe-finance', title: 'OpenVibe Finance', version: require('../package.json').version };
const SERVER_INFO = { name: 'openvibe-finance', title: 'OpenVibe Finance', version: require('../package.json').version };
const INSTRUCTIONS = 'Read one person\'s money on OpenVibe Finance, as them: accounts and balances, a month by category with budgets, '
const INSTRUCTIONS = 'Read one person\'s money on OpenVibe Finance, as them: accounts and balances, a month by category with budgets, '
+ 'transactions, recurring bills and income, goals and debt payoff, net worth over time, and what-if ("can I afford this?"). '
+ 'transactions, recurring bills and income, goals and debt payoff, net worth over time, and what-if ("can I afford this?"). '
- + 'Amounts are integer cents; months are YYYY-MM. Read only: nothing here moves money or changes anything.';
+ + 'Amounts are integer cents; months are YYYY-MM. With a write grant it can also import a bank\'s download, add a transaction, '
+ + 'categorise transactions and add a rule. Nothing here deletes anything or moves money.';
const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
+const WRITE = (idempotent) => ({ readOnlyHint: false, destructiveHint: false, idempotentHint: idempotent, openWorldHint: false });
+const DAY = { type: 'string', pattern: '^\\d{4}-\\d{2}-\\d{2}$', description: 'A day, YYYY-MM-DD.' };
+const ACCOUNT = { type: 'string', maxLength: 64, description: 'The account (from accounts).' };
+const CATEGORY = { type: 'string', minLength: 1, maxLength: 60, description: `A category: ${CATEGORIES.join(', ')} (or your own).` };
const MONTH = { type: 'string', pattern: '^\\d{4}-(0[1-9]|1[0-2])$', description: 'A month, YYYY-MM.' };
const MONTH = { type: 'string', pattern: '^\\d{4}-(0[1-9]|1[0-2])$', description: 'A month, YYYY-MM.' };
-const tool = (name, title, description, properties = {}) => ({
+const tool = (name, title, description, properties = {}, { required = [], annotations = READ } = {}) => ({
name, title, description,
name, title, description,
- inputSchema: { type: 'object', properties, additionalProperties: false },
- annotations: { title, ...READ },
+ inputSchema: { type: 'object', properties, ...(required.length ? { required } : {}), additionalProperties: false },
+ annotations: { title, ...annotations },
});
});
const TOOLS = [
const TOOLS = [
@@ -48,6 +59,20 @@ const TOOLS = [
@@ -48,6 +59,20 @@ const TOOLS = [
direction: { type: 'string', enum: ['out', 'in'], description: 'out: more going out (rent rises); in: more coming in. out by default.' },
direction: { type: 'string', enum: ['out', 'in'], description: 'out: more going out (rent rises); in: more coming in. out by default.' },
from: { ...MONTH, description: 'The month the change starts (next month by default).' },
from: { ...MONTH, description: 'The month the change starts (next month by default).' },
}),
}),
+ // ── Writing, with a write grant (v0.10) ──
+ 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.', {
+ account_id: ACCOUNT, text: { type: 'string', minLength: 1, maxLength: 4000000, description: 'The file\'s text.' },
+ }, { required: ['account_id', 'text'], annotations: WRITE(true) }),
+ 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.', {
+ account_id: ACCOUNT, posted_on: DAY, amount_cents: { type: 'integer', minimum: -1e11, maximum: 1e11, description: 'Cents; negative is money out.' },
+ payee: { type: 'string', minLength: 1, maxLength: 300 }, memo: { type: 'string', maxLength: 500 }, category: CATEGORY,
+ }, { required: ['account_id', 'posted_on', 'amount_cents', 'payee'], annotations: WRITE(false) }),
+ 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.', {
+ 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 } },
+ }, { required: ['items'], annotations: WRITE(true) }),
+ 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.', {
+ match: { type: 'string', minLength: 2, maxLength: 120, description: 'Words of the payee, such as "streamflix".' }, category: CATEGORY,
+ }, { required: ['match', 'category'], annotations: WRITE(true) }),
];
];
function createMcp({ store, aheadFor, now = () => new Date() }) {
function createMcp({ store, aheadFor, now = () => new Date() }) {
@@ -93,6 +118,34 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {
@@ -93,6 +118,34 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {
async net_worth(me) {
async net_worth(me) {
return { net_worth: (await aheadFor(me)).net_worth };
return { net_worth: (await aheadFor(me)).net_worth };
},
},
+ async import_statement(me, args) {
+ if (!(await store.account(me, args.account_id))) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');
+ const read = isOfx(args.text) ? readOfx(args.text) : readCsv(args.text);
+ if (read.problem) throw new FinanceError(422, 'finance.import.unreadable', read.problem);
+ const out = await store.importRows(me, args.account_id, read.rows);
+ return { added: out.added, already_there: out.skipped, unreadable_lines: read.skipped.length };
+ },
+ async add_transaction(me, args) {
+ 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 || '' });
+ return { transaction: { id: t.id, posted_on: t.posted_on, amount_cents: t.amount_cents, payee: t.payee, category: t.category } };
+ },
+ async categorize(me, args, ctx) {
+ const out = { changed: 0, kept_yours: 0, not_found: 0 };
+ for (const it of args.items) {
+ 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 }.');
+ try { await store.setCategory(me, it.transaction_id, it.category, { from: ctx.agent ? 'ai' : 'you' }); out.changed += 1; } catch (err) {
+ if (!(err instanceof FinanceError)) throw err;
+ if (err.status === 409) out.kept_yours += 1;
+ else if (err.status === 404) out.not_found += 1;
+ else throw err;
+ }
+ }
+ return out;
+ },
+ async add_rule(me, args) {
+ const r = await store.addRule(me, { match: args.match, category: args.category });
+ return { rule: { match: r.match, category: r.category }, applied_now: r.applied };
+ },
async what_if(me, args) {
async what_if(me, args) {
const q = {};
const q = {};
if (args.cost_cents) q.cost = (args.cost_cents / 100).toFixed(2);
if (args.cost_cents) q.cost = (args.cost_cents / 100).toFixed(2);
@@ -111,11 +164,13 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {
@@ -111,11 +164,13 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {
function badArgs(def, args) {
function badArgs(def, args) {
if (!args || typeof args !== 'object' || Array.isArray(args)) return 'The arguments are an object.';
if (!args || typeof args !== 'object' || Array.isArray(args)) return 'The arguments are an object.';
const props = def.inputSchema.properties;
const props = def.inputSchema.properties;
+ for (const k of def.inputSchema.required || []) if (args[k] === undefined || args[k] === null) return `${def.name} needs "${k}".`;
for (const [k, v] of Object.entries(args)) {
for (const [k, v] of Object.entries(args)) {
const p = props[k];
const p = props[k];
if (!p) return `${def.name} takes no "${k}".`;
if (!p) return `${def.name} takes no "${k}".`;
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}` : ''}.`;
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}` : ''}.`;
- if (p.type === 'string' && (typeof v !== 'string' || (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'}`;
+ 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.`;
+ 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'}`;
}
}
return null;
return null;
}
}
@@ -131,7 +186,11 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {
@@ -131,7 +186,11 @@ function createMcp({ store, aheadFor, now = () => new Date() }) {
const args = params.arguments == null ? {} : params.arguments;
const args = params.arguments == null ? {} : params.arguments;
const bad = badArgs(def, args);
const bad = badArgs(def, args);
if (bad) return { result: asError(bad) };
if (bad) return { result: asError(bad) };
- try { return { result: asResult(await RUN[def.name](me, args)) }; } catch (err) {
+ // Something acting for the person (a delegated token) writes only with a write grant; the person themselves may.
+ const agent = isDelegated(req.user);
+ const scope = agent ? String((req.user.delegated && req.user.delegated.scope) || (req.user.scope) || 'read') : 'write';
+ 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).') };
+ try { return { result: asResult(await RUN[def.name](me, args, { agent })) }; } catch (err) {
if (err instanceof FinanceError) return { result: asError(err.message) };
if (err instanceof FinanceError) return { result: asError(err.message) };
throw err;
throw err;
}
}
@@ -10,7 +10,8 @@
@@ -10,7 +10,8 @@
* addAccount(owner, { name, kind, currency, opening_cents })
* addAccount(owner, { name, kind, currency, opening_cents })
* transactions(owner, accountId, { month }) → [{ id, posted_on, amount_cents, payee, memo, category, category_from }]
* transactions(owner, accountId, { month }) → [{ id, posted_on, amount_cents, payee, memo, category, category_from }]
* addTransaction(owner, accountId, { posted_on, amount_cents, payee, memo, category })
* addTransaction(owner, accountId, { posted_on, amount_cents, payee, memo, category })
- * setCategory(owner, id, category) a correction: a new revision, category_from 'you'
+ * setCategory(owner, id, category, { from }) a correction: a new revision, category_from 'you' (or 'ai': an agent the
+ * person allowed to write; it never overwrites one they set themselves)
* removeTransaction(owner, id)
* removeTransaction(owner, id)
* importRows(owner, accountId, rows) → { import_id, read, added, skipped } (the same row twice is one)
* importRows(owner, accountId, rows) → { import_id, read, added, skipped } (the same row twice is one)
* month(owner, 'YYYY-MM') → { month, income_cents, spent_cents, by_category: [{ category, cents, count }] }
* month(owner, 'YYYY-MM') → { month, income_cents, spent_cents, by_category: [{ category, cents, count }] }
@@ -131,12 +132,17 @@ function createStore({ db, vault }) {
@@ -131,12 +132,17 @@ function createStore({ db, vault }) {
return open(owner, await db.one('SELECT * FROM finance_transactions WHERE id = $1', [id]));
return open(owner, await db.one('SELECT * FROM finance_transactions WHERE id = $1', [id]));
}
}
- async function setCategory(owner, id, category) {
+ async function setCategory(owner, id, category, { from = 'you' } = {}) {
own(owner);
own(owner);
const c = cleanCategory(category);
const c = cleanCategory(category);
- const n = await db.exec(`UPDATE finance_transactions SET category = $3, category_from = 'you', revision = revision + 1, updated_at = now()
- WHERE id = $1 AND owner = $2`, [String(id || ''), owner, c]);
- if (!n) fail(404, 'finance.transaction.not_found', 'No such transaction of yours.');
+ const by = from === 'ai' ? 'ai' : 'you';
+ const n = await db.exec(`UPDATE finance_transactions SET category = $3, category_from = $4, revision = revision + 1, updated_at = now()
+ WHERE id = $1 AND owner = $2 AND ($4 = 'you' OR category_from <> 'you')`, [String(id || ''), owner, c, by]);
+ if (!n) {
+ const row = await db.maybe('SELECT category_from FROM finance_transactions WHERE id = $1 AND owner = $2', [String(id || ''), owner]);
+ if (!row) fail(404, 'finance.transaction.not_found', 'No such transaction of yours.');
+ fail(409, 'finance.transaction.yours', 'You set this category yourself: an agent leaves it as it is.');
+ }
return open(owner, await db.one('SELECT * FROM finance_transactions WHERE id = $1', [String(id)]));
return open(owner, await db.one('SELECT * FROM finance_transactions WHERE id = $1', [String(id)]));
}
}
@@ -262,7 +262,7 @@ function accountPage({ account, balance, txns, month, o = {} }) {
@@ -262,7 +262,7 @@ function accountPage({ account, balance, txns, month, o = {} }) {
const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;
const cats = `<datalist id="fin-cats">${CATEGORIES.map((c) => `<option value="${esc(c)}">`).join('')}</datalist>`;
const row = (t) => `<li class="fin-txn"><span class="fin-txn-date">${esc(t.posted_on.slice(5))}</span>
const row = (t) => `<li class="fin-txn"><span class="fin-txn-date">${esc(t.posted_on.slice(5))}</span>
<span class="fin-txn-what"><b>${esc(t.payee || 'No payee')}</b>${t.memo ? `<small>${esc(t.memo)}</small>` : ''}
<span class="fin-txn-what"><b>${esc(t.payee || 'No payee')}</b>${t.memo ? `<small>${esc(t.memo)}</small>` : ''}
-<form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category"><input name="category" list="fin-cats" value="${esc(t.category)}" aria-label="Category" maxlength="60">${t.payee ? `<label class="fin-always" title="Every transaction from ${esc(t.payee)} goes here, now and in future imports"><input type="checkbox" name="always" value="yes"><span>Always</span></label>` : ''}<button type="submit" class="fin-mini">Save</button></form>${t.category_from === 'rule' ? '<small class="fin-by-rule">by a rule</small>' : ''}</span>
+<form class="fin-cat" method="post" action="/transactions/${esc(t.id)}/category">${t.category_from === 'ai' ? '<span class="fin-by-agent" title="An agent you allowed set this category. Change it and it is yours.">agent</span>' : ''}<input name="category" list="fin-cats" value="${esc(t.category)}" aria-label="Category" maxlength="60">${t.payee ? `<label class="fin-always" title="Every transaction from ${esc(t.payee)} goes here, now and in future imports"><input type="checkbox" name="always" value="yes"><span>Always</span></label>` : ''}<button type="submit" class="fin-mini">Save</button></form>${t.category_from === 'rule' ? '<small class="fin-by-rule">by a rule</small>' : ''}</span>
<span class="fin-txn-amount${t.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(t.amount_cents, account.currency))}</span></li>`;
<span class="fin-txn-amount${t.amount_cents < 0 ? ' is-neg' : ' is-pos'}">${esc(money(t.amount_cents, account.currency))}</span></li>`;
const today = new Date().toISOString().slice(0, 10);
const today = new Date().toISOString().slice(0, 10);
return page({
return page({
@@ -27,10 +27,10 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
@@ -27,10 +27,10 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
if (u) req.user = req.get('x-test-delegated') ? { subject_id: u, typ: 'delegated', delegated: { by: 'key_1', scope: 'read', services: ['finance'] } } : { subject_id: u };
if (u) req.user = req.get('x-test-delegated') ? { subject_id: u, typ: 'delegated', delegated: { by: 'key_1', scope: 'read', services: ['finance'] } } : { subject_id: u };
next();
next();
} };
} };
- // /mcp's sign-in: "Bearer person:<subject>" or "Bearer delegated:<subject>"; anything else is nobody.
+ // /mcp's sign-in: "Bearer person:<subject>", "Bearer delegated:<subject>" (a read grant) or "Bearer delegated-write:<subject>".
const mcpAuth = { optionalAuth: () => (req, _res, next) => {
const mcpAuth = { optionalAuth: () => (req, _res, next) => {
- const m = /^Bearer (person|delegated):(\S+)$/.exec(String(req.get('authorization') || ''));
- if (m) req.user = m[1] === 'delegated' ? { subject_id: m[2], typ: 'delegated', delegated: { by: 'key_1', scope: 'read', services: ['finance'] } } : { subject_id: m[2] };
+ const m = /^Bearer (person|delegated|delegated-write):(\S+)$/.exec(String(req.get('authorization') || ''));
+ if (m) req.user = m[1] === 'person' ? { subject_id: m[2] } : { subject_id: m[2], typ: 'delegated', delegated: { by: 'key_1', scope: m[1] === 'delegated-write' ? 'write' : 'read', services: ['finance'] } };
next();
next();
} };
} };
const server = createApp({ db, vault, auth, mcpAuth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');
const server = createApp({ db, vault, auth, mcpAuth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');
@@ -65,8 +65,10 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
@@ -65,8 +65,10 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
assert.strictEqual(note.status, 202, 'a notification is accepted with nothing to say');
assert.strictEqual(note.status, 202, 'a notification is accepted with nothing to say');
r = await rpc('tools/list');
r = await rpc('tools/list');
const names = r.body.result.tools.map((t) => t.name);
const names = r.body.result.tools.map((t) => t.name);
- assert.deepStrictEqual(names, ['accounts', 'month', 'transactions', 'recurring', 'goals', 'net_worth', 'what_if'], 'anyone may list them');
- assert.ok(r.body.result.tools.every((t) => t.annotations.readOnlyHint === true && t.annotations.destructiveHint === false), 'every tool is read only');
+ assert.deepStrictEqual(names, ['accounts', 'month', 'transactions', 'recurring', 'goals', 'net_worth', 'what_if', 'import_statement', 'add_transaction', 'categorize', 'add_rule'], 'anyone may list them');
+ const reads = r.body.result.tools.filter((t) => t.annotations.readOnlyHint === true).map((t) => t.name);
+ assert.deepStrictEqual(reads, names.slice(0, 7), 'seven read; four write (Network lists those only for a write grant)');
+ assert.ok(r.body.result.tools.every((t) => t.annotations.destructiveHint === false), 'nothing deletes or moves money');
// Nobody, or a cookie-style sign-in, is not a person here.
// Nobody, or a cookie-style sign-in, is not a person here.
assert.match((await call('accounts', {}, null)).content[0].text, /connect OpenVibe Finance/);
assert.match((await call('accounts', {}, null)).content[0].text, /connect OpenVibe Finance/);
@@ -115,7 +117,7 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
@@ -115,7 +117,7 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
assert.ok(r.body.result.supportedVersions.includes('2026-07-28'));
assert.ok(r.body.result.supportedVersions.includes('2026-07-28'));
r = await modern('tools/list', {});
r = await modern('tools/list', {});
assert.strictEqual(r.body.result.resultType, 'complete');
assert.strictEqual(r.body.result.resultType, 'complete');
- assert.strictEqual(r.body.result.tools.length, 7);
+ assert.strictEqual(r.body.result.tools.length, 11);
r = await modern('tools/call', { name: 'accounts', arguments: {} }, `Bearer delegated:${ADA}`);
r = await modern('tools/call', { name: 'accounts', arguments: {} }, `Bearer delegated:${ADA}`);
assert.strictEqual(r.body.result.resultType, 'complete');
assert.strictEqual(r.body.result.resultType, 'complete');
assert.strictEqual(r.body.result.structuredContent.accounts.length, 2);
assert.strictEqual(r.body.result.structuredContent.accounts.length, 2);
@@ -124,6 +126,49 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
@@ -124,6 +126,49 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
r = await modern('resources/list', {});
r = await modern('resources/list', {});
assert.strictEqual(r.status, 404);
assert.strictEqual(r.status, 404);
+ // ── Writing (v0.10): only with a write grant (or the person's own sign-in) ──
+ const OFX = '<OFX><BANKMSGSRSV1><STMTTRNRS><STMTRS><CURDEF>USD<BANKTRANLIST>'
+ + '<STMTTRN><TRNTYPE>DEBIT<DTPOSTED>20261112<TRNAMT>-42.10<FITID>F-1<NAME>CORNER GROCER</STMTTRN>'
+ + '<STMTTRN><TRNTYPE>DEBIT<DTPOSTED>20261113<TRNAMT>-9.99<FITID>F-2<NAME>MOVIE PASS 4421</STMTTRN>'
+ + '</BANKTRANLIST></STMTRS></STMTTRNRS></BANKMSGSRSV1></OFX>';
+ out = await call('import_statement', { account_id: checking.id, text: OFX });
+ assert.strictEqual(out.isError, true, 'a read grant may not write');
+ assert.match(out.content[0].text, /may only read: give it read and write in OpenVibe Finance/);
+ const W = `delegated-write:${ADA}`;
+ out = await call('import_statement', { account_id: checking.id, text: OFX }, W);
+ assert.deepStrictEqual(out.structuredContent, { added: 2, already_there: 0, unreadable_lines: 0 });
+ out = await call('import_statement', { account_id: checking.id, text: OFX }, W);
+ assert.deepStrictEqual(out.structuredContent, { added: 0, already_there: 2, unreadable_lines: 0 }, 'the same download twice adds nothing');
+ out = await call('import_statement', { account_id: boAcc.id, text: OFX }, W);
+ assert.match(out.content[0].text, /No such account of yours/, 'never another person\'s account');
+ out = await call('import_statement', { account_id: checking.id }, W);
+ assert.match(out.content[0].text, /import_statement needs "text"/);
+
+ const novTx = (await store.transactions(ADA, checking.id, { month: '2026-11' }));
+ const grocer = novTx.find((t) => t.payee === 'CORNER GROCER');
+ const movie = novTx.find((t) => t.payee === 'MOVIE PASS 4421');
+ const rent = novTx.find((t) => t.payee === 'Rent');
+ await store.setCategory(ADA, rent.id, 'Housing'); // the person's own choice
+ out = await call('categorize', { items: [{ transaction_id: grocer.id, category: 'Groceries' }, { transaction_id: rent.id, category: 'Shopping' }, { transaction_id: 'txn_nope', category: 'Fees' }] }, W);
+ assert.deepStrictEqual(out.structuredContent, { changed: 1, kept_yours: 1, not_found: 1 }, 'an agent never overwrites the person\'s own category');
+ const after = await store.transactions(ADA, checking.id, { month: '2026-11' });
+ assert.deepStrictEqual([after.find((t) => t.id === grocer.id).category_from, after.find((t) => t.id === rent.id).category], ['ai', 'Housing']);
+ const acctPage = await fetch(`${base}/accounts/${checking.id}?m=2026-11`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());
+ assert.match(acctPage, /class="fin-by-agent"[^>]*>agent<\/span>/, 'the page marks what an agent set');
+ out = await call('categorize', { items: [{ transaction_id: grocer.id, category: 'Eating out' }] }, `person:${ADA}`);
+ assert.strictEqual((await store.transactions(ADA, checking.id, { month: '2026-11' })).find((t) => t.id === grocer.id).category_from, 'you', 'the person\'s own sign-in sets it as theirs');
+ out = await call('categorize', { items: [] }, W);
+ assert.match(out.content[0].text, /"items" is a list of 1 to 200 items/);
+
+ out = await call('add_rule', { match: 'movie pass', category: 'Subscriptions' }, W);
+ assert.deepStrictEqual(out.structuredContent.rule, { match: 'movie pass', category: 'Subscriptions' });
+ assert.ok(out.structuredContent.applied_now >= 1, 'it applies to what is uncategorised now');
+ assert.strictEqual((await store.transactions(ADA, checking.id, { month: '2026-11' })).find((t) => t.id === movie.id).category, 'Subscriptions');
+ out = await call('add_transaction', { account_id: checking.id, posted_on: '2026-11-17', amount_cents: -1250, payee: 'Bakery', category: 'Eating out' }, W);
+ assert.strictEqual(out.structuredContent.transaction.payee, 'Bakery');
+ out = await call('add_transaction', { account_id: checking.id, posted_on: '17 Nov', amount_cents: -1, payee: 'x' }, W);
+ assert.match(out.content[0].text, /"posted_on" is not right/);
+
// The pages and the API never take a delegated person.
// The pages and the API never take a delegated person.
const api = await fetch(`${base}/api/v1/accounts`, { headers: { 'x-test-user': ADA, 'x-test-delegated': '1' } });
const api = await fetch(`${base}/api/v1/accounts`, { headers: { 'x-test-user': ADA, 'x-test-delegated': '1' } });
assert.strictEqual(api.status, 401, 'the API refuses something acting for the person');
assert.strictEqual(api.status, 401, 'the API refuses something acting for the person');
@@ -134,5 +179,5 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
@@ -134,5 +179,5 @@ const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
server.close();
server.close();
await close();
await close();
}
}
- console.log('mcp: seven read-only tools, Bearer only (delegated included), the person\'s own data, schemas checked, both eras; pages and API refuse delegated');
+ console.log('mcp: seven read-only tools and four that write with a write grant, Bearer only (delegated included), the person\'s own data, schemas checked, both eras; pages and API refuse delegated');
})().catch((err) => { console.error(err); process.exit(1); });
})().catch((err) => { console.error(err); process.exit(1); });