import AppKit import Foundation import UniformTypeIdentifiers import BucksleyKit /// Connection setup for Claude Code, Codex, Gemini CLI and Claude chat, the same way Glimmer and /// Inkspring do it. Every step is an explicit action on the Agents screen; Bucksley never edits an /// agent's configuration on its own. @MainActor enum AgentSetup { static var command: String { Bundle.main.executablePath ?? "/Applications/Bucksley.app/Contents/MacOS/Bucksley" } nonisolated static let argument = "--mcp" enum SetupError: LocalizedError { case invalidConfiguration, unsafeFile, changedFile, exportFailed, noAnswer var errorDescription: String? { switch self { case .invalidConfiguration: "The existing configuration isn’t a valid MCP configuration, so Bucksley left it unchanged." case .unsafeFile: "Choose a folder whose configuration is a regular file, not a link or folder." case .changedFile: "The project’s configuration changed while saving. Try again." case .exportFailed: "Bucksley couldn’t save the Claude extension. Choose another location and try again." case .noAnswer: "Bucksley didn’t answer. Quit and reopen it, then try again." } } } // MARK: Claude Code and Gemini CLI nonisolated static func mergedProjectConfiguration(existing: Data?, command: String) throws -> (data: Data, replaces: Bool) { let entry: [String: Any] = ["type": "stdio", "command": command, "args": [argument]] var root: [String: Any] = [:] if let existing, !existing.isEmpty { guard let parsed = try? JSONSerialization.jsonObject(with: existing) as? [String: Any] else { throw SetupError.invalidConfiguration } root = parsed } if let servers = root["mcpServers"], !(servers is [String: Any]) { throw SetupError.invalidConfiguration } var servers = root["mcpServers"] as? [String: Any] ?? [:] let replaces = servers["bucksley"].map { !NSDictionary(dictionary: ["entry": $0]).isEqual(to: ["entry": entry]) } ?? false servers["bucksley"] = entry root["mcpServers"] = servers return (try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]), replaces) } static func saveProjectConnection(gemini: Bool = false) throws -> String? { let client = gemini ? "Gemini CLI" : "Claude Code" let path = gemini ? ".gemini/settings.json" : ".mcp.json" let panel = NSOpenPanel() panel.title = "Choose your \(client) project folder" panel.message = "Bucksley adds itself to \(path) in this folder. Other servers in the file stay as they are." panel.prompt = "Save Connection" panel.canChooseFiles = false panel.canChooseDirectories = true panel.canCreateDirectories = true guard panel.runModal() == .OK, let folder = panel.url else { return nil } let scoped = folder.startAccessingSecurityScopedResource() defer { if scoped { folder.stopAccessingSecurityScopedResource() } } if gemini { let directory = folder.appending(path: ".gemini", directoryHint: .isDirectory) if (try? directory.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true { throw SetupError.unsafeFile } try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) } let file = folder.appending(path: path) let existing = try readConfiguration(file) let merged = try mergedProjectConfiguration(existing: existing, command: command) if merged.replaces { let alert = NSAlert() alert.messageText = "Replace this project’s Bucksley connection?" alert.informativeText = "Only the bucksley entry changes, so it points at this copy of Bucksley. Other MCP servers are kept." alert.addButton(withTitle: "Replace") alert.addButton(withTitle: "Cancel") guard alert.runModal() == .alertFirstButtonReturn else { return nil } } guard try readConfiguration(file) == existing else { throw SetupError.changedFile } try merged.data.write(to: file, options: .atomic) return "Saved to \(folder.lastPathComponent)/\(path). Start a new \(client) session in that folder." } private static func readConfiguration(_ file: URL) throws -> Data? { if let values = try? file.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]), values.isSymbolicLink == true || values.isDirectory == true { throw SetupError.unsafeFile } guard FileManager.default.fileExists(atPath: file.path) else { return nil } return try Data(contentsOf: file) } // MARK: Claude chat static func saveClaudeExtension() throws -> String? { let panel = NSSavePanel() panel.title = "Save the Claude extension" panel.nameFieldStringValue = "Bucksley.mcpb" panel.allowedContentTypes = [UTType(filenameExtension: "mcpb") ?? .data] panel.message = "Install this file in the Claude app under Settings → Extensions. It holds none of your money data." guard panel.runModal() == .OK, let destination = panel.url else { return nil } let staging = FileManager.default.temporaryDirectory.appending(path: "Bucksley-\(UUID().uuidString)", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: staging) } try Data(extensionServer.utf8).write(to: staging.appending(path: "server.js")) try extensionManifest(command: command).write(to: staging.appending(path: "manifest.json")) guard let tiff = NSApplication.shared.applicationIconImage?.tiffRepresentation, let png = NSBitmapImageRep(data: tiff)?.representation(using: .png, properties: [:]) else { throw SetupError.exportFailed } try png.write(to: staging.appending(path: "icon.png")) // Coordinated reading "for uploading" hands back a zip of the folder, which is what an .mcpb is. var coordinationError: NSError? var copyError: Error? NSFileCoordinator().coordinate(readingItemAt: staging, options: .forUploading, error: &coordinationError) { zip in do { try Data(contentsOf: zip).write(to: destination, options: .atomic) } catch { copyError = error } } if coordinationError != nil || copyError != nil { throw SetupError.exportFailed } NSWorkspace.shared.activateFileViewerSelecting([destination]) return "Bucksley.mcpb saved. In the Claude app, open Settings → Extensions and install it, then start a new chat." } nonisolated static func extensionManifest(command: String) throws -> Data { let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.1.0" let manifest: [String: Any] = [ "manifest_version": "0.3", "name": "bucksley", "display_name": "Bucksley", "version": version, "description": "Read your Bucksley accounts, spending and budgets on your Mac.", "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.", "author": ["name": "Protomota, LLC", "url": "https://protomota.com"], "homepage": "https://bucksley.ai", "support": "https://bucksley.ai/support/", "privacy_policies": ["https://bucksley.ai/privacy/"], "icon": "icon.png", "server": [ "type": "node", "entry_point": "server.js", "mcp_config": ["command": "node", "args": ["${__dirname}/server.js"], "env": ["BUCKSLEY_APP_EXECUTABLE": command]] ], "tools": MCPServer.toolSummaries.map { ["name": $0.name, "description": $0.summary] }, "compatibility": ["platforms": ["darwin"], "runtimes": ["node": ">=18.0.0"]] ] return try JSONSerialization.data(withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) } /// Claude supplies Node. The script only starts Bucksley's own `--mcp` server and passes messages through. nonisolated static let extensionServer = """ 'use strict'; const { spawn } = require('node:child_process'); const fs = require('node:fs'); const candidates = [process.env.BUCKSLEY_APP_EXECUTABLE, '/Applications/Bucksley.app/Contents/MacOS/Bucksley'] .filter(path => typeof path === 'string' && path.endsWith('/Bucksley.app/Contents/MacOS/Bucksley')); const executable = candidates.find(path => fs.existsSync(path)); if (!executable) { process.stderr.write('Install Bucksley for Mac in Applications, then open it once.\\n'); process.exit(1); } const bucksley = spawn(executable, ['--mcp'], { stdio: ['pipe', 'pipe', 'inherit'] }); process.stdin.pipe(bucksley.stdin); bucksley.stdout.pipe(process.stdout); process.stdin.on('end', () => bucksley.stdin.end()); bucksley.on('exit', code => process.exit(code ?? 0)); bucksley.on('error', () => { process.stderr.write('Bucksley could not start. Open Bucksley once, then try again.\\n'); process.exit(1); }); """ // MARK: Connection check /// Starts this copy of Bucksley the way an agent does and counts its tools. nonisolated static func testConnection(executable: String) async -> Result { await Task.detached { listTools(executable: executable) }.value } private nonisolated static func listTools(executable: String) -> Result { let process = Process() process.executableURL = URL(fileURLWithPath: executable) process.arguments = [argument] let input = Pipe(), output = Pipe() process.standardInput = input process.standardOutput = output process.standardError = FileHandle.nullDevice do { try process.run() let requests = [ #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"Bucksley connection check","version":"1"}}}"#, #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#, #"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"# ] input.fileHandleForWriting.write(Data((requests.joined(separator: "\n") + "\n").utf8)) try input.fileHandleForWriting.close() let finished = DispatchSemaphore(value: 0) process.terminationHandler = { _ in finished.signal() } if finished.wait(timeout: .now() + .seconds(10)) == .timedOut { process.terminate() } let data = output.fileHandleForReading.readDataToEndOfFile() for line in data.split(separator: 10) { guard let message = try? JSONSerialization.jsonObject(with: Data(line)) as? [String: Any], message["id"] as? Int == 2, let tools = (message["result"] as? [String: Any])?["tools"] as? [Any] else { continue } return .success(tools.count) } return .failure(SetupError.noAnswer) } catch { return .failure(error) } } static func copy(_ value: String) { NSPasteboard.general.clearContents() NSPasteboard.general.setString(value, forType: .string) } }