///
import { openDatabase } from "../db.ts";
import type { DatabaseSync } from "node:sqlite";
import { handleMcpRequest } from "./server.ts";
import { mintToken, type TokenPrincipal } from "../services/api-tokens.ts";
const MIGRATIONS_DIR = new URL("../../../../migrations", import.meta.url)
.pathname.replace(/^\/([A-Za-z]:)/, "$1");
const PROTOCOL = "2025-06-18";
function testDb(): DatabaseSync {
const db = openDatabase(`${Deno.makeTempDirSync()}/test.db`, MIGRATIONS_DIR);
const now = new Date().toISOString();
db.prepare(
"INSERT INTO users (did, handle, created_at) VALUES ('did:plc:t','tester',?)",
).run(now);
db.prepare(
"INSERT INTO connections (access_url, claimed_at) VALUES ('https://u:p@x/simplefin',?)",
).run(now);
db.prepare(
`INSERT INTO accounts (id, connection_id, name, currency, state, created_at)
VALUES ('act-1', 1, 'Checking', 'USD', 'ACTIVE', ?)`,
).run(now);
db.prepare(
"INSERT INTO categories (name, kind, created_at) VALUES ('Groceries','expense',?)",
).run(now);
return db;
}
function insertTxn(db: DatabaseSync, sfinId: string): number {
const result = db.prepare(
`INSERT INTO transactions (account_id, sfin_id, posted, amount_cents, description, pending, created_at)
VALUES ('act-1', ?, 1750000000, -1000, 'COFFEE', 0, ?)`,
).run(sfinId, new Date().toISOString());
return Number(result.lastInsertRowid);
}
/** POST one JSON-RPC message through the real transport and parse the result. */
async function rpc(
db: DatabaseSync,
principal: TokenPrincipal,
method: string,
params: unknown,
id = 1,
): Promise> {
const request = new Request("http://local/mcp", {
method: "POST",
headers: {
"content-type": "application/json",
"accept": "application/json, text/event-stream",
"mcp-protocol-version": PROTOCOL,
},
body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
});
const response = await handleMcpRequest(request, db, principal);
const body = JSON.parse(await response.text());
return body.result as Record;
}
/** The parsed JSON payload a tool returned in its text content. */
function toolData(result: Record): unknown {
const content = result.content as { type: string; text: string }[];
return JSON.parse(content[0].text);
}
function isError(result: Record): boolean {
return result.isError === true;
}
Deno.test("tools/list exposes the full 15-tool catalog to a read token", async () => {
const db = testDb();
const { summary } = mintToken(db, "reader", "read");
const principal: TokenPrincipal = {
id: summary.id,
scope: "read",
userDid: null,
};
const result = await rpc(db, principal, "tools/list", {});
const names = (result.tools as { name: string }[]).map((t) => t.name).sort();
const expected = [
"apply_rules",
"categorize_transaction",
"create_category",
"create_rule",
"get_monthly_report",
"get_net_worth",
"get_sync_status",
"get_transaction_history",
"list_accounts",
"list_categories",
"list_rules",
"list_transactions",
"probe_rule",
"set_rule_active",
"trigger_sync",
];
if (JSON.stringify(names) !== JSON.stringify(expected)) {
throw new Error(`catalog mismatch: ${JSON.stringify(names)}`);
}
db.close();
});
Deno.test("a read token is refused every write tool", async () => {
const db = testDb();
const txId = insertTxn(db, "t1");
const { summary } = mintToken(db, "reader", "read");
const principal: TokenPrincipal = {
id: summary.id,
scope: "read",
userDid: "did:plc:t",
};
const writeCalls: [string, unknown][] = [
["categorize_transaction", { transactionId: txId, categoryId: 1 }],
["create_category", { name: "New", kind: "expense" }],
["create_rule", {
matchType: "contains",
pattern: "COFFEE",
categoryId: 1,
}],
["set_rule_active", { ruleId: 1, active: false }],
["apply_rules", {}],
["trigger_sync", {}],
];
for (const [name, args] of writeCalls) {
const result = await rpc(db, principal, "tools/call", {
name,
arguments: args,
});
if (!isError(result)) {
throw new Error(`write tool ${name} was not refused for a read token`);
}
}
// Nothing was written: the transaction is still uncategorized.
const cat = (db.prepare("SELECT category_id FROM transactions WHERE id = ?")
.get(txId) as { category_id: number | null }).category_id;
if (cat !== null) throw new Error("a refused write still mutated data");
db.close();
});
Deno.test("a readwrite token categorizes, recording an agent event", async () => {
const db = testDb();
const txId = insertTxn(db, "t1");
const { summary } = mintToken(db, "claude", "readwrite");
const principal: TokenPrincipal = {
id: summary.id,
scope: "readwrite",
userDid: "did:plc:t",
};
const result = await rpc(db, principal, "tools/call", {
name: "categorize_transaction",
arguments: { transactionId: txId, categoryId: 1 },
});
const data = toolData(result) as { applied: boolean };
if (!data.applied) throw new Error("categorize did not apply");
const event = db.prepare(
"SELECT source, api_token_id FROM categorization_events WHERE transaction_id = ? ORDER BY id DESC LIMIT 1",
).get(txId) as { source: string; api_token_id: number | null };
if (event.source !== "agent" || event.api_token_id !== summary.id) {
throw new Error(`event not agent-sourced: ${JSON.stringify(event)}`);
}
db.close();
});
Deno.test("probe_rule mutates nothing", async () => {
const db = testDb();
insertTxn(db, "t1");
const { summary } = mintToken(db, "reader", "read");
const principal: TokenPrincipal = {
id: summary.id,
scope: "read",
userDid: null,
};
const before = (db.prepare(
"SELECT COUNT(*) AS n FROM categorization_events",
).get() as { n: number }).n;
const result = await rpc(db, principal, "tools/call", {
name: "probe_rule",
arguments: { matchType: "contains", pattern: "COFFEE" },
});
const data = toolData(result) as { uncategorizedMatchCount: number };
if (data.uncategorizedMatchCount !== 1) {
throw new Error(`expected 1 match, got ${data.uncategorizedMatchCount}`);
}
const after = (db.prepare(
"SELECT COUNT(*) AS n FROM categorization_events",
).get() as { n: number }).n;
if (before !== after) throw new Error("probe_rule wrote an event");
db.close();
});