diff --git a/README.md b/README.md index a3b2819..812311e 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,21 @@ brokeless runs in Docker, so it can't use a Claude login of its own. Instead, Cl Claude only answers while that command runs. It starts Claude with every tool off, in an empty folder, so it can't touch your files. Works on Windows, macOS and Linux. +## Connect Claude Code (MCP) + +brokeless is an MCP server too, so an AI app like Claude Code can read your money summary and fix things for you: find a rule that catches too much, delete it and undo what it did, make better rules, recategorize, mark transfers, merge accounts. + +1. In brokeless: Connect your AI, **Connect an AI app (MCP)**, **Make a token**. It shows once. +2. Run the command it shows on your computer: + + ```bash + claude mcp add --transport http brokeless https://brokeless.mangavalk.com/api/mcp --header "Authorization: Bearer " + ``` + +3. Start a new Claude Code session and ask, for example: "Which of my brokeless rules catch too much?" + +It is summary only, like broke ai: rounded amounts, months not days, names as placeholders (⟨M1⟩, ⟨A1⟩), never single transactions. Changes act on your real data, and Claude says what it will change first. Revoke a token on the same page. With AI switched off in Settings the endpoint refuses. + ## How AI stays private Every AI path goes through one gate. A cloud model gets a summary: rounded amounts, names replaced by tokens. Full detail goes only to a local model, which is what Ollama is here. You can turn AI off in Settings. Each answer runs with no way to change your data. diff --git a/src/app/(app)/connect-ai/page.tsx b/src/app/(app)/connect-ai/page.tsx index 92e7118..c46743e 100644 --- a/src/app/(app)/connect-ai/page.tsx +++ b/src/app/(app)/connect-ai/page.tsx @@ -1,4 +1,5 @@ import { ConnectAI } from "@/components/ConnectAI"; +import { McpTokens } from "@/components/McpTokens"; import { getUser } from "@/lib/data"; import { savedChoice } from "@/lib/llm/gate"; import { isHosted, providersFor } from "@/lib/llm/providers"; @@ -6,5 +7,10 @@ import { isHosted, providersFor } from "@/lib/llm/providers"; export default async function ConnectAIPage({ searchParams }: { searchParams: Promise<{ connected?: string; error?: string }> }) { const { user } = await getUser(); const [providers, q] = await Promise.all([providersFor(user!.id), searchParams]); - return ; + return ( +
+ + +
+ ); } diff --git a/src/app/api/accounts/merge/route.ts b/src/app/api/accounts/merge/route.ts index 9ff4ed8..dfe135e 100644 --- a/src/app/api/accounts/merge/route.ts +++ b/src/app/api/accounts/merge/route.ts @@ -1,58 +1,18 @@ import { NextResponse } from "next/server"; -import { planMerge, type MergeRow } from "@/lib/merge"; +import { mergeAccounts } from "@/lib/merge-run"; import { sameOrigin } from "@/lib/setup"; import { createAdminClient } from "@/utils/supabase/admin"; import { createClient } from "@/utils/supabase/server"; -// Merge an imported account into another of the person's accounts (usually the one their bank link made). -// preview: true only counts. Both accounts must be theirs, and only an imported (manual) one can be merged away: -// a linked account would come back on the next sync. -const COLS = "id, date, amount, category_id, custom_name, note, tags, ignored, plaid_transaction_id"; - -async function rowsOf(db: ReturnType, userId: string, accountId: string) { - const out: MergeRow[] = []; - for (let from = 0; ; from += 1000) { - const { data, error } = await db.from("transactions").select(COLS).eq("user_id", userId).eq("account_id", accountId).order("date").range(from, from + 999); - if (error) throw error; - out.push(...(data ?? []).map(({ plaid_transaction_id, ...r }) => ({ ...r, fromBank: !!plaid_transaction_id }) as MergeRow)); - if ((data ?? []).length < 1000) return out; - } -} -const chunks = (xs: T[], n = 200) => Array.from({ length: Math.ceil(xs.length / n) }, (_, i) => xs.slice(i * n, i * n + n)); - +// Merge an imported account into another of the person's accounts (lib/merge-run.ts). preview: true only counts. export async function POST(request: Request) { const { data: { user } } = await (await createClient()).auth.getUser(); if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 }); if (!sameOrigin(request)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); const { from, into, preview } = (await request.json().catch(() => ({}))) as { from?: string; into?: string; preview?: boolean }; - if (!from || !into || from === into) return NextResponse.json({ error: "Pick the account to merge into." }, { status: 400 }); - - const db = createAdminClient(); - const { data: accts } = await db.from("accounts").select("id, manual").eq("user_id", user.id).in("id", [from, into]); - const src = accts?.find((a) => a.id === from), dst = accts?.find((a) => a.id === into); - if (!src || !dst) return NextResponse.json({ error: "Account not found." }, { status: 404 }); - if (!src.manual) return NextResponse.json({ error: "Only an imported account can be merged into another." }, { status: 400 }); - try { - const plan = planMerge(await rowsOf(db, user.id, from), await rowsOf(db, user.id, into)); - const counts = { start: plan.start, moved: plan.move.length, replaced: plan.drop.length, edits: plan.edits.length }; - if (preview) return NextResponse.json(counts); - - for (const e of plan.edits) { - const { error } = await db.from("transactions").update(e.patch).eq("id", e.id).eq("user_id", user.id); - if (error) throw error; - } - for (const ids of chunks(plan.move)) { - const { error } = await db.from("transactions").update({ account_id: into }).eq("user_id", user.id).in("id", ids); - if (error) throw error; - } - // Rules and repeating charges that point at the imported account now point at the one it went into. - await db.from("rules").update({ account_id: into }).eq("user_id", user.id).eq("account_id", from); - await db.from("recurring").update({ account_id: into }).eq("user_id", user.id).eq("account_id", from); - // What's left on the imported account is the overlap the bank already has. Deleting the account takes it along. - const { error } = await db.from("accounts").delete().eq("id", from).eq("user_id", user.id); - if (error) throw error; - return NextResponse.json({ ok: true, ...counts }); + const r = await mergeAccounts(createAdminClient(), user.id, from ?? "", into ?? "", !!preview); + return r.error ? NextResponse.json({ error: r.error }, { status: r.status ?? 400 }) : NextResponse.json(r); } catch (e) { console.error("[broke] merge accounts:", e instanceof Error ? e.message : e); return NextResponse.json({ error: "Couldn't finish the merge. Try again: it picks up where it stopped." }, { status: 500 }); diff --git a/src/app/api/mcp-tokens/route.ts b/src/app/api/mcp-tokens/route.ts new file mode 100644 index 0000000..651c38a --- /dev/null +++ b/src/app/api/mcp-tokens/route.ts @@ -0,0 +1,19 @@ +import { NextResponse } from "next/server"; +import { createMcpToken } from "@/lib/llm/mcp-tokens"; +import { sameOrigin } from "@/lib/setup"; +import { createClient } from "@/utils/supabase/server"; + +// Connect your AI makes a token for the MCP endpoint here. It's returned once; listing and revoking go straight to +// the table (RLS: own rows, select and delete only). +export async function POST(request: Request) { + const { data: { user } } = await (await createClient()).auth.getUser(); + if (!user) return NextResponse.json({ error: "Not signed in" }, { status: 401 }); + if (!sameOrigin(request)) return NextResponse.json({ error: "Forbidden" }, { status: 403 }); + const { label } = (await request.json().catch(() => ({}))) as { label?: string }; + try { + return NextResponse.json({ token: await createMcpToken(user.id, typeof label === "string" ? label : "Claude") }); + } catch (e) { + console.error("[broke] mcp token:", e instanceof Error ? e.message : e); + return NextResponse.json({ error: "Couldn't make a token. If this is new, restart brokeless so the database updates." }, { status: 500 }); + } +} diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.ts new file mode 100644 index 0000000..d582e59 --- /dev/null +++ b/src/app/api/mcp/route.ts @@ -0,0 +1,58 @@ +import { Server } from "@modelcontextprotocol/sdk/server/index.js"; +import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; +import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; +import { agentClient, mintAgentToken } from "@/lib/llm/agent-auth"; +import { aiAllowed, SUMMARY_NOTE } from "@/lib/llm/gate"; +import { mcpUser } from "@/lib/llm/mcp-tokens"; +import { makeTools } from "@/lib/llm/shared"; +import { manageTools } from "@/lib/llm/tools/manage"; +import { createAdminClient } from "@/utils/supabase/admin"; + +// brokeless as an MCP server (Streamable HTTP, stateless) for AI apps such as Claude Code. A personal token from +// Settings (migration 0033) signs it in as that user; their own session runs every query, so RLS applies. +// Summary only, always: an outside AI is a cloud model (lib/llm/gate.ts). AI switched off in Settings: refused. +const READ_ONLY = new Set(["spending_summary", "search_transactions", "list_recurring", "list_accounts", "list_holdings", "get_profile", "list_categories", "list_rules"]); +const DESTRUCTIVE = new Set(["delete_rule", "merge_accounts", "recategorize"]); +const INSTRUCTIONS = `You are connected to the user's own brokeless, a personal finance app. ${SUMMARY_NOTE} +Tools that change things (create_rule, delete_rule, recategorize, find_transfers, merge_accounts) act on the real data: say what you will change and how many transactions it touches before you do it, and preview merges first.`; + +const deny = (status: number, message: string) => Response.json({ jsonrpc: "2.0", error: { code: -32001, message }, id: null }, { status }); + +async function handle(request: Request) { + const userId = await mcpUser(request.headers.get("authorization")?.replace(/^Bearer\s+/i, "") ?? null); + if (!userId) return deny(401, "Missing or revoked token. Make one in brokeless: Connect your AI, Connect an AI app (MCP)."); + const { data: { user } } = await createAdminClient().auth.admin.getUserById(userId); + if (!user) return deny(401, "That token's account is gone."); + if (!aiAllowed(user)) return deny(403, "AI is switched off in brokeless (Settings)."); + const session = await agentClient(await mintAgentToken(user)); + if (!session) return deny(503, "Couldn't open a session. Try again."); + + const tools = [...makeTools(session.supabase, user.user_metadata?.profile, user.id, "summary"), ...manageTools(session.supabase, user.id)]; + const server = new Server({ name: "brokeless", version: "1.0.0" }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS }); + server.setRequestHandler(ListToolsRequestSchema, async () => ({ + tools: tools.map((t) => ({ + name: t.name, description: t.description, inputSchema: z.toJSONSchema(t.schema) as { type: "object" }, + annotations: { readOnlyHint: READ_ONLY.has(t.name), destructiveHint: DESTRUCTIVE.has(t.name) }, + })), + })); + server.setRequestHandler(CallToolRequestSchema, async (req) => { + const t = tools.find((x) => x.name === req.params.name); + if (!t) return { content: [{ type: "text", text: `Unknown tool ${req.params.name}` }], isError: true }; + const parsed = t.schema.safeParse(req.params.arguments ?? {}); + if (!parsed.success) return { content: [{ type: "text", text: `Invalid arguments: ${parsed.error.message}` }], isError: true }; + try { + return { content: [{ type: "text", text: await t.run(parsed.data as Record) }] }; + } catch (e) { + console.error("[broke] mcp tool:", t.name, e instanceof Error ? e.message : e); + return { content: [{ type: "text", text: "That didn't work. Try again." }], isError: true }; + } + }); + const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); + await server.connect(transport); + return transport.handleRequest(request); +} + +export const POST = handle; +export const GET = handle; +export const DELETE = handle; diff --git a/src/components/McpTokens.tsx b/src/components/McpTokens.tsx new file mode 100644 index 0000000..7165d6b --- /dev/null +++ b/src/components/McpTokens.tsx @@ -0,0 +1,75 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { createClient } from "@/utils/supabase/client"; + +// Connect your AI: personal tokens for brokeless's MCP endpoint (api/mcp), for AI apps such as Claude Code. +// A new token shows once, with the command that adds it to Claude Code. Revoking deletes it: the app loses access at once. +type Row = { id: string; label: string; created_at: string; last_used_at: string | null }; +const when = (d: string | null) => (d ? new Date(d).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : "never"); + +export function McpTokens() { + const [rows, setRows] = useState(null); + const [fresh, setFresh] = useState(null); + const [err, setErr] = useState(""); + const [busy, setBusy] = useState(false); + const load = () => createClient().from("mcp_tokens").select("id, label, created_at, last_used_at").order("created_at").then(({ data }) => setRows((data ?? []) as Row[])); + useEffect(() => { load(); }, []); + const url = typeof window === "undefined" ? "" : `${window.location.origin}/api/mcp`; + const command = fresh ? `claude mcp add --transport http brokeless ${url} --header "Authorization: Bearer ${fresh}"` : ""; + + async function make() { + setBusy(true); + setErr(""); + const r = await fetch("/api/mcp-tokens", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label: "Claude" }) }); + const b = (await r.json().catch(() => ({}))) as { token?: string; error?: string }; + setBusy(false); + if (!r.ok || !b.token) return setErr(b.error ?? "Couldn't make a token."); + setFresh(b.token); + load(); + } + async function revoke(id: string) { + await createClient().from("mcp_tokens").delete().eq("id", id); + load(); + } + function copy(text: string) { + if (navigator.clipboard) return void navigator.clipboard.writeText(text); + const t = Object.assign(document.createElement("textarea"), { value: text }); + document.body.append(t); + t.select(); + document.execCommand("copy"); + t.remove(); + } + + return ( +
+
+

