openvibers/openvibe.finance testmcp.test.js

mcp.test.js

main 14.9 KB · 184 lines · javascript

1'use strict';
2/**
3 * Finance's MCP server (server/mcp.js, POST /mcp): seven read-only tools; anyone may list them; a call reads the person
4 * from a Bearer token only (a delegated person token naming finance included), never from a cookie or the pages'
5 * sign-in; the pages and the API refuse a delegated person; each tool answers the person's own data only; arguments are
6 * checked against the schema; both MCP eras (handshake and 2026-07-28 stateless) on one endpoint.
7 */
8const assert = require('assert');
9const path = require('node:path');
10const crypto = require('node:crypto');
11const mcp = require('openvibe-sdk/mcp');
12const { createTestDb } = require('openvibe-sdk/testing');
13const { createVault } = require('../server/crypto');
14const { createStore } = require('../server/store');
15const { createApp } = require('../server/app');
16
17const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
18const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
19
20(async () => {
21 const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
22 const vault = createVault(crypto.randomBytes(32).toString('base64'));
23 const store = createStore({ db, vault });
24 // The pages' sign-in: x-test-user (x-test-delegated makes that person a delegated one, which the pages must refuse).
25 const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => {
26 const u = req.get('x-test-user');
27 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 };
28 next();
29 } };
30 // /mcp's sign-in: "Bearer person:<subject>", "Bearer delegated:<subject>" (a read grant) or "Bearer delegated-write:<subject>".
31 const mcpAuth = { optionalAuth: () => (req, _res, next) => {
32 const m = /^Bearer (person|delegated|delegated-write):(\S+)$/.exec(String(req.get('authorization') || ''));
33 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'] } };
34 next();
35 } };
36 const server = createApp({ db, vault, auth, mcpAuth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');
37 await new Promise((r) => server.once('listening', r));
38 const base = `http://127.0.0.1:${server.address().port}`;
39 let n = 0;
40 const rpc = async (method, params = {}, headers = {}) => {
41 const r = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify({ jsonrpc: '2.0', id: ++n, method, params }) });
42 return { status: r.status, body: r.status === 202 ? null : await r.json() };
43 };
44 const call = async (name, args, as = `delegated:${ADA}`) => (await rpc('tools/call', { name, arguments: args }, as ? { authorization: `Bearer ${as}` } : {})).body.result;
45 try {
46 const checking = await store.addAccount(ADA, { name: 'Checking', kind: 'checking', opening_cents: 100000 });
47 const card = await store.addAccount(ADA, { name: 'Visa', kind: 'credit', opening_cents: -500000 });
48 await store.setDebt(ADA, card.id, { apr_bps: 2499, payment_cents: 15000 });
49 const rows = [];
50 for (const m of ['2026-08', '2026-09', '2026-10', '2026-11']) {
51 rows.push({ posted_on: `${m}-01`, amount_cents: 300000, payee: 'Paycheck', category: 'Income' });
52 rows.push({ posted_on: `${m}-03`, amount_cents: -150000, payee: 'Rent', category: 'Housing' });
53 rows.push({ posted_on: `${m}-05`, amount_cents: -1599, payee: 'StreamFlix', category: 'Subscriptions' });
54 }
55 await store.importRows(ADA, checking.id, rows);
56 await store.setBudget(ADA, 'Subscriptions', 1000);
57 await store.addGoal(ADA, { name: 'Trip', target_cents: 120000, target_on: '2027-11-01' });
58 const boAcc = await store.addAccount(BO, { name: 'Bo private', kind: 'checking', opening_cents: 999900 });
59
60 // The handshake era, as Network's /mcp/all calls it.
61 let r = await rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } });
62 assert.strictEqual(r.body.result.protocolVersion, '2025-06-18');
63 assert.strictEqual(r.body.result.serverInfo.name, 'openvibe-finance');
64 const note = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) });
65 assert.strictEqual(note.status, 202, 'a notification is accepted with nothing to say');
66 r = await rpc('tools/list');
67 const names = r.body.result.tools.map((t) => t.name);
68 assert.deepStrictEqual(names, ['accounts', 'month', 'transactions', 'recurring', 'goals', 'net_worth', 'what_if', 'import_statement', 'add_transaction', 'categorize', 'add_rule'], 'anyone may list them');
69 const reads = r.body.result.tools.filter((t) => t.annotations.readOnlyHint === true).map((t) => t.name);
70 assert.deepStrictEqual(reads, names.slice(0, 7), 'seven read; four write (Network lists those only for a write grant)');
71 assert.ok(r.body.result.tools.every((t) => t.annotations.destructiveHint === false), 'nothing deletes or moves money');
72
73 // Nobody, or a cookie-style sign-in, is not a person here.
74 assert.match((await call('accounts', {}, null)).content[0].text, /connect OpenVibe Finance/);
75 r = await rpc('tools/call', { name: 'accounts', arguments: {} }, { 'x-test-user': ADA });
76 assert.strictEqual(r.body.result.isError, true, 'the pages\' sign-in does not reach /mcp');
77
78 let out = await call('accounts', {});
79 assert.deepStrictEqual(out.structuredContent.accounts.map((a) => [a.name, a.balance_cents]), [['Checking', 100000 + 4 * (300000 - 150000 - 1599)], ['Visa', -500000]]);
80 assert.ok(!JSON.stringify(out).includes('Bo private'), 'another person\'s accounts never');
81 out = await call('accounts', {}, `person:${ADA}`);
82 assert.strictEqual(out.isError, false, 'the person\'s own Bearer sign-in works too');
83
84 out = await call('month', { month: '2026-10' });
85 assert.deepStrictEqual(out.structuredContent.by_category.find((c) => c.category === 'Subscriptions'), { category: 'Subscriptions', in_cents: 0, out_cents: 1599, count: 1, budget_cents: 1000, left_cents: -599 });
86 out = await call('transactions', { month: '2026-11', limit: 2 });
87 assert.deepStrictEqual(out.structuredContent.transactions.map((t) => [t.posted_on, t.payee]), [['2026-11-05', 'StreamFlix'], ['2026-11-03', 'Rent']], 'payees opened for the person');
88 out = await call('transactions', { account_id: boAcc.id });
89 assert.match(out.content[0].text, /No such account of yours/);
90 out = await call('recurring', {});
91 assert.ok(out.structuredContent.recurring.some((x) => x.payee === 'StreamFlix' && x.cadence === 'monthly'));
92 out = await call('goals', {});
93 assert.deepStrictEqual(out.structuredContent.debts.map((d) => [d.name, d.owed_cents, d.payoff_months, d.interest_cents]), [['Visa', 500000, 58, 362226]]);
94 assert.strictEqual(out.structuredContent.goals[0].name, 'Trip');
95 out = await call('net_worth', {});
96 assert.strictEqual(out.structuredContent.net_worth[0].month, '2026-08');
97 out = await call('what_if', { cost_cents: 50000000 });
98 assert.ok(out.structuredContent.plan.below_zero_on, 'a $500,000 cost does not fit');
99 out = await call('what_if', { change_cents: 10000, direction: 'out', from: '2027-02' });
100 assert.strictEqual(out.structuredContent.plan.left_with_cents, out.structuredContent.plan.left_now_cents - 10000);
101
102 for (const [name, args, said] of [['month', { month: '2026-13' }, /"month" is not right/], ['accounts', { secret: 1 }, /accounts takes no "secret"/], ['transactions', { limit: 9999 }, /"limit" is a whole number from 1 to 500/], ['what_if', { cost_on: '2031-01', cost_cents: 5 }, /within the next twelve months/]]) {
103 out = await call(name, args);
104 assert.strictEqual(out.isError, true, name);
105 assert.match(out.content[0].text, said);
106 }
107 r = await rpc('tools/call', { name: 'pay_bill', arguments: {} }, { authorization: `Bearer delegated:${ADA}` });
108 assert.strictEqual(r.body.error.code, -32602, 'there is no tool that moves money');
109
110 // The 2026-07-28 era: stateless, headers that agree with the body.
111 const modern = async (method, params, auth) => {
112 const { headers, body } = mcp.modernRequest({ id: ++n, method, params, clientInfo: { name: 't', version: '1' } });
113 const res = await fetch(`${base}/mcp`, { method: 'POST', headers: { ...headers, ...(auth ? { authorization: auth } : {}) }, body: JSON.stringify(body) });
114 return { status: res.status, body: await res.json() };
115 };
116 r = await modern('server/discover', {});
117 assert.ok(r.body.result.supportedVersions.includes('2026-07-28'));
118 r = await modern('tools/list', {});
119 assert.strictEqual(r.body.result.resultType, 'complete');
120 assert.strictEqual(r.body.result.tools.length, 11);
121 r = await modern('tools/call', { name: 'accounts', arguments: {} }, `Bearer delegated:${ADA}`);
122 assert.strictEqual(r.body.result.resultType, 'complete');
123 assert.strictEqual(r.body.result.structuredContent.accounts.length, 2);
124 const lie = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', 'MCP-Protocol-Version': '2026-07-28', 'Mcp-Method': 'tools/list' }, body: JSON.stringify(mcp.modernRequest({ id: 1, method: 'tools/call', params: { name: 'accounts' } }).body) });
125 assert.strictEqual(lie.status, 400, 'headers that disagree with the body are refused');
126 r = await modern('resources/list', {});
127 assert.strictEqual(r.status, 404);
128
129 // ── Writing (v0.10): only with a write grant (or the person's own sign-in) ──
130 const OFX = '<OFX><BANKMSGSRSV1><STMTTRNRS><STMTRS><CURDEF>USD<BANKTRANLIST>'
131 + '<STMTTRN><TRNTYPE>DEBIT<DTPOSTED>20261112<TRNAMT>-42.10<FITID>F-1<NAME>CORNER GROCER</STMTTRN>'
132 + '<STMTTRN><TRNTYPE>DEBIT<DTPOSTED>20261113<TRNAMT>-9.99<FITID>F-2<NAME>MOVIE PASS 4421</STMTTRN>'
133 + '</BANKTRANLIST></STMTRS></STMTTRNRS></BANKMSGSRSV1></OFX>';
134 out = await call('import_statement', { account_id: checking.id, text: OFX });
135 assert.strictEqual(out.isError, true, 'a read grant may not write');
136 assert.match(out.content[0].text, /may only read: give it read and write in OpenVibe Finance/);
137 const W = `delegated-write:${ADA}`;
138 out = await call('import_statement', { account_id: checking.id, text: OFX }, W);
139 assert.deepStrictEqual(out.structuredContent, { added: 2, already_there: 0, unreadable_lines: 0 });
140 out = await call('import_statement', { account_id: checking.id, text: OFX }, W);
141 assert.deepStrictEqual(out.structuredContent, { added: 0, already_there: 2, unreadable_lines: 0 }, 'the same download twice adds nothing');
142 out = await call('import_statement', { account_id: boAcc.id, text: OFX }, W);
143 assert.match(out.content[0].text, /No such account of yours/, 'never another person\'s account');
144 out = await call('import_statement', { account_id: checking.id }, W);
145 assert.match(out.content[0].text, /import_statement needs "text"/);
146
147 const novTx = (await store.transactions(ADA, checking.id, { month: '2026-11' }));
148 const grocer = novTx.find((t) => t.payee === 'CORNER GROCER');
149 const movie = novTx.find((t) => t.payee === 'MOVIE PASS 4421');
150 const rent = novTx.find((t) => t.payee === 'Rent');
151 await store.setCategory(ADA, rent.id, 'Housing'); // the person's own choice
152 out = await call('categorize', { items: [{ transaction_id: grocer.id, category: 'Groceries' }, { transaction_id: rent.id, category: 'Shopping' }, { transaction_id: 'txn_nope', category: 'Fees' }] }, W);
153 assert.deepStrictEqual(out.structuredContent, { changed: 1, kept_yours: 1, not_found: 1 }, 'an agent never overwrites the person\'s own category');
154 const after = await store.transactions(ADA, checking.id, { month: '2026-11' });
155 assert.deepStrictEqual([after.find((t) => t.id === grocer.id).category_from, after.find((t) => t.id === rent.id).category], ['ai', 'Housing']);
156 const acctPage = await fetch(`${base}/accounts/${checking.id}?m=2026-11`, { headers: { 'x-test-user': ADA } }).then((x) => x.text());
157 assert.match(acctPage, /class="fin-by-agent"[^>]*>agent<\/span>/, 'the page marks what an agent set');
158 out = await call('categorize', { items: [{ transaction_id: grocer.id, category: 'Eating out' }] }, `person:${ADA}`);
159 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');
160 out = await call('categorize', { items: [] }, W);
161 assert.match(out.content[0].text, /"items" is a list of 1 to 200 items/);
162
163 out = await call('add_rule', { match: 'movie pass', category: 'Subscriptions' }, W);
164 assert.deepStrictEqual(out.structuredContent.rule, { match: 'movie pass', category: 'Subscriptions' });
165 assert.ok(out.structuredContent.applied_now >= 1, 'it applies to what is uncategorised now');
166 assert.strictEqual((await store.transactions(ADA, checking.id, { month: '2026-11' })).find((t) => t.id === movie.id).category, 'Subscriptions');
167 out = await call('add_transaction', { account_id: checking.id, posted_on: '2026-11-17', amount_cents: -1250, payee: 'Bakery', category: 'Eating out' }, W);
168 assert.strictEqual(out.structuredContent.transaction.payee, 'Bakery');
169 out = await call('add_transaction', { account_id: checking.id, posted_on: '17 Nov', amount_cents: -1, payee: 'x' }, W);
170 assert.match(out.content[0].text, /"posted_on" is not right/);
171
172 // The pages and the API never take a delegated person.
173 const api = await fetch(`${base}/api/v1/accounts`, { headers: { 'x-test-user': ADA, 'x-test-delegated': '1' } });
174 assert.strictEqual(api.status, 401, 'the API refuses something acting for the person');
175 const pageRes = await fetch(`${base}/data`, { redirect: 'manual', headers: { 'x-test-user': ADA, 'x-test-delegated': '1' } });
176 assert.ok([302, 303].includes(pageRes.status), 'and so do the pages');
177 assert.strictEqual((await fetch(`${base}/mcp`)).status, 405);
178 } finally {
179 server.close();
180 await close();
181 }
182 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');
183})().catch((err) => { console.error(err); process.exit(1); });
184