Something went wrong. Try again.
A self-hosted household ledger.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";import { z } from "zod";import type { DatabaseSync } from "node:sqlite";import type { TokenPrincipal } from "../services/api-tokens.ts";
import { listAccounts, listStaleAccounts } from "../services/accounts.ts";import { type LedgerFilters, listLedger, listMonths,} from "../services/ledger.ts";import { categorizeByAgent, listEvents } from "../services/categorization.ts";import { monthlyReport, netWorthSeries, pendingStats,} from "../services/reports.ts";import { type CategoryKind, createCategory, listCategories,} from "../services/categories.ts";import { applyRulesToUncategorized, countRuleMatches, createRule, listRules, probeRule, ruleMatchHealth, type RuleProbe, setRuleActive,} from "../services/rules.ts";import { getConnectionErrors, getLastSync } from "../services/sync-status.ts";import { runSync } from "../services/sync.ts";
// A tool result carrying JSON data as text. Every tool returns plain service// data this way; the agent reads structured JSON, and any MCP host renders it.type ToolResult = { content: { type: "text"; text: string }[]; isError?: boolean;};
function json(data: unknown): ToolResult { return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }] };}
function error(message: string): ToolResult { return { content: [{ type: "text", text: message }], isError: true };}
// An agent looping on trigger_sync would hammer the SimpleFIN Bridge, which// refreshes bank data only ~daily (the rationale behind the server's daily// cron). Refuse a sync that follows too closely on the last one.const MIN_SYNC_INTERVAL_MS = 15 * 60 * 1000;
const probeShape = { matchType: z.enum(["exact", "contains"]), pattern: z.string().min(1), amountCents: z.number().int().nullable().optional(),};
/** * Build a fresh MCP server for one request, with the database and the * authenticating token principal captured in closure. Read tools require any * valid token; write tools require a `readwrite` scope and are refused (not * hidden) for a `read` token. The server is transport-agnostic — it never reads * a cookie or SvelteKit event — so the desktop change can remount it verbatim. */export function buildMcpServer( db: DatabaseSync, principal: TokenPrincipal,): McpServer { const server = new McpServer({ name: "quantum", version: "1.0.0" });
const requireWrite = (): ToolResult | null => principal.scope === "readwrite" ? null : error( "This tool requires a read-write token. The presented token is read-only.", );
// ---- Read tools (any scope) ------------------------------------------
server.registerTool("list_accounts", { description: "List all accounts with balances and classification, plus which are stale (no recent successful sync).", }, () => json({ accounts: listAccounts(db), stale: listStaleAccounts(db), }));
server.registerTool("list_transactions", { description: "List transactions, filterable by account, category (a category id or 'uncategorized'), month (YYYY-MM), pending state, source, and a free-text query. Also returns the months that have data.", inputSchema: { accountId: z.string().optional(), category: z.union([z.number().int(), z.literal("uncategorized")]) .optional(), month: z.string().regex(/^\d{4}-\d{2}$/).optional(), pending: z.boolean().optional(), source: z.enum(["synced", "imported"]).optional(), q: z.string().optional(), limit: z.number().int().positive().optional(), }, }, (args: LedgerFilters) => json({ transactions: listLedger(db, args), availableMonths: listMonths(db), }));
server.registerTool( "get_transaction_history", { description: "The full, ordered categorization history (provenance chain) of one transaction: every rule, person, reconciliation, or agent event that set its category.", inputSchema: { transactionId: z.number().int() }, }, ({ transactionId }: { transactionId: number }) => json(listEvents(db, transactionId)), );
server.registerTool("get_monthly_report", { description: "Income vs. expense totals by category for one month (YYYY-MM), plus pending-transaction stats for that month.", inputSchema: { month: z.string().regex(/^\d{4}-\d{2}$/) }, }, ({ month }: { month: string }) => json({ report: monthlyReport(db, month), pending: pendingStats(db, month), }));
server.registerTool("get_net_worth", { description: "The net-worth-over-time series, one point per date across all non-hidden accounts.", }, () => json(netWorthSeries(db)));
server.registerTool( "list_categories", { description: "List categories with their kind (income, expense, or transfer). Pass activeOnly to exclude deactivated ones.", inputSchema: { activeOnly: z.boolean().optional() }, }, ({ activeOnly }: { activeOnly?: boolean }) => json(listCategories(db, { activeOnly })), );
server.registerTool("list_rules", { description: "List categorization rules. Pass includeHealth to attach each rule's match health (when it last fired, recent pattern-hit/amount-miss drift).", inputSchema: { activeOnly: z.boolean().optional(), includeHealth: z.boolean().optional(), }, }, ( { activeOnly, includeHealth }: { activeOnly?: boolean; includeHealth?: boolean; }, ) => { const rules = listRules(db, { activeOnly }); if (!includeHealth) return json(rules); return json( rules.map((rule) => ({ ...rule, health: ruleMatchHealth(db, rule) })), ); });
server.registerTool("probe_rule", { description: "Dry-run a rule pattern WITHOUT creating it: returns how many uncategorized transactions it would newly categorize, plus the matching transactions labelled by their current status. Always probe before create_rule.", inputSchema: probeShape, }, (probe: RuleProbe) => json({ uncategorizedMatchCount: countRuleMatches(db, probe), hits: probeRule(db, probe).slice(0, 200), }));
server.registerTool("get_sync_status", { description: "The most recent sync's outcome and timestamp, plus any current connection-level errors.", }, () => json({ lastSync: getLastSync(db), connectionErrors: getConnectionErrors(db), }));
// ---- Write tools (readwrite scope) -----------------------------------
server.registerTool("categorize_transaction", { description: "Set (or clear, with a null category) a transaction's category as the agent. Refused if a person manually set the category — humans outrank agents.", inputSchema: { transactionId: z.number().int(), categoryId: z.number().int().nullable(), }, }, ( { transactionId, categoryId }: { transactionId: number; categoryId: number | null; }, ) => { const denied = requireWrite(); if (denied) return denied; const applied = categorizeByAgent( db, transactionId, categoryId, principal.id, ); return applied ? json({ applied: true }) : json({ applied: false, reason: "Refused: a person manually set this transaction's category, which an agent may not overwrite.", }); });
server.registerTool("create_category", { description: "Create a new category with a name and kind.", inputSchema: { name: z.string().min(1), kind: z.enum(["income", "expense", "transfer"]), }, }, ({ name, kind }: { name: string; kind: CategoryKind }) => { const denied = requireWrite(); if (denied) return denied; return json(createCategory(db, name, kind)); });
server.registerTool("create_rule", { description: "Create a categorization rule. Probe the pattern with probe_rule first to see its blast radius. A text pattern is required; an amount constraint is optional.", inputSchema: { matchType: z.enum(["exact", "contains"]), pattern: z.string().min(1), categoryId: z.number().int(), amountCents: z.number().int().nullable().optional(), displayName: z.string().nullable().optional(), }, }, ( { matchType, pattern, categoryId, amountCents, displayName }: { matchType: "exact" | "contains"; pattern: string; categoryId: number; amountCents?: number | null; displayName?: string | null; }, ) => { const denied = requireWrite(); if (denied) return denied; if (!principal.userDid) { return error( "Creating a rule requires a token bound to a user; this token has none.", ); } return json(createRule(db, { matchType, pattern, categoryId, amountCents, displayName, createdByDid: principal.userDid, })); });
server.registerTool("set_rule_active", { description: "Enable or disable a rule by id.", inputSchema: { ruleId: z.number().int(), active: z.boolean() }, }, ({ ruleId, active }: { ruleId: number; active: boolean }) => { const denied = requireWrite(); if (denied) return denied; setRuleActive(db, ruleId, active); return json({ ruleId, active }); });
server.registerTool("apply_rules", { description: "Run the active rulebook over currently-uncategorized transactions, categorizing those that match. Optionally limit to specific rule ids. Never overwrites a manual choice. Returns how many transactions were categorized.", inputSchema: { ruleIds: z.array(z.number().int()).optional() }, }, ({ ruleIds }: { ruleIds?: number[] }) => { const denied = requireWrite(); if (denied) return denied; return json({ categorized: applyRulesToUncategorized(db, { ruleIds }) }); });
server.registerTool("trigger_sync", { description: "Pull fresh transaction data from SimpleFIN for every connection. SimpleFIN refreshes bank data roughly daily, so this is rate-limited; a call too soon after the last sync is skipped.", }, async () => { const denied = requireWrite(); if (denied) return denied; const last = getLastSync(db); if (last) { const sinceMs = Date.now() - new Date(last.fetchedAt).getTime(); if (sinceMs < MIN_SYNC_INTERVAL_MS) { return json({ skipped: true, reason: `Last sync was ${Math.round(sinceMs / 60000)} minute(s) ago. ` + "SimpleFIN updates roughly daily; try again later.", lastSync: last, }); } } return json({ outcomes: await runSync(db) }); });
return server;}
/** Whether a path targets the MCP endpoint. */export function isMcpPath(path: string): boolean { return path === "/mcp" || path.startsWith("/mcp/");}
/** * Handle one MCP request: build a per-request server (stateless), connect it to * a web-standard transport, and let the transport produce the Response. Pure * `Request → Response`, no SvelteKit or cookie dependency. */export async function handleMcpRequest( request: Request, db: DatabaseSync, principal: TokenPrincipal,): Promise<Response> { const server = buildMcpServer(db, principal); const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, // stateless enableJsonResponse: true, }); await server.connect(transport); return transport.handleRequest(request);}