Branchwell

Bucksley / app · bucksley.ai / Sources / BucksleyKit / MCPServer.swift

1import Foundation
2
3/// STDIO MCP server, run as `Bucksley --mcp` (the Inkspring pattern). It reads and writes the same
4/// local store as the Mac app, so an agent can answer money questions, review transactions and set
5/// up rules and budgets while the app shows the result. Write tools need "Let agents make changes"
6/// in Settings → Agents, and every agent write is logged and shown in the app. Bucksley is read-only
7/// toward banks: no tool can move money.
8public final class MCPServer: @unchecked Sendable {
9 let store: WorkspaceStore
10 var clientName = "Agent"
11 let sync: @Sendable () async -> BankSync.Report
12
13 /// Ask Bucksley's agent gets a server with no write tools at all.
14 var readOnly = false
15
16 public convenience init(store: WorkspaceStore, readOnly: Bool, sync: (@Sendable () async -> BankSync.Report)? = nil) {
17 self.init(store: store, sync: sync)
18 self.readOnly = readOnly
19 }
20
21 public init(store: WorkspaceStore, sync: (@Sendable () async -> BankSync.Report)? = nil) {
22 self.store = store
23 self.sync = sync ?? { await BankSync(store: store).syncAll() }
24 }
25
26 struct Tool {
27 let name: String, summary: String
28 var fields: [String: [String: Any]] = [:]
29 var required: [String] = []
30 var writes = false, network = false
31 var json: [String: Any] {
32 ["name": name, "description": summary,
33 "inputSchema": ["type": "object", "properties": fields, "required": required, "additionalProperties": false],
34 "annotations": ["readOnlyHint": !writes, "destructiveHint": false, "idempotentHint": !writes, "openWorldHint": network]]
35 }
36 }
37
38 static var str: [String: Any] { ["type": "string"] }
39 static var num: [String: Any] { ["type": "number"] }
40 static var bool: [String: Any] { ["type": "boolean"] }
41 static var strs: [String: Any] { ["type": "array", "items": ["type": "string"]] }
42 static var day: [String: Any] { ["type": "string", "description": "yyyy-MM-dd"] }
43 static var month: [String: Any] { ["type": "string", "description": "yyyy-MM, default this month"] }
44 static var limit: [String: Any] { ["type": "integer", "minimum": 1, "maximum": 500] }
45
46 /// Name and description of every tool, for the Claude extension's manifest.
47 public static var toolSummaries: [(name: String, summary: String)] { tools.map { ($0.name, $0.summary) } }
48
49 static var tools: [Tool] { [
50 .init(name: "get_status", summary: "Connections, account count, last bank sync, review queue size and whether agents may make changes. Call this first."),
51 .init(name: "list_accounts", summary: "Every account with institution, type and balance (money owed is negative)."),
52 .init(name: "get_net_worth", summary: "Net worth now, by account group, and a daily series for the last N days.",
53 fields: ["days": ["type": "integer", "minimum": 1, "maximum": 730]]),
54 .init(name: "list_transactions", summary: "Search transactions. All filters optional; newest first.",
55 fields: ["query": str, "category_id": str, "account_id": str, "from": day, "to": day, "tag": str, "unreviewed_only": bool, "limit": limit]),
56 .init(name: "get_spending", summary: "Spending by category for a month, with income and the total.", fields: ["month": month]),
57 .init(name: "list_categories", summary: "Categories with their groups and IDs."),
58 .init(name: "list_rules", summary: "Categorization rules in the order they apply."),
59 .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]),
60 .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.",
61 fields: ["savings_rate": ["type": "integer", "minimum": 0, "maximum": 60, "description": "Percent of income to keep free, default 20"]]),
62 .init(name: "list_recurring", summary: "Recurring charges Bucksley found, with cadence, amount and next expected date."),
63 .init(name: "get_review_queue", summary: "Transactions not yet marked reviewed, most worth a look first (flagged, uncategorized, large).", fields: ["limit": limit]),
64 .init(name: "get_cash_flow", summary: "Income, spend, net and savings rate for each of the last N months, plus monthly averages.",
65 fields: ["months": ["type": "integer", "minimum": 1, "maximum": 36]]),
66 .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."),
67 .init(name: "mark_reviewed", summary: "Mark transactions reviewed (or not).", fields: ["transaction_ids": strs, "reviewed": bool], required: ["transaction_ids"], writes: true),
68 .init(name: "set_category", summary: "Recategorize a transaction.", fields: ["transaction_id": str, "category_id": str], required: ["transaction_id", "category_id"], writes: true),
69 .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),
70 .init(name: "rename_transaction", summary: "Give a transaction a clearer name.", fields: ["transaction_id": str, "name": str], required: ["transaction_id", "name"], writes: true),
71 .init(name: "set_tags", summary: "Replace a transaction's tags.", fields: ["transaction_id": str, "tags": strs], required: ["transaction_id", "tags"], writes: true),
72 .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.",
73 fields: ["match_text": str, "category_id": str, "rename": str, "tags": strs, "mark_reviewed": bool, "min_amount": num, "max_amount": num],
74 required: ["match_text"], writes: true),
75 .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),
76 .init(name: "create_smart_budgets", summary: "Create the smart budget plan's budgets (all categories, or only category_ids). Other budgets are kept.",
77 fields: ["savings_rate": ["type": "integer", "minimum": 0, "maximum": 60], "category_ids": strs], writes: true),
78 .init(name: "sync_now", summary: "Pull fresh balances and transactions from every bank connection on this Mac now.", writes: true, network: true)
79 ] }
80
81 // MARK: Transport
82
83 public func run() async {
84 let input = FileHandle.standardInput, output = FileHandle.standardOutput
85 var line = Data()
86 while true {
87 let chunk = input.availableData
88 if chunk.isEmpty { if !line.isEmpty { await respond(line, output) }; return }
89 for byte in chunk {
90 if byte == 10 { if !line.isEmpty { await respond(line, output) }; line.removeAll(keepingCapacity: true) }
91 else if line.count < 1_048_576 { line.append(byte) }
92 }
93 }
94 }
95
96 private func respond(_ data: Data, _ output: FileHandle) async {
97 let reply: [String: Any]?
98 if let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] { reply = await handle(request) }
99 else { reply = failure(NSNull(), -32700, "Parse error.") }
100 if let reply, var json = try? JSONSerialization.data(withJSONObject: reply) { json.append(10); try? output.write(contentsOf: json) }
101 }
102
103 public func handle(_ request: [String: Any]) async -> [String: Any]? {
104 let id = request["id"] ?? NSNull()
105 guard let method = request["method"] as? String else { return failure(id, -32600, "Invalid request.") }
106 guard request["id"] != nil else { return nil } // notification
107 let params = request["params"] as? [String: Any] ?? [:]
108 switch method {
109 case "initialize":
110 if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String { clientName = name }
111 let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
112 let asked = params["protocolVersion"] as? String ?? ""
113 return success(id, ["protocolVersion": supported.contains(asked) ? asked : supported[0],
114 "capabilities": ["tools": ["listChanged": false]],
115 "serverInfo": ["name": "bucksley", "version": "0.1.0"],
116 "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."])
117 case "ping": return success(id, [:])
118 case "tools/list": return success(id, ["tools": Self.tools.filter { !readOnly || !$0.writes }.map(\.json)])
119 case "tools/call":
120 let name = params["name"] as? String ?? ""
121 let args = params["arguments"] as? [String: Any] ?? [:]
122 do {
123 let result = try await call(name, args)
124 let text = String(decoding: try JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]), as: UTF8.self)
125 return success(id, ["content": [["type": "text", "text": text]], "structuredContent": result])
126 } catch {
127 return success(id, ["content": [["type": "text", "text": error.localizedDescription]], "isError": true])
128 }
129 default: return failure(id, -32601, "Unknown method \(method).")
130 }
131 }
132
133 // MARK: Tools
134
135 func call(_ name: String, _ a: [String: Any]) async throws -> [String: Any] {
136 guard let tool = Self.tools.first(where: { $0.name == name }) else { throw BucksleyError.missing("Unknown tool \(name).") }
137 let ledger = try store.ledger()
138 let ws = ledger.workspace
139 if tool.writes && readOnly { throw BucksleyError.notAllowed("Ask Bucksley's agent can only read.") }
140 if tool.writes && !ws.settings.agentsCanWrite { throw BucksleyError.notAllowed("Turn on “Let agents make changes” in Bucksley → Settings → Agents.") }
141 func s(_ k: String) -> String? { (a[k] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty }
142 func need(_ k: String) throws -> String { guard let v = s(k) else { throw BucksleyError.missing("\(k) is required.") }; return v }
143 func money(_ k: String) -> Decimal? { (a[k] as? NSNumber).flatMap { Decimal(string: $0.stringValue) } }
144 func txID() throws -> String {
145 let id = try need("transaction_id")
146 guard ledger.entries.contains(where: { $0.id == id }) else { throw BucksleyError.missing("No transaction \(id).") }
147 return id
148 }
149 func category() throws -> String {
150 let id = try need("category_id")
151 guard ws.category(id) != nil else { throw BucksleyError.missing("No category \(id). Call list_categories.") }
152 return id
153 }
154 let month = s("month") ?? MonthKey.current
155 let limit = a["limit"] as? Int ?? 100
156
157 switch name {
158 case "get_status":
159 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)] },
160 "accounts": ledger.visibleAccounts.count, "transactions": ledger.entries.count, "review_queue": ledger.reviewQueue.count,
161 "net_worth": ledger.netWorth.jsonMoney, "last_sync_at": orNull(ws.settings.lastSyncAt?.ISO8601Format()),
162 "agents_can_write": ws.settings.agentsCanWrite, "read_only_banking": true]
163 case "list_accounts":
164 return ["accounts": ledger.visibleAccounts.map { ["id": $0.id, "name": $0.displayName, "institution": $0.institution, "type": $0.kind.rawValue,
165 "group": $0.kind.group.rawValue, "balance": $0.balance.jsonMoney, "currency": $0.currency,
166 "available": orNull($0.available?.jsonMoney), "as_of": $0.balanceDate.ISO8601Format()] }]
167 case "get_net_worth":
168 let days = a["days"] as? Int ?? 90
169 return ["net_worth": ledger.netWorth.jsonMoney, "assets": ledger.assets.jsonMoney, "debts": ledger.debts.jsonMoney,
170 "by_group": Dictionary(uniqueKeysWithValues: AccountGroup.allCases.map { ($0.rawValue, ledger.total($0).jsonMoney) }),
171 "series": ledger.netWorthSeries(days: days).map { ["day": $0.day, "total": $0.total.jsonMoney] }]
172 case "list_transactions":
173 let rows = ledger.search(s("query") ?? "", categoryID: s("category_id"), accountID: s("account_id"), unreviewedOnly: a["unreviewed_only"] as? Bool ?? false,
174 from: s("from"), to: s("to"), tag: s("tag"))
175 return ["count": rows.count, "transactions": rows.prefix(limit).map { row($0, ws) }]
176 case "get_spending":
177 let spend = ledger.spending(month: month)
178 return ["month": month, "total": spend.reduce(Decimal(0)) { $0 + $1.amount }.jsonMoney, "income": ledger.income(month: month).jsonMoney,
179 "categories": spend.map { ["category_id": $0.categoryID, "name": ws.category($0.categoryID)?.name ?? $0.categoryID, "amount": $0.amount.jsonMoney] }]
180 case "list_categories":
181 return ["groups": ws.groups.map { g in ["id": g.id, "name": g.name,
182 "categories": ws.categories.filter { $0.groupID == g.id }.map { ["id": $0.id, "name": $0.name, "kind": $0.kind.rawValue] }] }]
183 case "list_rules":
184 return ["rules": ws.rules.map { ["id": $0.id, "match_text": $0.matchText, "category_id": orNull($0.setCategoryID), "rename": orNull($0.rename),
185 "tags": $0.addTags, "mark_reviewed": $0.markReviewed, "enabled": $0.enabled] }]
186 case "list_budgets":
187 return ["month": month,
188 "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,
189 "rollover": $0.budget.rollover, "carried": $0.carried.jsonMoney, "spent": $0.spent.jsonMoney,
190 "remaining": $0.remaining.jsonMoney, "progress": $0.progress, "month_elapsed": $0.pace] },
191 "suggestions": ledger.budgetSuggestions().map { ["category_id": $0.categoryID, "amount": $0.amount.jsonMoney, "typical_month": $0.typical.jsonMoney, "reason": $0.reason] }]
192 case "get_smart_budget_plan":
193 let plan = ledger.smartBudgetPlan(savingsRate: (a["savings_rate"] as? NSNumber)?.intValue ?? 20)
194 return ["months": plan.months, "typical_income": plan.income.jsonMoney, "typical_spending": plan.typicalSpending.jsonMoney,
195 "savings_rate": plan.savingsRate, "savings_goal": plan.savingsGoal.jsonMoney, "plan_total": plan.total.jsonMoney,
196 "left_over": plan.leftOver.jsonMoney, "summary": plan.summary,
197 "budgets": plan.items.map { ["category_id": $0.categoryID, "name": $0.name, "fixed": $0.fixed, "typical_month": $0.typical.jsonMoney,
198 "recommended": $0.recommended.jsonMoney, "current": $0.current.map { $0.jsonMoney } as Any? ?? NSNull(), "reason": $0.reason] }]
199 case "list_recurring":
200 return ["recurring": ledger.recurring().map { ["id": $0.id, "name": $0.name, "cadence": $0.cadence.rawValue, "amount": $0.amount.jsonMoney,
201 "last": $0.lastDay, "next": $0.nextDay, "status": $0.status.rawValue, "count": $0.count] }]
202 case "get_cash_flow":
203 let flow = ledger.cashFlow(months: a["months"] as? Int ?? 12)
204 let avg = ledger.cashFlowAverages(flow)
205 return ["months": flow.map { ["month": $0.month, "income": $0.income.jsonMoney, "spend": $0.spend.jsonMoney, "net": $0.net.jsonMoney,
206 "savings_rate": orNull($0.savingsRate)] },
207 "average": ["income": avg.income.jsonMoney, "spend": avg.spend.jsonMoney, "net": avg.net.jsonMoney, "savings_rate": orNull(avg.savingsRate)]]
208 case "get_insights":
209 return ["flags": ledger.flags().map { ["transaction_id": $0.entryID, "kind": $0.kind.rawValue, "reason": $0.reason] },
210 "refund_matches": ledger.refundMatches().map { ["refund_id": $0.refundID, "purchase_id": $0.purchaseID,
211 "refund": entryName($0.refundID, ledger), "purchase": entryName($0.purchaseID, ledger)] },
212 "category_suggestions": ledger.historySuggestions().map { ["transaction_id": $0.entryID, "category_id": $0.categoryID, "reason": $0.reason] },
213 "last_month_recap": orNull(ledger.recap()?.facts)]
214 case "get_review_queue":
215 let queue = ledger.prioritizedReviewQueue()
216 return ["count": queue.count, "transactions": queue.prefix(limit).map { row($0, ws) }]
217 case "mark_reviewed":
218 let ids = (a["transaction_ids"] as? [String] ?? []).filter { id in ledger.entries.contains { $0.id == id } }
219 guard !ids.isEmpty else { throw BucksleyError.missing("None of those transaction IDs exist.") }
220 let reviewed = a["reviewed"] as? Bool ?? true
221 for id in ids { try store.edit(id, device: clientName) { $0.reviewed = reviewed } }
222 try log("mark_reviewed", "Marked \(ids.count) transaction\(ids.count == 1 ? "" : "s") \(reviewed ? "reviewed" : "unreviewed")")
223 return ["updated": ids.count]
224 case "set_category":
225 let id = try txID(), c = try category()
226 try store.edit(id, device: clientName) { $0.categoryID = c }
227 try log("set_category", "Set \(entryName(id, ledger)) to \(ws.category(c)?.name ?? c)")
228 return ["ok": true]
229 case "set_note":
230 let id = try txID(), note = a["note"] as? String ?? ""
231 try store.edit(id, device: clientName) { $0.note = note }
232 try log("set_note", "Noted \(entryName(id, ledger))")
233 return ["ok": true]
234 case "rename_transaction":
235 let id = try txID(), newName = try need("name")
236 try store.edit(id, device: clientName) { $0.name = newName }
237 try log("rename_transaction", "Renamed \(entryName(id, ledger)) to \(newName)")
238 return ["ok": true]
239 case "set_tags":
240 let id = try txID(), tags = (a["tags"] as? [String] ?? []).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
241 try store.edit(id, device: clientName) { $0.tags = tags }
242 try log("set_tags", "Tagged \(entryName(id, ledger)) \(tags.joined(separator: ", "))")
243 return ["ok": true]
244 case "create_rule":
245 let text = try need("match_text")
246 let c = s("category_id")
247 if let c, ws.category(c) == nil { throw BucksleyError.missing("No category \(c).") }
248 let rule = Rule(matchText: text, minAmount: money("min_amount"), maxAmount: money("max_amount"), setCategoryID: c, rename: s("rename"),
249 addTags: a["tags"] as? [String] ?? [], markReviewed: a["mark_reviewed"] as? Bool ?? false)
250 let matches = ledger.entries.filter { rule.matches($0.transaction) }.count
251 try store.update { ws in
252 ws.rules.insert(rule, at: 0)
253 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)
254 }
255 return ["rule_id": rule.id, "matches_existing": matches]
256 case "set_budget":
257 let c = try category()
258 guard let amount = money("amount"), amount >= 0 else { throw BucksleyError.missing("amount must be 0 or more.") }
259 try store.update { ws in
260 ws.budgets.removeAll { $0.categoryID == c }
261 if amount > 0 { ws.budgets.append(Budget(categoryID: c, amount: amount, rollover: a["rollover"] as? Bool ?? false)) }
262 ws.agentLog.insert(AgentAction(client: clientName, tool: "set_budget",
263 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)
264 }
265 return ["ok": true]
266 case "create_smart_budgets":
267 let plan = ledger.smartBudgetPlan(savingsRate: (a["savings_rate"] as? NSNumber)?.intValue ?? 20)
268 let only = (a["category_ids"] as? [String]).map(Set.init)
269 let chosen = plan.items.filter { only?.contains($0.categoryID) ?? true }
270 guard !chosen.isEmpty else { throw BucksleyError.missing("No categories in the plan match.") }
271 try store.update { ws in
272 SmartBudgetPlan.apply(chosen, to: &ws)
273 ws.agentLog.insert(AgentAction(client: clientName, tool: "create_smart_budgets", summary: "Created \(chosen.count) smart budget\(chosen.count == 1 ? "" : "s")"), at: 0)
274 }
275 return ["ok": true, "created": chosen.map { ["category_id": $0.categoryID, "amount": $0.recommended.jsonMoney] }]
276 case "sync_now":
277 let report = await sync()
278 try log("sync_now", "Synced \(report.synced.count) connection\(report.synced.count == 1 ? "" : "s")" + (report.failed.isEmpty ? "" : ", \(report.failed.count) failed"))
279 return ["synced": report.synced, "failed": report.failed, "added": report.added, "updated": report.updated]
280 default:
281 throw BucksleyError.missing("Unknown tool \(name).")
282 }
283 }
284
285 private func row(_ e: LedgerEntry, _ ws: Workspace) -> [String: Any] {
286 ["id": e.id, "day": e.day, "name": e.name, "amount": e.amount.jsonMoney, "category_id": e.categoryID,
287 "category": ws.category(e.categoryID)?.name ?? e.categoryID, "account": ws.account(e.accountID)?.displayName ?? e.accountID,
288 "note": orNull(e.note), "tags": e.tags, "reviewed": e.reviewed, "pending": e.transaction.pending, "bank_description": e.transaction.description]
289 }
290
291 private func entryName(_ id: String, _ ledger: Ledger) -> String {
292 ledger.entries.first { $0.id == id }.map { "\($0.name) (\($0.day))" } ?? id
293 }
294
295 private func log(_ tool: String, _ summary: String) throws {
296 try store.update { ws in
297 ws.agentLog.insert(AgentAction(client: clientName, tool: tool, summary: summary), at: 0)
298 if ws.agentLog.count > 500 { ws.agentLog.removeLast(ws.agentLog.count - 500) }
299 }
300 }
301
302 private func success(_ id: Any, _ result: [String: Any]) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "result": result] }
303 private func failure(_ id: Any, _ code: Int, _ message: String) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]] }
304}
305
306extension String { var nilIfEmpty: String? { isEmpty ? nil : self } }
307
308/// JSON null for a missing value.
309func orNull(_ value: Any?) -> Any { value ?? NSNull() }
310
311extension Decimal {
312 /// Exact cents in JSON output (JSONSerialization writes NSDecimalNumber without binary noise).
313 var jsonMoney: NSDecimalNumber { NSDecimalNumber(decimal: rounded(2)) }
314}