Jotley / app · jotley.ai / macOS / Utilities / JotleyMCPDesktopSetup.swift
| 1 | import AppKit |
| 2 | import Foundation |
| 3 | import UniformTypeIdentifiers |
| 4 | |
| 5 | /// Setup is an explicit user action. Never edits a personal client on launch. |
| 6 | @MainActor |
| 7 | enum JotleyMCPDesktopSetup { |
| 8 | static var command: String { Bundle.main.executableURL?.path ?? "" } |
| 9 | static let argument = "--mcp-stdio" |
| 10 | static var projectConfiguration: String? { |
| 11 | guard !command.isEmpty, let data = try? JSONSerialization.data(withJSONObject: ["mcpServers": ["jotley": [ |
| 12 | "type": "stdio", "command": command, "args": [argument] |
| 13 | ]]], options: [.prettyPrinted, .sortedKeys]) else { return nil } |
| 14 | return String(decoding: data, as: UTF8.self) |
| 15 | } |
| 16 | enum SetupError: LocalizedError { |
| 17 | case invalidConfiguration, unsafeFile, changedFile, missingResources, exportFailed |
| 18 | var errorDescription: String? { |
| 19 | switch self { |
| 20 | case .invalidConfiguration: return "The existing .mcp.json is not a valid MCP configuration. It was left unchanged." |
| 21 | case .unsafeFile: return "Choose a project with a regular .mcp.json file, rather than a link or directory." |
| 22 | case .changedFile: return "The project configuration changed during setup. Try saving again." |
| 23 | case .missingResources: return "The Claude extension is missing from this Jotley build." |
| 24 | case .exportFailed: return "The Claude extension could not be saved. Choose another location and try again." |
| 25 | } |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | nonisolated static func mergedProjectConfiguration(existing: Data?, connection: Data) throws -> (data: Data, replacesConnection: Bool) { |
| 30 | guard let incoming = try JSONSerialization.jsonObject(with: connection) as? [String: Any], |
| 31 | let entries = incoming["mcpServers"] as? [String: Any], let jotley = entries["jotley"] else { |
| 32 | throw SetupError.invalidConfiguration |
| 33 | } |
| 34 | var root: [String: Any] = [:] |
| 35 | if let existing { |
| 36 | guard let parsed = try JSONSerialization.jsonObject(with: existing) as? [String: Any] else { |
| 37 | throw SetupError.invalidConfiguration |
| 38 | } |
| 39 | root = parsed |
| 40 | } |
| 41 | if let servers = root["mcpServers"], !(servers is [String: Any]) { throw SetupError.invalidConfiguration } |
| 42 | var servers = root["mcpServers"] as? [String: Any] ?? [:] |
| 43 | let replaces = servers["jotley"].map { !NSDictionary(dictionary: ["entry": $0]).isEqual(to: ["entry": jotley]) } ?? false |
| 44 | servers["jotley"] = jotley |
| 45 | root["mcpServers"] = servers |
| 46 | return (try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys]), replaces) |
| 47 | } |
| 48 | |
| 49 | static func saveProject(configuration: String) throws -> String? { |
| 50 | let panel = NSOpenPanel() |
| 51 | panel.title = "Choose your Claude Code project" |
| 52 | panel.message = "Jotley will add its bundled connection to .mcp.json in this folder. Other servers are preserved. No Jotley access token is saved in this file." |
| 53 | panel.prompt = "Save connection" |
| 54 | panel.canChooseFiles = false |
| 55 | panel.canChooseDirectories = true |
| 56 | panel.canCreateDirectories = true |
| 57 | guard panel.runModal() == .OK, let folder = panel.url else { return nil } |
| 58 | let access = folder.startAccessingSecurityScopedResource() |
| 59 | defer { if access { folder.stopAccessingSecurityScopedResource() } } |
| 60 | let file = folder.appendingPathComponent(".mcp.json") |
| 61 | let existing = try readConfiguration(file) |
| 62 | let merged = try mergedProjectConfiguration(existing: existing, connection: Data(configuration.utf8)) |
| 63 | if merged.replacesConnection { |
| 64 | let alert = NSAlert() |
| 65 | alert.messageText = "Replace this project’s Jotley connection?" |
| 66 | alert.informativeText = "This updates only the jotley entry to use this copy of Jotley. Other MCP servers and project settings are preserved." |
| 67 | alert.addButton(withTitle: "Replace Jotley connection") |
| 68 | alert.addButton(withTitle: "Cancel") |
| 69 | guard alert.runModal() == .alertFirstButtonReturn else { return nil } |
| 70 | } |
| 71 | let temporary = folder.appendingPathComponent(".jotley-mcp-\(UUID().uuidString).tmp") |
| 72 | defer { try? FileManager.default.removeItem(at: temporary) } |
| 73 | guard FileManager.default.createFile(atPath: temporary.path, contents: merged.data, attributes: [.posixPermissions: 0o600]) else { |
| 74 | throw SetupError.exportFailed |
| 75 | } |
| 76 | guard try readConfiguration(file) == existing else { throw SetupError.changedFile } |
| 77 | if existing != nil { |
| 78 | _ = try FileManager.default.replaceItemAt(file, withItemAt: temporary, options: .usingNewMetadataOnly) |
| 79 | } else { |
| 80 | try FileManager.default.moveItem(at: temporary, to: file) |
| 81 | } |
| 82 | return "Connection saved for \(folder.lastPathComponent). Open that folder in Claude’s Code tab and start a new local session. Keep this copy of Jotley in its current location." |
| 83 | } |
| 84 | |
| 85 | private static func readConfiguration(_ file: URL) throws -> Data? { |
| 86 | // fileExists follows links, so check the link itself first (including broken links). |
| 87 | if let values = try? file.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]), |
| 88 | values.isSymbolicLink == true || values.isDirectory == true { throw SetupError.unsafeFile } |
| 89 | guard FileManager.default.fileExists(atPath: file.path) else { return nil } |
| 90 | return try Data(contentsOf: file) |
| 91 | } |
| 92 | |
| 93 | static func saveClaudeExtension(endpoint: String) throws -> String? { |
| 94 | guard let resources = Bundle.main.url(forResource: "JotleyClaudeMCP", withExtension: nil) else { throw SetupError.missingResources } |
| 95 | let panel = NSSavePanel() |
| 96 | panel.title = "Save Claude chat extension" |
| 97 | panel.nameFieldStringValue = "Jotley.mcpb" |
| 98 | panel.allowedContentTypes = [UTType(filenameExtension: "mcpb") ?? .data] |
| 99 | panel.message = "Install this file in Claude’s local extensions, then paste the access token from Jotley. The extension file contains no access token." |
| 100 | guard panel.runModal() == .OK, let destination = panel.url else { return nil } |
| 101 | let staging = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) |
| 102 | try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true) |
| 103 | defer { try? FileManager.default.removeItem(at: staging) } |
| 104 | try FileManager.default.copyItem(at: resources.appendingPathComponent("server.js"), to: staging.appendingPathComponent("server.js")) |
| 105 | var manifest = try JSONSerialization.jsonObject(with: Data(contentsOf: resources.appendingPathComponent("manifest.json"))) as? [String: Any] ?? [:] |
| 106 | var server = manifest["server"] as? [String: Any] ?? [:] |
| 107 | var config = server["mcp_config"] as? [String: Any] ?? [:] |
| 108 | var environment = config["env"] as? [String: String] ?? [:] |
| 109 | environment["JOTLEY_MCP_URL"] = endpoint |
| 110 | config["env"] = environment; server["mcp_config"] = config; manifest["server"] = server |
| 111 | try JSONSerialization.data(withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys]).write(to: staging.appendingPathComponent("manifest.json")) |
| 112 | if let tiff = NSApplication.shared.applicationIconImage.tiffRepresentation, |
| 113 | let bitmap = NSBitmapImageRep(data: tiff), let png = bitmap.representation(using: .png, properties: [:]) { |
| 114 | try png.write(to: staging.appendingPathComponent("icon.png")) |
| 115 | } else { throw SetupError.missingResources } |
| 116 | let archive = staging.appendingPathExtension("mcpb") |
| 117 | defer { try? FileManager.default.removeItem(at: archive) } |
| 118 | let process = Process() |
| 119 | process.executableURL = URL(fileURLWithPath: "/usr/bin/ditto") |
| 120 | process.arguments = ["-c", "-k", "--norsrc", staging.path, archive.path] |
| 121 | process.standardOutput = FileHandle.nullDevice |
| 122 | process.standardError = FileHandle.nullDevice |
| 123 | try process.run(); process.waitUntilExit() |
| 124 | guard process.terminationStatus == 0 else { throw SetupError.exportFailed } |
| 125 | try Data(contentsOf: archive).write(to: destination, options: .atomic) |
| 126 | NSWorkspace.shared.activateFileViewerSelecting([destination]) |
| 127 | return "Jotley.mcpb saved. Install it in Claude’s Extensions settings, then paste your Jotley access token." |
| 128 | } |
| 129 | |
| 130 | static func openClient(_ bundleID: String) -> Bool { |
| 131 | guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID) else { return false } |
| 132 | NSWorkspace.shared.openApplication(at: url, configuration: .init()) |
| 133 | return true |
| 134 | } |
| 135 | } |