Connect an AI app (MCP)

+

Let an AI app like Claude Code read your money summary and fix things for you: rules, categories, transfers, merging accounts. It gets the same summary as broke ai: rounded amounts and placeholder names, never single transactions.

+
+ {fresh && ( +
+

Your token. It shows only now: copy it before you leave this page.

+

Add it to Claude Code by running this on your computer:

+ {command} +
+ + +
+
+ )} + {!!rows?.length && ( +
    + {rows.map((r) => ( +
  • + {r.label} · made {when(r.created_at)} · last used {when(r.last_used_at)} + +
  • + ))} +
+ )} + {err &&

{err}

} + +
+ ); +} diff --git a/src/components/RuleForm.tsx b/src/components/RuleForm.tsx index 6df2cae..0acbb60 100644 --- a/src/components/RuleForm.tsx +++ b/src/components/RuleForm.tsx @@ -10,33 +10,20 @@ import { useMoney } from "@/components/Money"; import { TagEditor } from "@/components/Tags"; import type { Category } from "@/lib/data"; import { displayName, plural } from "@/lib/format"; -import { applyRules, findsSomething, matches, mergeTags, RULE_COLS, type Rule } from "@/lib/rules"; +import { findsSomething, type Rule } from "@/lib/rules"; +import { applyRulePast, pastMatchesWith, undoRuleWith, type PastRow } from "@/lib/rule-past"; import { createClient } from "@/utils/supabase/client"; export type Draft = Omit & { id?: string }; export const emptyRule = (x: Partial = {}): Draft => ({ match: "", amount_min: null, amount_max: null, account_id: null, day_from: null, day_to: null, category_id: null, rename: null, ignore: null, add_tags: null, ...x }); -type Match = { id: string; date: string; name: string; merchant_name: string | null; custom_name: string | null; logo_url: string | null; amount: number; currency: string | null; account_id: string; tags: string[] | null; category_id?: string | null; ignored?: boolean }; +type Match = PastRow; +const session = async () => { const db = createClient(); return { db, uid: (await db.auth.getSession()).data.session?.user.id } }; -// Past transactions the rule matches, newest first. Name and account filter in Postgres, the rest here. +// Past transactions the rule matches, newest first (lib/rule-past.ts). export async function pastMatches(d: Draft) { - if (!findsSomething(d)) return []; - const s = d.match.trim().replace(/[%,()]/g, " "); - const db = createClient(); - const uid = (await db.auth.getSession()).data.session?.user.id; - if (!uid) return []; - // Own rows only (not a partner's shared ones), paged: Supabase returns at most 1000 rows per request. - // ponytail: a rule with no name pages through every own row; fine for a personal ledger, an RPC if it gets slow. - const rows: Match[] = []; - for (let from = 0; ; from += 1000) { - let q = db.from("transactions").select("id, date, name, merchant_name, custom_name, logo_url, amount, currency, account_id, tags, category_id, ignored").eq("user_id", uid); - if (s) q = q.or(`name.ilike.%${s}%,merchant_name.ilike.%${s}%`); - if (d.account_id) q = q.eq("account_id", d.account_id); - const { data } = await q.order("date", { ascending: false }).order("id").range(from, from + 999); - rows.push(...((data ?? []) as Match[])); - if (!data || data.length < 1000) break; - } - return rows.filter((t) => matches(d, t)); + const { db, uid } = await session(); + return uid ? pastMatchesWith(db, uid, d) : []; } /** Saves the rule and, if asked, rewrites the past transactions it matches. Returns how many changed, or an error. */ @@ -49,43 +36,15 @@ export async function saveRule(d: Draft, applyPast: boolean): Promise<{ error?: const { error } = d.id ? await supabase.from("rules").update(row).eq("id", d.id) : await supabase.from("rules").insert(row); if (error) return { error: /rules|column/.test(error.message) ? "Rules need a database update. Open Setup to run it." : "Couldn't save the rule.", updated: 0 }; if (!applyPast) return { updated: 0 }; - const patch = { ...(row.category_id ? { category_id: row.category_id } : {}), ...(row.rename ? { custom_name: row.rename } : {}), ...(row.ignore != null ? { ignored: row.ignore } : {}) }; - const past = await pastMatches(d); - const ids = past.map((t) => t.id); - if (Object.keys(patch).length) for (let i = 0; i < ids.length; i += 200) await supabase.from("transactions").update(patch).in("id", ids.slice(i, i + 200)); - // Tags merge with what each row already has, so it's one write per row that gains a tag. - // ponytail: per-row updates, 10 at a time; a Postgres function would do it in one call if rules grow to thousands of rows. - const tagged = row.add_tags ? past.filter((t) => mergeTags(t.tags, row.add_tags).length > (t.tags ?? []).length) : []; - for (let i = 0; i < tagged.length; i += 10) - await Promise.all(tagged.slice(i, i + 10).map((t) => supabase.from("transactions").update({ tags: mergeTags(t.tags, row.add_tags) }).eq("id", t.id))); - return { updated: ids.length }; + const { db, uid } = await session(); + return { updated: uid ? await applyRulePast(db, uid, { ...d, ...row }) : 0 }; } -/** Takes back what a rule did to past transactions, before it's deleted: rows it still matches and that still carry its - * category, name or hiding get what the other rules say instead (or nothing: Other for money out). Tags stay. - * Then transfers between own accounts are looked for again, since rows without a category are open to that. */ +/** Takes back what a rule did to past transactions (lib/rule-past.ts), then looks for own transfers again, since rows + * without a category are open to that. */ export async function undoRule(rule: Draft): Promise { - const db = createClient(); - const past = await pastMatches(rule); - const { data: rest } = await db.from("rules").select(RULE_COLS).neq("id", rule.id ?? "").order("created_at", { ascending: false }); - const { data: other } = await db.from("categories").select("id").is("user_id", null).eq("key", "OTHER").maybeSingle(); - const by = new Map(); // patch as JSON -> row ids - for (const t of past) { - const p = applyRules((rest ?? []) as Rule[], t); - const patch: Record = {}; - if (rule.category_id && t.category_id === rule.category_id) patch.category_id = p.category_id ?? (t.amount > 0 ? other?.id ?? null : null); - if (rule.rename && t.custom_name === rule.rename) patch.custom_name = p.custom_name ?? null; - if (rule.ignore != null && t.ignored === rule.ignore) patch.ignored = p.ignored ?? false; - if (!Object.keys(patch).length) continue; - const k = JSON.stringify(patch); - by.set(k, [...(by.get(k) ?? []), t.id]); - } - let n = 0; - for (const [k, ids] of by) - for (let i = 0; i < ids.length; i += 200) { - const { error } = await db.from("transactions").update(JSON.parse(k)).in("id", ids.slice(i, i + 200)); - if (!error) n += Math.min(200, ids.length - i); - } + const { db, uid } = await session(); + const n = uid ? await undoRuleWith(db, uid, rule) : 0; await fetch("/api/transfers/find", { method: "POST" }).catch(() => null); return n; } diff --git a/src/lib/llm/mcp-tokens.ts b/src/lib/llm/mcp-tokens.ts new file mode 100644 index 0000000..b5706b8 --- /dev/null +++ b/src/lib/llm/mcp-tokens.ts @@ -0,0 +1,24 @@ +import "server-only"; +import { createHash, randomBytes } from "node:crypto"; +import { createAdminClient } from "@/utils/supabase/admin"; + +// Personal tokens for /api/mcp (migration 0033). Shown once, stored as a SHA-256 hash, revocable in Settings. +// "bk_" in front so it's recognizable in a config file. +const hash = (t: string) => createHash("sha256").update(t).digest("hex"); + +export async function createMcpToken(userId: string, label = "Claude") { + const token = `bk_${randomBytes(32).toString("base64url")}`; + const { error } = await createAdminClient().from("mcp_tokens").insert({ user_id: userId, token_hash: hash(token), label: label.slice(0, 60) || "Claude" }); + if (error) throw error; + return token; +} + +/** The user a token belongs to, or null. Notes when it was last used (at most once a minute). */ +export async function mcpUser(token: string | null): Promise { + if (!token || !/^bk_[\w-]{20,}$/.test(token)) return null; + const db = createAdminClient(); + const { data } = await db.from("mcp_tokens").select("id, user_id, last_used_at").eq("token_hash", hash(token)).maybeSingle(); + if (!data) return null; + if (!data.last_used_at || Date.now() - Date.parse(data.last_used_at) > 60_000) await db.from("mcp_tokens").update({ last_used_at: new Date().toISOString() }).eq("id", data.id); + return data.user_id as string; +} diff --git a/src/lib/llm/tools/manage.ts b/src/lib/llm/tools/manage.ts new file mode 100644 index 0000000..7e0078d --- /dev/null +++ b/src/lib/llm/tools/manage.ts @@ -0,0 +1,130 @@ +import "server-only"; +import type { SupabaseClient } from "@supabase/supabase-js"; +import { z } from "zod"; +import { namesFor } from "@/lib/llm/gate"; +import type { Tool } from "@/lib/llm/shared"; +import { mergeAccounts } from "@/lib/merge-run"; +import { mask, unmask } from "@/lib/privacy"; +import { applyRulePast, pastMatchesWith, undoRuleWith, type RuleDraft } from "@/lib/rule-past"; +import { RULE_COLS, type Rule } from "@/lib/rules"; +import { fileOwnTransfers } from "@/lib/sync"; +import { createAdminClient } from "@/utils/supabase/admin"; + +// Tools that change things, for the MCP endpoint (api/mcp). Summary only, like every cloud path: they take real names or +// placeholders (⟨M1⟩, ⟨A1⟩), turn placeholders back into names here, and answer with counts and placeholders, never a +// single transaction. Writes run as the user (RLS); the few columns the user's own session can't write (moving rows +// between accounts, marking transfers) go through the same server code the app uses, filtered to this user. + +const tool = (t: { name: string; description: string; schema: S; run: (input: z.infer) => Promise }) => t as unknown as Tool; +const ok = (x: unknown) => JSON.stringify(x); + +export function manageTools(supabase: SupabaseClient, userId: string): Tool[] { + const names = () => namesFor(supabase, userId); + const categories = async () => { + const { data } = await supabase.from("categories").select("id, key, label, kind"); + return (data ?? []) as { id: string; key: string; label: string; kind: string }[]; + }; + const categoryId = async (k: string) => { + const t = k.trim().toLowerCase(); + return (await categories()).find((c) => c.key.toLowerCase() === t || c.label.toLowerCase() === t)?.id ?? null; + }; + const accountId = async (ref: string) => { + const real = unmask(ref, await names()).trim().toLowerCase(); + const { data } = await supabase.from("accounts").select("id, name, custom_name").eq("user_id", userId); + return (data ?? []).find((a) => (a.custom_name || a.name).toLowerCase() === real)?.id ?? null; + }; + const dir = z.enum(["in", "out"]).optional().describe("Only money coming in, or only money going out"); + + return [ + tool({ + name: "list_categories", + description: "Every category a transaction can have: key, label and kind (spend, income or transfer: transfers never count as spending or income). Use a key or label wherever a tool asks for a category.", + schema: z.object({}), + run: async () => ok((await categories()).map(({ key, label, kind }) => ({ key, label, kind }))), + }), + tool({ + name: "list_rules", + description: "The user's rules: what text they match (merchant names as placeholders), direction, the category they set, and how many past transactions each matches now. A rule's text matches anywhere in a name, so very short text can catch far too much.", + schema: z.object({}), + run: async () => { + const n = await names(); + const [{ data }, cats] = await Promise.all([supabase.from("rules").select(`${RULE_COLS}, created_at`).eq("user_id", userId).order("created_at"), categories()]); + const key = new Map(cats.map((c) => [c.id, c.key])); + const out = []; + for (const r of (data ?? []) as (Rule & { created_at: string })[]) + out.push({ id: r.id, match: r.match ? mask(r.match, n) : null, direction: r.direction ?? "both", category: r.category_id ? key.get(r.category_id) ?? null : null, + renames: !!r.rename, hides: !!r.ignore, matches_now: (await pastMatchesWith(supabase, userId, r)).length }); + return ok(out); + }, + }), + tool({ + name: "create_rule", + description: "Make a rule that sets a category on matching transactions, new ones from now on and (by default) past ones too. match: text that appears in the name (a real name or a placeholder like ⟨M1⟩). Returns how many past transactions it changed.", + schema: z.object({ + match: z.string().min(2).describe("Text in the transaction name, or a placeholder such as ⟨M1⟩"), + category: z.string().describe("Category key or label, see list_categories"), + direction: dir, + apply_past: z.boolean().optional().describe("Also change matching past transactions (default true)"), + }), + run: async ({ match, category, direction, apply_past }) => { + const cat = await categoryId(category); + if (!cat) return ok({ error: `No category "${category}". See list_categories.` }); + const real = unmask(match, await names()).trim(); + const draft: RuleDraft = { match: real, amount_min: null, amount_max: null, account_id: null, day_from: null, day_to: null, direction: direction ?? null, category_id: cat, rename: null, ignore: null, add_tags: null }; + const { data, error } = await supabase.from("rules").insert(draft).select("id").single(); + if (error) return ok({ error: "Couldn't save the rule." }); + const updated = apply_past === false ? 0 : await applyRulePast(supabase, userId, draft); + return ok({ rule_id: data.id, updated_past: updated, warning: real.length <= 3 ? "Very short text matches inside other words. Check list_rules matches_now." : undefined }); + }, + }), + tool({ + name: "delete_rule", + description: "Delete a rule by id (from list_rules). By default it also takes back what the rule did to past transactions: they get what the other rules say, or no category, and transfers between own accounts are looked for again.", + schema: z.object({ id: z.string().uuid(), undo_past: z.boolean().optional().describe("Take back its changes on past transactions (default true)") }), + run: async ({ id, undo_past }) => { + const { data: rule } = await supabase.from("rules").select(RULE_COLS).eq("user_id", userId).eq("id", id).maybeSingle(); + if (!rule) return ok({ error: "No such rule." }); + const undone = undo_past === false ? 0 : await undoRuleWith(supabase, userId, rule as Rule); + const { error } = await supabase.from("rules").delete().eq("id", id).eq("user_id", userId); + if (error) return ok({ error: "Couldn't delete the rule." }); + const transfers = undo_past === false ? 0 : await fileOwnTransfers(userId); + return ok({ deleted: true, undone_past: undone, marked_as_transfers: transfers }); + }, + }), + tool({ + name: "recategorize", + description: "Set a category on past transactions that match a name (real text or placeholder), optionally only money in or out and only between two dates. No rule is made, so new transactions aren't affected: use create_rule for that. Returns how many changed.", + schema: z.object({ + match: z.string().min(2).describe("Text in the transaction name, or a placeholder such as ⟨M1⟩"), + category: z.string().describe("Category key or label"), + direction: dir, + from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), + }), + run: async ({ match, category, direction, from, to }) => { + const cat = await categoryId(category); + if (!cat) return ok({ error: `No category "${category}". See list_categories.` }); + const draft: RuleDraft = { match: unmask(match, await names()).trim(), amount_min: null, amount_max: null, account_id: null, day_from: null, day_to: null, direction: direction ?? null, category_id: cat, rename: null, ignore: null, add_tags: null }; + const ids = (await pastMatchesWith(supabase, userId, draft)).filter((t) => (!from || t.date >= from) && (!to || t.date <= to)).map((t) => t.id); + for (let i = 0; i < ids.length; i += 200) await supabase.from("transactions").update({ category_id: cat }).in("id", ids.slice(i, i + 200)); + return ok({ updated: ids.length }); + }, + }), + tool({ + name: "find_transfers", + description: "Look for money moved between the user's own accounts that still counts as spending and income (same amount out and in within 4 days, or a savings or investment account by name) and mark it as transfers. Only rows without a category, or Other.", + schema: z.object({}), + run: async () => ok({ marked_as_transfers: await fileOwnTransfers(userId) }), + }), + tool({ + name: "merge_accounts", + description: "Merge an imported (CSV) account into a linked one, by placeholder (⟨A1⟩, see list_accounts). Older imported transactions move over; from the day the bank's history starts its own are kept and edits carry over; then the imported account is removed. preview (default true) only counts.", + schema: z.object({ from: z.string().describe("The imported account, e.g. ⟨A2⟩"), into: z.string().describe("The linked account, e.g. ⟨A1⟩"), preview: z.boolean().optional() }), + run: async ({ from, into, preview }) => { + const [a, b] = await Promise.all([accountId(from), accountId(into)]); + if (!a || !b) return ok({ error: "Account not found. Use placeholders from list_accounts." }); + return ok(await mergeAccounts(createAdminClient(), userId, a, b, preview !== false)); + }, + }), + ]; +} diff --git a/src/lib/merge-run.ts b/src/lib/merge-run.ts new file mode 100644 index 0000000..552bae0 --- /dev/null +++ b/src/lib/merge-run.ts @@ -0,0 +1,45 @@ +import "server-only"; +import type { SupabaseClient } from "@supabase/supabase-js"; +import { planMerge, type MergeRow } from "@/lib/merge"; + +// Merge an imported account into another of the person's accounts (lib/merge.ts decides what moves). Used by the +// Accounts page (api/accounts/merge) and the MCP tools. db: a client that can write the user's rows. +const COLS = "id, date, amount, category_id, custom_name, note, tags, ignored, plaid_transaction_id"; + +async function rowsOf(db: SupabaseClient, userId: string, accountId: string) { + const out: MergeRow[] = []; + for (let from = 0; ; from += 1000) { + const { data, error } = await db.from("transactions").select(COLS).eq("user_id", userId).eq("account_id", accountId).order("date").range(from, from + 999); + if (error) throw error; + out.push(...(data ?? []).map(({ plaid_transaction_id, ...r }) => ({ ...r, fromBank: !!plaid_transaction_id }) as MergeRow)); + if ((data ?? []).length < 1000) return out; + } +} +const chunks = (xs: T[], n = 200) => Array.from({ length: Math.ceil(xs.length / n) }, (_, i) => xs.slice(i * n, i * n + n)); + +export type MergeResult = { error?: string; status?: number; start?: string | null; moved?: number; replaced?: number; edits?: number; ok?: boolean }; +export async function mergeAccounts(db: SupabaseClient, userId: string, from: string, into: string, preview: boolean): Promise { + if (!from || !into || from === into) return { error: "Pick the account to merge into.", status: 400 }; + const { data: accts } = await db.from("accounts").select("id, manual").eq("user_id", userId).in("id", [from, into]); + const src = accts?.find((a) => a.id === from), dst = accts?.find((a) => a.id === into); + if (!src || !dst) return { error: "Account not found.", status: 404 }; + if (!src.manual) return { error: "Only an imported account can be merged into another.", status: 400 }; + const plan = planMerge(await rowsOf(db, userId, from), await rowsOf(db, userId, into)); + const counts = { start: plan.start, moved: plan.move.length, replaced: plan.drop.length, edits: plan.edits.length }; + if (preview) return counts; + for (const e of plan.edits) { + const { error } = await db.from("transactions").update(e.patch).eq("id", e.id).eq("user_id", userId); + if (error) throw error; + } + for (const ids of chunks(plan.move)) { + const { error } = await db.from("transactions").update({ account_id: into }).eq("user_id", userId).in("id", ids); + if (error) throw error; + } + // Rules and repeating charges that point at the imported account now point at the one it went into. + await db.from("rules").update({ account_id: into }).eq("user_id", userId).eq("account_id", from); + await db.from("recurring").update({ account_id: into }).eq("user_id", userId).eq("account_id", from); + // What's left on the imported account is the overlap the bank already has. Deleting the account takes it along. + const { error } = await db.from("accounts").delete().eq("id", from).eq("user_id", userId); + if (error) throw error; + return { ok: true, ...counts }; +} diff --git a/src/lib/rule-past.ts b/src/lib/rule-past.ts new file mode 100644 index 0000000..a7a3dfc --- /dev/null +++ b/src/lib/rule-past.ts @@ -0,0 +1,63 @@ +// A rule's effect on past transactions: find them, apply the rule, or take it back. Shared by the rule form (browser +// client) and the MCP tools (server, the user's own session): same code, same RLS. +import type { SupabaseClient } from "@supabase/supabase-js"; +import { applyRules, findsSomething, matches, mergeTags, RULE_COLS, type Rule } from "@/lib/rules"; + +export type RuleDraft = Omit & { id?: string }; +export type PastRow = { id: string; date: string; name: string; merchant_name: string | null; custom_name: string | null; logo_url: string | null; amount: number; currency: string | null; account_id: string; tags: string[] | null; category_id?: string | null; ignored?: boolean }; + +// Past transactions the rule matches, newest first. Name and account filter in Postgres, the rest here. +// Own rows only (not a partner's shared ones), paged: Supabase returns at most 1000 rows per request. +export async function pastMatchesWith(db: SupabaseClient, uid: string, d: RuleDraft) { + if (!findsSomething(d)) return []; + const s = d.match.trim().replace(/[%,()]/g, " "); + const rows: PastRow[] = []; + for (let from = 0; ; from += 1000) { + let q = db.from("transactions").select("id, date, name, merchant_name, custom_name, logo_url, amount, currency, account_id, tags, category_id, ignored").eq("user_id", uid); + if (s) q = q.or(`name.ilike.%${s}%,merchant_name.ilike.%${s}%`); + if (d.account_id) q = q.eq("account_id", d.account_id); + const { data } = await q.order("date", { ascending: false }).order("id").range(from, from + 999); + rows.push(...((data ?? []) as PastRow[])); + if (!data || data.length < 1000) break; + } + return rows.filter((t) => matches(d, t)); +} + +/** Applies a rule's category, name, hiding and tags to the past transactions it matches. Returns how many it matched. */ +export async function applyRulePast(db: SupabaseClient, uid: string, d: RuleDraft) { + const patch = { ...(d.category_id ? { category_id: d.category_id } : {}), ...(d.rename ? { custom_name: d.rename } : {}), ...(d.ignore != null ? { ignored: d.ignore } : {}) }; + const past = await pastMatchesWith(db, uid, d); + const ids = past.map((t) => t.id); + if (Object.keys(patch).length) for (let i = 0; i < ids.length; i += 200) await db.from("transactions").update(patch).in("id", ids.slice(i, i + 200)); + // Tags merge with what each row already has, so it's one write per row that gains a tag. + const tagged = d.add_tags ? past.filter((t) => mergeTags(t.tags, d.add_tags).length > (t.tags ?? []).length) : []; + for (let i = 0; i < tagged.length; i += 10) + await Promise.all(tagged.slice(i, i + 10).map((t) => db.from("transactions").update({ tags: mergeTags(t.tags, d.add_tags) }).eq("id", t.id))); + return ids.length; +} + +/** Takes back what a rule did to past transactions, before it's deleted: rows it still matches and that still carry its + * category, name or hiding get what the other rules say instead (or nothing: Other for money out). Tags stay. */ +export async function undoRuleWith(db: SupabaseClient, uid: string, rule: RuleDraft) { + const past = await pastMatchesWith(db, uid, rule); + const { data: rest } = await db.from("rules").select(RULE_COLS).neq("id", rule.id ?? "").order("created_at", { ascending: false }); + const { data: other } = await db.from("categories").select("id").is("user_id", null).eq("key", "OTHER").maybeSingle(); + const by = new Map(); // patch as JSON -> row ids + for (const t of past) { + const p = applyRules((rest ?? []) as Rule[], t); + const patch: Record = {}; + if (rule.category_id && t.category_id === rule.category_id) patch.category_id = p.category_id ?? (t.amount > 0 ? other?.id ?? null : null); + if (rule.rename && t.custom_name === rule.rename) patch.custom_name = p.custom_name ?? null; + if (rule.ignore != null && t.ignored === rule.ignore) patch.ignored = p.ignored ?? false; + if (!Object.keys(patch).length) continue; + const k = JSON.stringify(patch); + by.set(k, [...(by.get(k) ?? []), t.id]); + } + let n = 0; + for (const [k, ids] of by) + for (let i = 0; i < ids.length; i += 200) { + const { error } = await db.from("transactions").update(JSON.parse(k)).in("id", ids.slice(i, i + 200)); + if (!error) n += Math.min(200, ids.length - i); + } + return n; +} diff --git a/src/middleware.ts b/src/middleware.ts index 0ea2c22..096b645 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -5,5 +5,5 @@ export const middleware = (request: NextRequest) => updateSession(request); // auth/callback runs without the session refresh: clearing an old sign-in there would wipe the one the email link just made. export const config = { - matcher: ["/((?!_next/static|_next/image|favicon.ico|api/plaid/webhook|auth/callback|api/agent|api/ai/helper|broke-connect|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"], + matcher: ["/((?!_next/static|_next/image|favicon.ico|api/plaid/webhook|auth/callback|api/agent|api/mcp|api/ai/helper|broke-connect|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"], }; diff --git a/supabase/migrations/0033_mcp_tokens.sql b/supabase/migrations/0033_mcp_tokens.sql new file mode 100644 index 0000000..91dea76 --- /dev/null +++ b/supabase/migrations/0033_mcp_tokens.sql @@ -0,0 +1,17 @@ +-- Personal tokens for the MCP endpoint (/api/mcp): an AI app such as Claude Code connects with one and acts as you, +-- summary only. Only a hash is stored; the token itself is shown once. You see and revoke your own; the server checks them. +create table if not exists public.mcp_tokens ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references auth.users on delete cascade, + token_hash text not null unique, + label text not null default 'Claude', + created_at timestamptz not null default now(), + last_used_at timestamptz +); +create index if not exists mcp_tokens_user on public.mcp_tokens (user_id); +alter table public.mcp_tokens enable row level security; +drop policy if exists "own" on public.mcp_tokens; +create policy "own" on public.mcp_tokens for select to authenticated using (user_id = (select auth.uid())); +drop policy if exists "own delete" on public.mcp_tokens; +create policy "own delete" on public.mcp_tokens for delete to authenticated using (user_id = (select auth.uid())); +grant select (id, user_id, label, created_at, last_used_at), delete on public.mcp_tokens to authenticated;