import Foundation /// STDIO MCP server, run as `Bucksley --mcp` (the Inkspring pattern). It reads and writes the same /// local store as the Mac app, so an agent can answer money questions, review transactions and set /// up rules and budgets while the app shows the result. Write tools need "Let agents make changes" /// in Settings → Agents, and every agent write is logged and shown in the app. Bucksley is read-only /// toward banks: no tool can move money. public final class MCPServer: @unchecked Sendable { let store: WorkspaceStore var clientName = "Agent" let sync: @Sendable () async -> BankSync.Report /// Ask Bucksley's agent gets a server with no write tools at all. var readOnly = false public convenience init(store: WorkspaceStore, readOnly: Bool, sync: (@Sendable () async -> BankSync.Report)? = nil) { self.init(store: store, sync: sync) self.readOnly = readOnly } public init(store: WorkspaceStore, sync: (@Sendable () async -> BankSync.Report)? = nil) { self.store = store self.sync = sync ?? { await BankSync(store: store).syncAll() } } struct Tool { let name: String, summary: String var fields: [String: [String: Any]] = [:] var required: [String] = [] var writes = false, network = false var json: [String: Any] { ["name": name, "description": summary, "inputSchema": ["type": "object", "properties": fields, "required": required, "additionalProperties": false], "annotations": ["readOnlyHint": !writes, "destructiveHint": false, "idempotentHint": !writes, "openWorldHint": network]] } } static var str: [String: Any] { ["type": "string"] } static var num: [String: Any] { ["type": "number"] } static var bool: [String: Any] { ["type": "boolean"] } static var strs: [String: Any] { ["type": "array", "items": ["type": "string"]] } static var day: [String: Any] { ["type": "string", "description": "yyyy-MM-dd"] } static var month: [String: Any] { ["type": "string", "description": "yyyy-MM, default this month"] } static var limit: [String: Any] { ["type": "integer", "minimum": 1, "maximum": 500] } /// Name and description of every tool, for the Claude extension's manifest. public static var toolSummaries: [(name: String, summary: String)] { tools.map { ($0.name, $0.summary) } } static var tools: [Tool] { [ .init(name: "get_status", summary: "Connections, account count, last bank sync, review queue size and whether agents may make changes. Call this first."), .init(name: "list_accounts", summary: "Every account with institution, type and balance (money owed is negative)."), .init(name: "get_net_worth", summary: "Net worth now, by account group, and a daily series for the last N days.", fields: ["days": ["type": "integer", "minimum": 1, "maximum": 730]]), .init(name: "list_transactions", summary: "Search transactions. All filters optional; newest first.", fields: ["query": str, "category_id": str, "account_id": str, "from": day, "to": day, "tag": str, "unreviewed_only": bool, "limit": limit]), .init(name: "get_spending", summary: "Spending by category for a month, with income and the total.", fields: ["month": month]), .init(name: "list_categories", summary: "Categories with their groups and IDs."), .init(name: "list_rules", summary: "Categorization rules in the order they apply."), .init(name: "list_budgets", summary: "Budgets for a month with spent, carried over, remaining and pace, plus suggested budgets from past spending.", fields: ["month": month]), .init(name: "get_smart_budget_plan", summary: "A recommended monthly budget for every category the user spends in, from typical income and spending, sized to leave a savings goal. Essentials keep headroom; flexible categories are trimmed first.", fields: ["savings_rate": ["type": "integer", "minimum": 0, "maximum": 60, "description": "Percent of income to keep free, default 20"]]), .init(name: "list_recurring", summary: "Recurring charges Bucksley found, with cadence, amount and next expected date."), .init(name: "get_review_queue", summary: "Transactions not yet marked reviewed, most worth a look first (flagged, uncategorized, large).", fields: ["limit": limit]), .init(name: "get_cash_flow", summary: "Income, spend, net and savings rate for each of the last N months, plus monthly averages.", fields: ["months": ["type": "integer", "minimum": 1, "maximum": 36]]), .init(name: "get_insights", summary: "Charges worth a look (duplicates, above usual, new merchant, price increases), likely refunds of earlier purchases, category suggestions, and last month's recap."), .init(name: "mark_reviewed", summary: "Mark transactions reviewed (or not).", fields: ["transaction_ids": strs, "reviewed": bool], required: ["transaction_ids"], writes: true), .init(name: "set_category", summary: "Recategorize a transaction.", fields: ["transaction_id": str, "category_id": str], required: ["transaction_id", "category_id"], writes: true), .init(name: "set_note", summary: "Add or replace a transaction's note (empty clears it).", fields: ["transaction_id": str, "note": str], required: ["transaction_id", "note"], writes: true), .init(name: "rename_transaction", summary: "Give a transaction a clearer name.", fields: ["transaction_id": str, "name": str], required: ["transaction_id", "name"], writes: true), .init(name: "set_tags", summary: "Replace a transaction's tags.", fields: ["transaction_id": str, "tags": strs], required: ["transaction_id", "tags"], writes: true), .init(name: "create_rule", summary: "When a transaction's name contains match_text, set its category and optionally rename, tag or mark it reviewed. Applies to past and future transactions without user edits.", fields: ["match_text": str, "category_id": str, "rename": str, "tags": strs, "mark_reviewed": bool, "min_amount": num, "max_amount": num], required: ["match_text"], writes: true), .init(name: "set_budget", summary: "Set a monthly budget for a category (amount 0 removes it).", fields: ["category_id": str, "amount": num, "rollover": bool], required: ["category_id", "amount"], writes: true), .init(name: "create_smart_budgets", summary: "Create the smart budget plan's budgets (all categories, or only category_ids). Other budgets are kept.", fields: ["savings_rate": ["type": "integer", "minimum": 0, "maximum": 60], "category_ids": strs], writes: true), .init(name: "sync_now", summary: "Pull fresh balances and transactions from every bank connection on this Mac now.", writes: true, network: true) ] } // MARK: Transport public func run() async { let input = FileHandle.standardInput, output = FileHandle.standardOutput var line = Data() while true { let chunk = input.availableData if chunk.isEmpty { if !line.isEmpty { await respond(line, output) }; return } for byte in chunk { if byte == 10 { if !line.isEmpty { await respond(line, output) }; line.removeAll(keepingCapacity: true) } else if line.count < 1_048_576 { line.append(byte) } } } } private func respond(_ data: Data, _ output: FileHandle) async { let reply: [String: Any]? if let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] { reply = await handle(request) } else { reply = failure(NSNull(), -32700, "Parse error.") } if let reply, var json = try? JSONSerialization.data(withJSONObject: reply) { json.append(10); try? output.write(contentsOf: json) } } public func handle(_ request: [String: Any]) async -> [String: Any]? { let id = request["id"] ?? NSNull() guard let method = request["method"] as? String else { return failure(id, -32600, "Invalid request.") } guard request["id"] != nil else { return nil } // notification let params = request["params"] as? [String: Any] ?? [:] switch method { case "initialize": if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String { clientName = name } let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] let asked = params["protocolVersion"] as? String ?? "" return success(id, ["protocolVersion": supported.contains(asked) ? asked : supported[0], "capabilities": ["tools": ["listChanged": false]], "serverInfo": ["name": "bucksley", "version": "0.1.0"], "instructions": "Bucksley is a read-only money app; nothing here can move money. Call get_status first. Amounts are in the account currency; negative is money out. Ask the user before bulk changes such as marking many transactions reviewed or creating rules."]) case "ping": return success(id, [:]) case "tools/list": return success(id, ["tools": Self.tools.filter { !readOnly || !$0.writes }.map(\.json)]) case "tools/call": let name = params["name"] as? String ?? "" let args = params["arguments"] as? [String: Any] ?? [:] do { let result = try await call(name, args) let text = String(decoding: try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]), as: UTF8.self) return success(id, ["content": [["type": "text", "text": text]], "structuredContent": result]) } catch { return success(id, ["content": [["type": "text", "text": error.localizedDescription]], "isError": true]) } default: return failure(id, -32601, "Unknown method \(method).") } } // MARK: Tools func call(_ name: String, _ a: [String: Any]) async throws -> [String: Any] { guard let tool = Self.tools.first(where: { $0.name == name }) else { throw BucksleyError.missing("Unknown tool \(name).") } let ledger = try store.ledger() let ws = ledger.workspace if tool.writes && readOnly { throw BucksleyError.notAllowed("Ask Bucksley's agent can only read.") } if tool.writes && !ws.settings.agentsCanWrite { throw BucksleyError.notAllowed("Turn on “Let agents make changes” in Bucksley → Settings → Agents.") } func s(_ k: String) -> String? { (a[k] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty } func need(_ k: String) throws -> String { guard let v = s(k) else { throw BucksleyError.missing("\(k) is required.") }; return v } func money(_ k: String) -> Decimal? { (a[k] as? NSNumber).flatMap { Decimal(string: $0.stringValue) } } func txID() throws -> String { let id = try need("transaction_id") guard ledger.entries.contains(where: { $0.id == id }) else { throw BucksleyError.missing("No transaction \(id).") } return id } func category() throws -> String { let id = try need("category_id") guard ws.category(id) != nil else { throw BucksleyError.missing("No category \(id). Call list_categories.") } return id } let month = s("month") ?? MonthKey.current let limit = a["limit"] as? Int ?? 100 switch name { case "get_status": return ["connections": ws.connections.map { ["id": $0.id, "kind": $0.kind.rawValue, "name": $0.name, "last_sync_at": orNull($0.lastSyncAt?.ISO8601Format()), "error": orNull($0.lastError)] }, "accounts": ledger.visibleAccounts.count, "transactions": ledger.entries.count, "review_queue": ledger.reviewQueue.count, "net_worth": ledger.netWorth.jsonMoney, "last_sync_at": orNull(ws.settings.lastSyncAt?.ISO8601Format()), "agents_can_write": ws.settings.agentsCanWrite, "read_only_banking": true] case "list_accounts": return ["accounts": ledger.visibleAccounts.map { ["id": $0.id, "name": $0.displayName, "institution": $0.institution, "type": $0.kind.rawValue, "group": $0.kind.group.rawValue, "balance": $0.balance.jsonMoney, "currency": $0.currency, "available": orNull($0.available?.jsonMoney), "as_of": $0.balanceDate.ISO8601Format()] }] case "get_net_worth": let days = a["days"] as? Int ?? 90 return ["net_worth": ledger.netWorth.jsonMoney, "assets": ledger.assets.jsonMoney, "debts": ledger.debts.jsonMoney, "by_group": Dictionary(uniqueKeysWithValues: AccountGroup.allCases.map { ($0.rawValue, ledger.total($0).jsonMoney) }), "series": ledger.netWorthSeries(days: days).map { ["day": $0.day, "total": $0.total.jsonMoney] }] case "list_transactions": let rows = ledger.search(s("query") ?? "", categoryID: s("category_id"), accountID: s("account_id"), unreviewedOnly: a["unreviewed_only"] as? Bool ?? false, from: s("from"), to: s("to"), tag: s("tag")) return ["count": rows.count, "transactions": rows.prefix(limit).map { row($0, ws) }] case "get_spending": let spend = ledger.spending(month: month) return ["month": month, "total": spend.reduce(Decimal(0)) { $0 + $1.amount }.jsonMoney, "income": ledger.income(month: month).jsonMoney, "categories": spend.map { ["category_id": $0.categoryID, "name": ws.category($0.categoryID)?.name ?? $0.categoryID, "amount": $0.amount.jsonMoney] }] case "list_categories": return ["groups": ws.groups.map { g in ["id": g.id, "name": g.name, "categories": ws.categories.filter { $0.groupID == g.id }.map { ["id": $0.id, "name": $0.name, "kind": $0.kind.rawValue] }] }] case "list_rules": return ["rules": ws.rules.map { ["id": $0.id, "match_text": $0.matchText, "category_id": orNull($0.setCategoryID), "rename": orNull($0.rename), "tags": $0.addTags, "mark_reviewed": $0.markReviewed, "enabled": $0.enabled] }] case "list_budgets": return ["month": month, "budgets": ledger.budgetStatus(month: month).map { ["category_id": $0.id, "name": ledger.budgetName($0.id), "is_group": ledger.isGroup($0.id), "amount": $0.allowed.jsonMoney, "rollover": $0.budget.rollover, "carried": $0.carried.jsonMoney, "spent": $0.spent.jsonMoney, "remaining": $0.remaining.jsonMoney, "progress": $0.progress, "month_elapsed": $0.pace] }, "suggestions": ledger.budgetSuggestions().map { ["category_id": $0.categoryID, "amount": $0.amount.jsonMoney, "typical_month": $0.typical.jsonMoney, "reason": $0.reason] }] case "get_smart_budget_plan": let plan = ledger.smartBudgetPlan(savingsRate: (a["savings_rate"] as? NSNumber)?.intValue ?? 20) return ["months": plan.months, "typical_income": plan.income.jsonMoney, "typical_spending": plan.typicalSpending.jsonMoney, "savings_rate": plan.savingsRate, "savings_goal": plan.savingsGoal.jsonMoney, "plan_total": plan.total.jsonMoney, "left_over": plan.leftOver.jsonMoney, "summary": plan.summary, "budgets": plan.items.map { ["category_id": $0.categoryID, "name": $0.name, "fixed": $0.fixed, "typical_month": $0.typical.jsonMoney, "recommended": $0.recommended.jsonMoney, "current": $0.current.map { $0.jsonMoney } as Any? ?? NSNull(), "reason": $0.reason] }] case "list_recurring": return ["recurring": ledger.recurring().map { ["id": $0.id, "name": $0.name, "cadence": $0.cadence.rawValue, "amount": $0.amount.jsonMoney, "last": $0.lastDay, "next": $0.nextDay, "status": $0.status.rawValue, "count": $0.count] }] case "get_cash_flow": let flow = ledger.cashFlow(months: a["months"] as? Int ?? 12) let avg = ledger.cashFlowAverages(flow) return ["months": flow.map { ["month": $0.month, "income": $0.income.jsonMoney, "spend": $0.spend.jsonMoney, "net": $0.net.jsonMoney, "savings_rate": orNull($0.savingsRate)] }, "average": ["income": avg.income.jsonMoney, "spend": avg.spend.jsonMoney, "net": avg.net.jsonMoney, "savings_rate": orNull(avg.savingsRate)]] case "get_insights": return ["flags": ledger.flags().map { ["transaction_id": $0.entryID, "kind": $0.kind.rawValue, "reason": $0.reason] }, "refund_matches": ledger.refundMatches().map { ["refund_id": $0.refundID, "purchase_id": $0.purchaseID, "refund": entryName($0.refundID, ledger), "purchase": entryName($0.purchaseID, ledger)] }, "category_suggestions": ledger.historySuggestions().map { ["transaction_id": $0.entryID, "category_id": $0.categoryID, "reason": $0.reason] }, "last_month_recap": orNull(ledger.recap()?.facts)] case "get_review_queue": let queue = ledger.prioritizedReviewQueue() return ["count": queue.count, "transactions": queue.prefix(limit).map { row($0, ws) }] case "mark_reviewed": let ids = (a["transaction_ids"] as? [String] ?? []).filter { id in ledger.entries.contains { $0.id == id } } guard !ids.isEmpty else { throw BucksleyError.missing("None of those transaction IDs exist.") } let reviewed = a["reviewed"] as? Bool ?? true for id in ids { try store.edit(id, device: clientName) { $0.reviewed = reviewed } } try log("mark_reviewed", "Marked \(ids.count) transaction\(ids.count == 1 ? "" : "s") \(reviewed ? "reviewed" : "unreviewed")") return ["updated": ids.count] case "set_category": let id = try txID(), c = try category() try store.edit(id, device: clientName) { $0.categoryID = c } try log("set_category", "Set \(entryName(id, ledger)) to \(ws.category(c)?.name ?? c)") return ["ok": true] case "set_note": let id = try txID(), note = a["note"] as? String ?? "" try store.edit(id, device: clientName) { $0.note = note } try log("set_note", "Noted \(entryName(id, ledger))") return ["ok": true] case "rename_transaction": let id = try txID(), newName = try need("name") try store.edit(id, device: clientName) { $0.name = newName } try log("rename_transaction", "Renamed \(entryName(id, ledger)) to \(newName)") return ["ok": true] case "set_tags": let id = try txID(), tags = (a["tags"] as? [String] ?? []).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } try store.edit(id, device: clientName) { $0.tags = tags } try log("set_tags", "Tagged \(entryName(id, ledger)) \(tags.joined(separator: ", "))") return ["ok": true] case "create_rule": let text = try need("match_text") let c = s("category_id") if let c, ws.category(c) == nil { throw BucksleyError.missing("No category \(c).") } let rule = Rule(matchText: text, minAmount: money("min_amount"), maxAmount: money("max_amount"), setCategoryID: c, rename: s("rename"), addTags: a["tags"] as? [String] ?? [], markReviewed: a["mark_reviewed"] as? Bool ?? false) let matches = ledger.entries.filter { rule.matches($0.transaction) }.count try store.update { ws in ws.rules.insert(rule, at: 0) ws.agentLog.insert(AgentAction(client: clientName, tool: "create_rule", summary: "Rule: “\(text)” → \(c.flatMap { id in ws.category(id)?.name } ?? "no category change")"), at: 0) } return ["rule_id": rule.id, "matches_existing": matches] case "set_budget": let c = try category() guard let amount = money("amount"), amount >= 0 else { throw BucksleyError.missing("amount must be 0 or more.") } try store.update { ws in ws.budgets.removeAll { $0.categoryID == c } if amount > 0 { ws.budgets.append(Budget(categoryID: c, amount: amount, rollover: a["rollover"] as? Bool ?? false)) } ws.agentLog.insert(AgentAction(client: clientName, tool: "set_budget", summary: amount > 0 ? "Budget \(ws.category(c)?.name ?? c): \(Money.format(amount, cents: false)) a month" : "Removed the \(ws.category(c)?.name ?? c) budget"), at: 0) } return ["ok": true] case "create_smart_budgets": let plan = ledger.smartBudgetPlan(savingsRate: (a["savings_rate"] as? NSNumber)?.intValue ?? 20) let only = (a["category_ids"] as? [String]).map(Set.init) let chosen = plan.items.filter { only?.contains($0.categoryID) ?? true } guard !chosen.isEmpty else { throw BucksleyError.missing("No categories in the plan match.") } try store.update { ws in SmartBudgetPlan.apply(chosen, to: &ws) ws.agentLog.insert(AgentAction(client: clientName, tool: "create_smart_budgets", summary: "Created \(chosen.count) smart budget\(chosen.count == 1 ? "" : "s")"), at: 0) } return ["ok": true, "created": chosen.map { ["category_id": $0.categoryID, "amount": $0.recommended.jsonMoney] }] case "sync_now": let report = await sync() try log("sync_now", "Synced \(report.synced.count) connection\(report.synced.count == 1 ? "" : "s")" + (report.failed.isEmpty ? "" : ", \(report.failed.count) failed")) return ["synced": report.synced, "failed": report.failed, "added": report.added, "updated": report.updated] default: throw BucksleyError.missing("Unknown tool \(name).") } } private func row(_ e: LedgerEntry, _ ws: Workspace) -> [String: Any] { ["id": e.id, "day": e.day, "name": e.name, "amount": e.amount.jsonMoney, "category_id": e.categoryID, "category": ws.category(e.categoryID)?.name ?? e.categoryID, "account": ws.account(e.accountID)?.displayName ?? e.accountID, "note": orNull(e.note), "tags": e.tags, "reviewed": e.reviewed, "pending": e.transaction.pending, "bank_description": e.transaction.description] } private func entryName(_ id: String, _ ledger: Ledger) -> String { ledger.entries.first { $0.id == id }.map { "\($0.name) (\($0.day))" } ?? id } private func log(_ tool: String, _ summary: String) throws { try store.update { ws in ws.agentLog.insert(AgentAction(client: clientName, tool: tool, summary: summary), at: 0) if ws.agentLog.count > 500 { ws.agentLog.removeLast(ws.agentLog.count - 500) } } } private func success(_ id: Any, _ result: [String: Any]) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "result": result] } private func failure(_ id: Any, _ code: Int, _ message: String) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]] } } extension String { var nilIfEmpty: String? { isEmpty ? nil : self } } /// JSON null for a missing value. func orNull(_ value: Any?) -> Any { value ?? NSNull() } extension Decimal { /// Exact cents in JSON output (JSONSerialization writes NSDecimalNumber without binary noise). var jsonMoney: NSDecimalNumber { NSDecimalNumber(decimal: rounded(2)) } }