Bucksley / app / Apps / Mac / AgentSetup.swift
| 1 | import AppKit |
| 2 | import Foundation |
| 3 | import UniformTypeIdentifiers |
| 4 | import BucksleyKit |
| 5 | |
| 6 | /// Connection setup for Claude Code, Codex, Gemini CLI and Claude chat, the same way Glimmer and |
| 7 | /// Inkspring do it. Every step is an explicit action on the Agents screen; Bucksley never edits an |
| 8 | /// agent's configuration on its own. |
| 9 | @MainActor |
| 10 | enum AgentSetup { |
| 11 | static var command: String { Bundle.main.executablePath ?? "/Applications/Bucksley.app/Contents/MacOS/Bucksley" } |
| 12 | nonisolated static let argument = "--mcp" |
| 13 | |
| 14 | enum SetupError: LocalizedError { |
| 15 | case invalidConfiguration, unsafeFile, changedFile, exportFailed, noAnswer |
| 16 | |
| 17 | var errorDescription: String? { |
| 18 | switch self { |
| 19 | case .invalidConfiguration: "The existing configuration isn’t a valid MCP configuration, so Bucksley left it unchanged." |
| 20 | case .unsafeFile: "Choose a folder whose configuration is a regular file, not a link or folder." |
| 21 | case .changedFile: "The project’s configuration changed while saving. Try again." |
| 22 | case .exportFailed: "Bucksley couldn’t save the Claude extension. Choose another location and try again." |
| 23 | case .noAnswer: "Bucksley didn’t answer. Quit and reopen it, then try again." |
| 24 | } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | // MARK: Claude Code and Gemini CLI |
| 29 | |
| 30 | nonisolated static func mergedProjectConfiguration(existing: Data?, command: String) throws -> (data: Data, replaces: Bool) { |
| 31 | let entry: [String: Any] = ["type": "stdio", "command": command, "args": [argument]] |
| 32 | var root: [String: Any] = [:] |
| 33 | if let existing, !existing.isEmpty { |
| 34 | guard let parsed = try? JSONSerialization.jsonObject(with: existing) as? [String: Any] else { throw SetupError.invalidConfiguration } |
| 35 | root = parsed |
| 36 | } |
| 37 | if let servers = root["mcpServers"], !(servers is [String: Any]) { throw SetupError.invalidConfiguration } |
| 38 | var servers = root["mcpServers"] as? [String: Any] ?? [:] |
| 39 | let replaces = servers["bucksley"].map { !NSDictionary(dictionary: ["entry": $0]).isEqual(to: ["entry": entry]) } ?? false |
| 40 | servers["bucksley"] = entry |
| 41 | root["mcpServers"] = servers |
| 42 | return (try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]), replaces) |
| 43 | } |
| 44 | |
| 45 | static func saveProjectConnection(gemini: Bool = false) throws -> String? { |
| 46 | let client = gemini ? "Gemini CLI" : "Claude Code" |
| 47 | let path = gemini ? ".gemini/settings.json" : ".mcp.json" |
| 48 | let panel = NSOpenPanel() |
| 49 | panel.title = "Choose your \(client) project folder" |
| 50 | panel.message = "Bucksley adds itself to \(path) in this folder. Other servers in the file stay as they are." |
| 51 | panel.prompt = "Save Connection" |
| 52 | panel.canChooseFiles = false |
| 53 | panel.canChooseDirectories = true |
| 54 | panel.canCreateDirectories = true |
| 55 | guard panel.runModal() == .OK, let folder = panel.url else { return nil } |
| 56 | let scoped = folder.startAccessingSecurityScopedResource() |
| 57 | defer { if scoped { folder.stopAccessingSecurityScopedResource() } } |
| 58 | if gemini { |
| 59 | let directory = folder.appending(path: ".gemini", directoryHint: .isDirectory) |
| 60 | if (try? directory.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true { throw SetupError.unsafeFile } |
| 61 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) |
| 62 | } |
| 63 | let file = folder.appending(path: path) |
| 64 | let existing = try readConfiguration(file) |
| 65 | let merged = try mergedProjectConfiguration(existing: existing, command: command) |
| 66 | if merged.replaces { |
| 67 | let alert = NSAlert() |
| 68 | alert.messageText = "Replace this project’s Bucksley connection?" |
| 69 | alert.informativeText = "Only the bucksley entry changes, so it points at this copy of Bucksley. Other MCP servers are kept." |
| 70 | alert.addButton(withTitle: "Replace") |
| 71 | alert.addButton(withTitle: "Cancel") |
| 72 | guard alert.runModal() == .alertFirstButtonReturn else { return nil } |
| 73 | } |
| 74 | guard try readConfiguration(file) == existing else { throw SetupError.changedFile } |
| 75 | try merged.data.write(to: file, options: .atomic) |
| 76 | return "Saved to \(folder.lastPathComponent)/\(path). Start a new \(client) session in that folder." |
| 77 | } |
| 78 | |
| 79 | private static func readConfiguration(_ file: URL) throws -> Data? { |
| 80 | if let values = try? file.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]), |
| 81 | values.isSymbolicLink == true || values.isDirectory == true { throw SetupError.unsafeFile } |
| 82 | guard FileManager.default.fileExists(atPath: file.path) else { return nil } |
| 83 | return try Data(contentsOf: file) |
| 84 | } |
| 85 | |
| 86 | // MARK: Claude chat |
| 87 | |
| 88 | static func saveClaudeExtension() throws -> String? { |
| 89 | let panel = NSSavePanel() |
| 90 | panel.title = "Save the Claude extension" |
| 91 | panel.nameFieldStringValue = "Bucksley.mcpb" |
| 92 | panel.allowedContentTypes = [UTType(filenameExtension: "mcpb") ?? .data] |
| 93 | panel.message = "Install this file in the Claude app under Settings → Extensions. It holds none of your money data." |
| 94 | guard panel.runModal() == .OK, let destination = panel.url else { return nil } |
| 95 | |
| 96 | let staging = FileManager.default.temporaryDirectory.appending(path: "Bucksley-\(UUID().uuidString)", directoryHint: .isDirectory) |
| 97 | try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true) |
| 98 | defer { try? FileManager.default.removeItem(at: staging) } |
| 99 | try Data(extensionServer.utf8).write(to: staging.appending(path: "server.js")) |
| 100 | try extensionManifest(command: command).write(to: staging.appending(path: "manifest.json")) |
| 101 | guard let tiff = NSApplication.shared.applicationIconImage?.tiffRepresentation, |
| 102 | let png = NSBitmapImageRep(data: tiff)?.representation(using: .png, properties: [:]) else { throw SetupError.exportFailed } |
| 103 | try png.write(to: staging.appending(path: "icon.png")) |
| 104 | |
| 105 | // Coordinated reading "for uploading" hands back a zip of the folder, which is what an .mcpb is. |
| 106 | var coordinationError: NSError? |
| 107 | var copyError: Error? |
| 108 | NSFileCoordinator().coordinate(readingItemAt: staging, options: .forUploading, error: &coordinationError) { zip in |
| 109 | do { try Data(contentsOf: zip).write(to: destination, options: .atomic) } catch { copyError = error } |
| 110 | } |
| 111 | if coordinationError != nil || copyError != nil { throw SetupError.exportFailed } |
| 112 | NSWorkspace.shared.activateFileViewerSelecting([destination]) |
| 113 | return "Bucksley.mcpb saved. In the Claude app, open Settings → Extensions and install it, then start a new chat." |
| 114 | } |
| 115 | |
| 116 | nonisolated static func extensionManifest(command: String) throws -> Data { |
| 117 | let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.1.0" |
| 118 | let manifest: [String: Any] = [ |
| 119 | "manifest_version": "0.3", |
| 120 | "name": "bucksley", |
| 121 | "display_name": "Bucksley", |
| 122 | "version": version, |
| 123 | "description": "Read your Bucksley accounts, spending and budgets on your Mac.", |
| 124 | "long_description": "Connect Claude chat to Bucksley on this Mac. Bucksley → Agents controls whether Claude can make changes. No tool can move money. Claude may send what it reads to Anthropic under Claude's terms.", |
| 125 | "author": ["name": "Protomota, LLC", "url": "https://protomota.com"], |
| 126 | "homepage": "https://bucksley.ai", |
| 127 | "support": "https://bucksley.ai/support/", |
| 128 | "privacy_policies": ["https://bucksley.ai/privacy/"], |
| 129 | "icon": "icon.png", |
| 130 | "server": [ |
| 131 | "type": "node", |
| 132 | "entry_point": "server.js", |
| 133 | "mcp_config": ["command": "node", "args": ["${__dirname}/server.js"], "env": ["BUCKSLEY_APP_EXECUTABLE": command]] |
| 134 | ], |
| 135 | "tools": MCPServer.toolSummaries.map { ["name": $0.name, "description": $0.summary] }, |
| 136 | "compatibility": ["platforms": ["darwin"], "runtimes": ["node": ">=18.0.0"]] |
| 137 | ] |
| 138 | return try JSONSerialization.data(withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) |
| 139 | } |
| 140 | |
| 141 | /// Claude supplies Node. The script only starts Bucksley's own `--mcp` server and passes messages through. |
| 142 | nonisolated static let extensionServer = """ |
| 143 | 'use strict'; |
| 144 | const { spawn } = require('node:child_process'); |
| 145 | const fs = require('node:fs'); |
| 146 | |
| 147 | const candidates = [process.env.BUCKSLEY_APP_EXECUTABLE, '/Applications/Bucksley.app/Contents/MacOS/Bucksley'] |
| 148 | .filter(path => typeof path === 'string' && path.endsWith('/Bucksley.app/Contents/MacOS/Bucksley')); |
| 149 | const executable = candidates.find(path => fs.existsSync(path)); |
| 150 | if (!executable) { |
| 151 | process.stderr.write('Install Bucksley for Mac in Applications, then open it once.\\n'); |
| 152 | process.exit(1); |
| 153 | } |
| 154 | |
| 155 | const bucksley = spawn(executable, ['--mcp'], { stdio: ['pipe', 'pipe', 'inherit'] }); |
| 156 | process.stdin.pipe(bucksley.stdin); |
| 157 | bucksley.stdout.pipe(process.stdout); |
| 158 | process.stdin.on('end', () => bucksley.stdin.end()); |
| 159 | bucksley.on('exit', code => process.exit(code ?? 0)); |
| 160 | bucksley.on('error', () => { |
| 161 | process.stderr.write('Bucksley could not start. Open Bucksley once, then try again.\\n'); |
| 162 | process.exit(1); |
| 163 | }); |
| 164 | """ |
| 165 | |
| 166 | // MARK: Connection check |
| 167 | |
| 168 | /// Starts this copy of Bucksley the way an agent does and counts its tools. |
| 169 | nonisolated static func testConnection(executable: String) async -> Result<Int, Error> { |
| 170 | await Task.detached { listTools(executable: executable) }.value |
| 171 | } |
| 172 | |
| 173 | private nonisolated static func listTools(executable: String) -> Result<Int, Error> { |
| 174 | let process = Process() |
| 175 | process.executableURL = URL(fileURLWithPath: executable) |
| 176 | process.arguments = [argument] |
| 177 | let input = Pipe(), output = Pipe() |
| 178 | process.standardInput = input |
| 179 | process.standardOutput = output |
| 180 | process.standardError = FileHandle.nullDevice |
| 181 | do { |
| 182 | try process.run() |
| 183 | let requests = [ |
| 184 | #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"Bucksley connection check","version":"1"}}}"#, |
| 185 | #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, |
| 186 | #"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"# |
| 187 | ] |
| 188 | input.fileHandleForWriting.write(Data((requests.joined(separator: "\n") + "\n").utf8)) |
| 189 | try input.fileHandleForWriting.close() |
| 190 | let finished = DispatchSemaphore(value: 0) |
| 191 | process.terminationHandler = { _ in finished.signal() } |
| 192 | if finished.wait(timeout: .now() + .seconds(10)) == .timedOut { process.terminate() } |
| 193 | let data = output.fileHandleForReading.readDataToEndOfFile() |
| 194 | for line in data.split(separator: 10) { |
| 195 | guard let message = try? JSONSerialization.jsonObject(with: Data(line)) as? [String: Any], |
| 196 | message["id"] as? Int == 2, |
| 197 | let tools = (message["result"] as? [String: Any])?["tools"] as? [Any] else { continue } |
| 198 | return .success(tools.count) |
| 199 | } |
| 200 | return .failure(SetupError.noAnswer) |
| 201 | } catch { |
| 202 | return .failure(error) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | static func copy(_ value: String) { |
| 207 | NSPasteboard.general.clearContents() |
| 208 | NSPasteboard.general.setString(value, forType: .string) |
| 209 | } |
| 210 | } |