brokeless as an MCP server for AI apps like Claude Code
/api/mcp (Streamable HTTP, stateless) with personal tokens made on Connect your AI (stored as a hash, shown once, revocable; migration 0033). Each call runs as the token's user in their own session, so RLS applies; AI switched off in Settings refuses. Summary only, like every cloud path: the existing summary tools, plus tools that change things through placeholders and answer with counts: list categories and rules, create rule, delete rule (with undo), recategorize, find transfers, merge accounts (preview first). Rule past-matching and merging moved to shared libraries (lib/rule-past.ts, lib/merge-run.ts) so the app and the tools run the same code. Tested with the official MCP client: bad token refused, tools listed, and the 'ing' rule found, undone and replaced. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c7298cf955
commit
1253f4e7fb
13 files changed
+471
-100
No files matched your search
@@ -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<string | null> {
|
||||
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;
|
||||
}
|
||||
@@ -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 = <S extends z.ZodObject>(t: { name: string; description: string; schema: S; run: (input: z.infer<S>) => Promise<string> }) => 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));
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -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 = <T,>(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<MergeResult> {
|
||||
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 };
|
||||
}
|
||||
@@ -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<Rule, "id"> & { 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<string, string[]>(); // patch as JSON -> row ids
|
||||
for (const t of past) {
|
||||
const p = applyRules((rest ?? []) as Rule[], t);
|
||||
const patch: Record<string, unknown> = {};
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user