openvibers/openvibe.finance Commits

/mcp: read your money as you, for agents you allow (v0.8) (#8)

OP OpenVibers committed 13 days ago · 1e6de6cc77 · 7 files, +354 −11

Plan §L.2 ("all through an SDK, with Finance Experts on top … narrow permissions, never a bank login").
POST /mcp is an MCP server with seven read-only tools: accounts, month (with budgets), transactions,
recurring, goals (with debt payoff), net_worth, what_if. Both MCP eras on one endpoint (openvibe-sdk/mcp).
- Anyone may list the tools; a call reads the person from a Bearer token only (cookies are dropped on
  /mcp): their own sign-in, or a delegated person token naming finance (SDK 0.187), which Network mints
  per call for a key with a grant in OpenVibe Finance. A second sign-in client takes delegated tokens
  and is used on /mcp alone; the pages and the API refuse a delegated person (who() checks it too).
- Arguments are checked against each tool's schema; no tool writes or moves money.
test/mcp.test.js.

Changes

ddiff --git a/README.md b/README.md
iindex 096cbe9..9fb82de 100644
---- a/README.md
++++ b/README.md
@@@ -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.7)
++## What it does today (v0.8)
- 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:
@@@ -39,6 +39,18 @@ to connect.
Plan: `OpenVibe_Plan_2026-11-13.md` §L.2. Next: the Link plugin
for local-only import, and Finance Experts (Budget Coach, Subscription Auditor) with narrow read permission.
++## For agents: /mcp
++
++`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`.
++
++- 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 an agent with a grant in **OpenVibe Finance** (Connect; `https://connect.openvibe.network/mcp/all`).
++- The pages and the JSON API never take a delegated token: only the person changes anything, and nothing here moves
++ money.
++
## Running
```bash
ddiff --git a/package-lock.json b/package-lock.json
iindex 35227b4..52da5db 100644
---- a/package-lock.json
++++ b/package-lock.json
@@@ -1,12 +1,12 @@
{
"name": "openvibe-finance",
-- "version": "0.7.0",
++ "version": "0.8.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "openvibe-finance",
-- "version": "0.7.0",
++ "version": "0.8.0",
"license": "AGPL-3.0-only",
"dependencies": {
"@electric-sql/pglite": "^0.5.8",
ddiff --git a/package.json b/package.json
iindex a78bf34..6c6bfd1 100644
---- a/package.json
++++ b/package.json
@@@ -1,6 +1,6 @@
{
"name": "openvibe-finance",
-- "version": "0.7.0",
++ "version": "0.8.0",
"private": true,
"description": "Your money, your rules, your data: accounts, CSV imports and a monthly picture, private to you",
"main": "server/index.js",
ddiff --git a/server/app.js b/server/app.js
iindex f33994c..5ef7896 100644
---- a/server/app.js
++++ b/server/app.js
@@@ -2,8 +2,10 @@
/**
* OpenVibe.Finance (plan §L.2): the pages and the JSON API over one person's accounts and transactions.
*
-- * createApp({ db, vault, auth, baseUrl }) → an Express app
++ * createApp({ db, vault, auth, mcpAuth, baseUrl }) → an Express app
* auth: openvibe-sdk/sso's client (router, optionalAuth); tests pass a stand-in that sets req.user.
++ * mcpAuth: a second client that also takes a delegated person token naming finance, used on POST /mcp only
++ * (server/mcp.js); without it /mcp reads the person from a Bearer token of the ordinary client.
*
* Pages: / (signed out: what it is; signed in: your accounts and this month), /accounts/:id (?m=YYYY-MM), /month,
* /data (download or delete everything). API (JSON, the same person, same rules): /api/v1/accounts,
@@@ -22,7 +24,7 @@ const readExport = (text) => (isOfx(text) ? readOfx(text) : readCsv(text));
const { findRecurring } = require('./recurring');
const v = require('./views');
--function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now = () => new Date() }) {
++function createApp({ db, vault, auth, mcpAuth = null, baseUrl = 'https://openvibe.finance', now = () => new Date() }) {
const store = createStore({ db, vault });
const app = express();
app.disable('x-powered-by');
@@@ -44,10 +46,20 @@ function createApp({ db, vault, auth, baseUrl = 'https://openvibe.finance', now
app.use(express.static(path.join(__dirname, '..', 'public'), { maxAge: '1h' }));
app.use('/shared', require('openvibe-shared/serve').handler());
if (auth) app.use('/auth', auth.router(express));
++ // POST /mcp (server/mcp.js), before the pages' sign-in: a Bearer token only (never a cookie), which may be a
++ // delegated person token for this service (mcpAuth); the pages and the API below never take one.
++ 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 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()),
++ (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());
app.use((req, res, next) => { res.set('Cache-Control', 'private, no-store'); next(); });
-- const who = (req) => (req.user && /^usr_/.test(String(req.user.subject_id || '')) ? String(req.user.subject_id) : null);
++ // The pages and the API: the person's own sign-in only. A delegated token (something acting for them) is for /mcp.
++ const { isDelegated } = require('openvibe-sdk/auth/delegated');
++ const who = (req) => (req.user && !isDelegated(req.user) && /^usr_/.test(String(req.user.subject_id || '')) ? String(req.user.subject_id) : null);
const own = new URL(baseUrl).origin;
const sameOrigin = (req) => {
if (/^Bearer\s/i.test(String(req.get('authorization') || ''))) return true;
ddiff --git a/server/index.js b/server/index.js
iindex 1cc19fa..b84f4df 100644
---- a/server/index.js
++++ b/server/index.js
@@@ -21,13 +21,16 @@ async function main() {
try { await owner.migrate({ dir: path.join(__dirname, '..', 'migrations') }); } finally { await owner.close(); }
const db = createDb({ url: env.DATABASE_URL, service: 'finance' });
const vault = createVault(env.FINANCE_DATA_KEY);
-- const auth = env.OV_OAUTH_CLIENT_ID && env.OV_OAUTH_CLIENT_SECRET ? createSsoClient({
++ const sso = (more = {}) => createSsoClient({
site: 'finance', siteName: 'OpenVibe.Finance', baseUrl, clientId: env.OV_OAUTH_CLIENT_ID, clientSecret: env.OV_OAUTH_CLIENT_SECRET,
networkUrl: env.OV_NETWORK_URL || 'https://openvibe.network', networkInternalUrl: env.OV_NETWORK_INTERNAL_URL || 'http://127.0.0.1:4000',
-- secureCookies: env.NODE_ENV === 'production',
-- }) : null;
++ secureCookies: env.NODE_ENV === 'production', ...more,
++ });
++ const auth = env.OV_OAUTH_CLIENT_ID && env.OV_OAUTH_CLIENT_SECRET ? sso() : null;
++ // POST /mcp only: also a delegated person token naming finance (SDK 0.187; Network's Connect mints it per call).
++ const mcpAuth = auth ? sso({ delegated: true }) : null;
if (!auth) console.warn('[finance] no OAuth client: sign-in is off');
-- const server = createApp({ db, vault, auth, baseUrl }).listen(port, '127.0.0.1', () => console.log(`[finance] listening on 127.0.0.1:${port}`));
++ const server = createApp({ db, vault, auth, mcpAuth, baseUrl }).listen(port, '127.0.0.1', () => console.log(`[finance] listening on 127.0.0.1:${port}`));
process.on('SIGTERM', () => server.close(async () => { try { await db.close(); } finally { process.exit(0); } }));
}
ddiff --git a/server/mcp.js b/server/mcp.js
nnew file mode 100644
iindex 0000000..da777ea
---- /dev/null
++++ b/server/mcp.js
@@@ -0,0 +1,178 @@
++'use strict';
++/**
++ * Finance's MCP server, POST /mcp (plan §L.2: "all through an SDK, with Finance Experts on top … an Expert gets narrow
++ * 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."
++ * - **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
++ * refusing delegated tokens (their sign-in client does not take them).
++ * - **Both MCP eras on one endpoint** (openvibe-sdk/mcp): 2026-07-28 (stateless, _meta version) and the handshake era.
++ * - tools/list answers anyone (names and schemas only); tools/call without a person says to connect Finance.
++ *
++ * 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 { 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.';
++const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
++const MONTH = { type: 'string', pattern: '^\\d{4}-(0[1-9]|1[0-2])$', description: 'A month, YYYY-MM.' };
++const tool = (name, title, description, properties = {}) => ({
++ name, title, description,
++ inputSchema: { type: 'object', properties, additionalProperties: false },
++ annotations: { title, ...READ },
++});
++
++const TOOLS = [
++ 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.'),
++ 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 }),
++ 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.', {
++ account_id: { type: 'string', maxLength: 64, description: 'One account (from accounts); all accounts when left out.' },
++ month: MONTH, limit: { type: 'integer', minimum: 1, maximum: 500, description: 'At most this many (100 by default).' },
++ }),
++ 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.'),
++ 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).'),
++ tool('net_worth', 'Net worth over time', 'Net worth at the end of each month since the data starts (assets, owed, net, in cents).'),
++ 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.', {
++ cost_cents: { type: 'integer', minimum: 0, maximum: 1e11, description: 'A one-off cost.' },
++ cost_on: { ...MONTH, description: 'The month it is paid (next month by default), within the next twelve.' },
++ change_cents: { type: 'integer', minimum: 0, maximum: 1e11, description: 'A change every month.' },
++ 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).' },
++ }),
++];
++
++function createMcp({ store, aheadFor, now = () => new Date() }) {
++ const today = () => now().toISOString().slice(0, 10);
++
++ const RUN = {
++ async accounts(me) {
++ 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 })) };
++ },
++ async month(me, args) {
++ const m = await store.month(me, args.month || today().slice(0, 7));
++ const limit = new Map((await store.budgets(me)).map((b) => [b.category, b.monthly_cents]));
++ return {
++ month: m.month, income_cents: m.income_cents, spent_cents: m.spent_cents,
++ by_category: m.by_category.map((c) => ({ category: c.category, in_cents: c.in_cents, out_cents: c.out_cents, count: c.count,
++ ...(limit.has(c.category) ? { budget_cents: limit.get(c.category), left_cents: limit.get(c.category) - c.out_cents } : {}) })),
++ budgets_unspent: [...limit].filter(([cat]) => !m.by_category.some((c) => c.category === cat)).map(([category, cents]) => ({ category, budget_cents: cents, left_cents: cents })),
++ };
++ },
++ async transactions(me, args) {
++ const limit = args.limit || 100;
++ const ids = args.account_id ? [String(args.account_id)] : (await store.accounts(me)).map((a) => a.id);
++ if (args.account_id && !(await store.account(me, args.account_id))) throw new FinanceError(404, 'finance.account.not_found', 'No such account of yours.');
++ const all = [];
++ for (const id of ids) all.push(...await store.transactions(me, id, { month: args.month || null, limit }));
++ all.sort((a, b) => (a.posted_on < b.posted_on ? 1 : a.posted_on > b.posted_on ? -1 : 0));
++ 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 })) };
++ },
++ async recurring(me) {
++ return { recurring: findRecurring(await store.recent(me), { today: today() }).map(({ key, ...r }) => r) };
++ },
++ async goals(me) {
++ const accounts = await store.accounts(me);
++ return {
++ 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 })),
++ debts: accounts.filter((a) => a.kind === 'loan' || a.kind === 'credit').map((a) => {
++ const owed = Math.max(0, -a.balance_cents);
++ 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;
++ 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) };
++ }),
++ };
++ },
++ async net_worth(me) {
++ return { net_worth: (await aheadFor(me)).net_worth };
++ },
++ async what_if(me, args) {
++ const q = {};
++ if (args.cost_cents) q.cost = (args.cost_cents / 100).toFixed(2);
++ if (args.cost_on) q.cost_on = args.cost_on;
++ if (args.change_cents) q.change = (args.change_cents / 100).toFixed(2);
++ if (args.direction) q.dir = args.direction;
++ if (args.from) q.from = args.from;
++ const a = await aheadFor(me, q);
++ if (a.error) throw new FinanceError(422, 'finance.ahead.ask', a.error);
++ if (!a.plan) return { average: a.average, plan: null, note: 'Not enough history: the months before this one have no transactions.' };
++ return { average: a.average, spendable_cents: a.spendable_cents, goals_need_cents: a.goals_need_cents, plan: a.plan };
++ },
++ };
++
++ /** The arguments against the tool's schema: only its own keys, the right types, in range. → a message or null. */
++ 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, 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'}`;
++ }
++ return null;
++ }
++
++ const asResult = (value) => ({ content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value, isError: false });
++ const asError = (message) => ({ content: [{ type: 'text', text: message }], isError: true });
++
++ async function call(req, params) {
++ const def = TOOLS.find((t) => t.name === String(params && params.name));
++ if (!def) return { error: { code: mcp.ERRORS.invalidParams, message: `No tool named ${String(params && params.name)}.` } };
++ const me = req.user && /^usr_/.test(String(req.user.subject_id || '')) ? String(req.user.subject_id) : null;
++ 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.') };
++ 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) {
++ if (err instanceof FinanceError) return { result: asError(err.message) };
++ throw err;
++ }
++ }
++
++ async function handler(req, res) {
++ const body = req.body && typeof req.body === 'object' ? req.body : {};
++ const id = Object.prototype.hasOwnProperty.call(body, 'id') ? body.id : null;
++ const method = body.method;
++ const params = body.params && typeof body.params === 'object' ? body.params : {};
++ const reply = (result, status = 200) => res.status(status).json({ jsonrpc: '2.0', id, result });
++ const fail = (status, error) => res.status(status).json({ jsonrpc: '2.0', id, error });
++ if (body.jsonrpc !== '2.0' || typeof method !== 'string') return fail(400, { code: mcp.ERRORS.invalidRequest, message: 'A JSON-RPC 2.0 request.' });
++ const modern = mcp.requestVersion(params);
++ if (modern) {
++ const bad = mcp.checkRequest({ header: (n) => req.get(n), method, params });
++ if (bad) return fail(bad.status, bad.error);
++ }
++ if (!Object.prototype.hasOwnProperty.call(body, 'id') || method.startsWith('notifications/')) return res.status(202).end();
++ switch (method) {
++ case 'initialize':
++ return reply({ protocolVersion: mcp.legacyVersion(params.protocolVersion), capabilities: { tools: { listChanged: false } }, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS });
++ case 'server/discover':
++ return reply(mcp.discoverResult({ serverInfo: SERVER_INFO, capabilities: { tools: { listChanged: false } }, instructions: INSTRUCTIONS }));
++ case 'ping':
++ return reply(modern ? mcp.complete({}) : {});
++ case 'tools/list':
++ return reply(modern ? mcp.listResult('tools', TOOLS, { cacheScope: 'public' }) : { tools: TOOLS });
++ case 'tools/call': {
++ const out = await call(req, params);
++ if (out.error) return fail(200, out.error);
++ return reply(modern ? mcp.complete(out.result) : out.result);
++ }
++ default: {
++ const nf = mcp.methodNotFound(method);
++ return fail(nf.status, nf.error);
++ }
++ }
++ }
++
++ return { tools: TOOLS, handler };
++}
++
++module.exports = { createMcp, TOOLS };
ddiff --git a/test/mcp.test.js b/test/mcp.test.js
nnew file mode 100644
iindex 0000000..43fda7a
---- /dev/null
++++ b/test/mcp.test.js
@@@ -0,0 +1,138 @@
++'use strict';
++/**
++ * Finance's MCP server (server/mcp.js, POST /mcp): seven read-only tools; anyone may list them; a call reads the person
++ * from a Bearer token only (a delegated person token naming finance included), never from a cookie or the pages'
++ * sign-in; the pages and the API refuse a delegated person; each tool answers the person's own data only; arguments are
++ * checked against the schema; both MCP eras (handshake and 2026-07-28 stateless) on one endpoint.
++ */
++const assert = require('assert');
++const path = require('node:path');
++const crypto = require('node:crypto');
++const mcp = require('openvibe-sdk/mcp');
++const { createTestDb } = require('openvibe-sdk/testing');
++const { createVault } = require('../server/crypto');
++const { createStore } = require('../server/store');
++const { createApp } = require('../server/app');
++
++const ADA = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAW';
++const BO = 'usr_01JCZ3NDEKTSV4RRFFQ69G5FAX';
++
++(async () => {
++ const { db, close } = await createTestDb({ migrations: path.join(__dirname, '..', 'migrations'), store: process.env.FINANCE_TEST_STORE || 'pglite', service: 'finance' });
++ const vault = createVault(crypto.randomBytes(32).toString('base64'));
++ const store = createStore({ db, vault });
++ // The pages' sign-in: x-test-user (x-test-delegated makes that person a delegated one, which the pages must refuse).
++ const auth = { router: (express) => express.Router(), optionalAuth: () => (req, _res, next) => {
++ const u = req.get('x-test-user');
++ 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.
++ 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] };
++ next();
++ } };
++ const server = createApp({ db, vault, auth, mcpAuth, now: () => new Date('2026-11-18T12:00:00Z') }).listen(0, '127.0.0.1');
++ await new Promise((r) => server.once('listening', r));
++ const base = `http://127.0.0.1:${server.address().port}`;
++ let n = 0;
++ const rpc = async (method, params = {}, headers = {}) => {
++ const r = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify({ jsonrpc: '2.0', id: ++n, method, params }) });
++ return { status: r.status, body: r.status === 202 ? null : await r.json() };
++ };
++ const call = async (name, args, as = `delegated:${ADA}`) => (await rpc('tools/call', { name, arguments: args }, as ? { authorization: `Bearer ${as}` } : {})).body.result;
++ try {
++ const checking = await store.addAccount(ADA, { name: 'Checking', kind: 'checking', opening_cents: 100000 });
++ const card = await store.addAccount(ADA, { name: 'Visa', kind: 'credit', opening_cents: -500000 });
++ await store.setDebt(ADA, card.id, { apr_bps: 2499, payment_cents: 15000 });
++ const rows = [];
++ for (const m of ['2026-08', '2026-09', '2026-10', '2026-11']) {
++ rows.push({ posted_on: `${m}-01`, amount_cents: 300000, payee: 'Paycheck', category: 'Income' });
++ rows.push({ posted_on: `${m}-03`, amount_cents: -150000, payee: 'Rent', category: 'Housing' });
++ rows.push({ posted_on: `${m}-05`, amount_cents: -1599, payee: 'StreamFlix', category: 'Subscriptions' });
++ }
++ await store.importRows(ADA, checking.id, rows);
++ await store.setBudget(ADA, 'Subscriptions', 1000);
++ await store.addGoal(ADA, { name: 'Trip', target_cents: 120000, target_on: '2027-11-01' });
++ const boAcc = await store.addAccount(BO, { name: 'Bo private', kind: 'checking', opening_cents: 999900 });
++
++ // The handshake era, as Network's /mcp/all calls it.
++ let r = await rpc('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } });
++ assert.strictEqual(r.body.result.protocolVersion, '2025-06-18');
++ assert.strictEqual(r.body.result.serverInfo.name, 'openvibe-finance');
++ const note = await fetch(`${base}/mcp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) });
++ 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');
++
++ // Nobody, or a cookie-style sign-in, is not a person here.
++ assert.match((await call('accounts', {}, null)).content[0].text, /connect OpenVibe Finance/);
++ r = await rpc('tools/call', { name: 'accounts', arguments: {} }, { 'x-test-user': ADA });
++ assert.strictEqual(r.body.result.isError, true, 'the pages\' sign-in does not reach /mcp');
++
++ let out = await call('accounts', {});
++ assert.deepStrictEqual(out.structuredContent.accounts.map((a) => [a.name, a.balance_cents]), [['Checking', 100000 + 4 * (300000 - 150000 - 1599)], ['Visa', -500000]]);
++ assert.ok(!JSON.stringify(out).includes('Bo private'), 'another person\'s accounts never');
++ out = await call('accounts', {}, `person:${ADA}`);
++ assert.strictEqual(out.isError, false, 'the person\'s own Bearer sign-in works too');
++
++ out = await call('month', { month: '2026-10' });
++ 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 });
++ out = await call('transactions', { month: '2026-11', limit: 2 });
++ 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');
++ out = await call('transactions', { account_id: boAcc.id });
++ assert.match(out.content[0].text, /No such account of yours/);
++ out = await call('recurring', {});
++ assert.ok(out.structuredContent.recurring.some((x) => x.payee === 'StreamFlix' && x.cadence === 'monthly'));
++ out = await call('goals', {});
++ assert.deepStrictEqual(out.structuredContent.debts.map((d) => [d.name, d.owed_cents, d.payoff_months, d.interest_cents]), [['Visa', 500000, 58, 362226]]);
++ assert.strictEqual(out.structuredContent.goals[0].name, 'Trip');
++ out = await call('net_worth', {});
++ assert.strictEqual(out.structuredContent.net_worth[0].month, '2026-08');
++ out = await call('what_if', { cost_cents: 50000000 });
++ assert.ok(out.structuredContent.plan.below_zero_on, 'a $500,000 cost does not fit');
++ out = await call('what_if', { change_cents: 10000, direction: 'out', from: '2027-02' });
++ assert.strictEqual(out.structuredContent.plan.left_with_cents, out.structuredContent.plan.left_now_cents - 10000);
++
++ 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/]]) {
++ out = await call(name, args);
++ assert.strictEqual(out.isError, true, name);
++ assert.match(out.content[0].text, said);
++ }
++ r = await rpc('tools/call', { name: 'pay_bill', arguments: {} }, { authorization: `Bearer delegated:${ADA}` });
++ assert.strictEqual(r.body.error.code, -32602, 'there is no tool that moves money');
++
++ // The 2026-07-28 era: stateless, headers that agree with the body.
++ const modern = async (method, params, auth) => {
++ const { headers, body } = mcp.modernRequest({ id: ++n, method, params, clientInfo: { name: 't', version: '1' } });
++ const res = await fetch(`${base}/mcp`, { method: 'POST', headers: { ...headers, ...(auth ? { authorization: auth } : {}) }, body: JSON.stringify(body) });
++ return { status: res.status, body: await res.json() };
++ };
++ r = await modern('server/discover', {});
++ 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);
++ 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);
++ 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) });
++ assert.strictEqual(lie.status, 400, 'headers that disagree with the body are refused');
++ r = await modern('resources/list', {});
++ assert.strictEqual(r.status, 404);
++
++ // 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');
++ const pageRes = await fetch(`${base}/data`, { redirect: 'manual', headers: { 'x-test-user': ADA, 'x-test-delegated': '1' } });
++ assert.ok([302, 303].includes(pageRes.status), 'and so do the pages');
++ assert.strictEqual((await fetch(`${base}/mcp`)).status, 405);
++ } finally {
++ 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');
++})().catch((err) => { console.error(err); process.exit(1); });