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:
MangaValkandClaude Opus 5.5 committed 2026-11-19 21:06:44 +01:00
1 parent c7298cf955
commit 1253f4e7fb
13 files changed
+471 -100

No files matched your search

+7 -1
View File
@@ -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 <ConnectAI initial={JSON.parse(JSON.stringify(providers))} choice={savedChoice(user)} hosted={isHosted()} connected={!!q.connected} failed={!!q.error} />;
return (
<div className="max-w-2xl space-y-4">
<ConnectAI initial={JSON.parse(JSON.stringify(providers))} choice={savedChoice(user)} hosted={isHosted()} connected={!!q.connected} failed={!!q.error} />
<McpTokens />
</div>
);
}
+4 -44
View File
@@ -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<typeof createAdminClient>, 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));
// 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 });
+19
View File
@@ -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 });
}
}
+58
View File
@@ -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<string, unknown>) }] };
} 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;