// SPDX-License-Identifier: GPL-3.0-or-later import AppKit import CryptoKit import Foundation import Security import SwiftUI /// Only the helper path and the grant filename go into the desktop client's configuration. struct MCPChatGPTConnection { let grantURL: URL let helper: URL let name: String init(grantURL: URL, helper: URL = Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/vcc-mcp")) { self.grantURL = grantURL self.helper = helper // Per-file names let BASIC, C and assembly grants coexist. Re-exporting to the same path reuses the entry. let suffix = SHA256.hash(data: Data(grantURL.path.utf8)).prefix(6).map { String(format: "%02x", $0) }.joined() name = "vcc-plus-oss-" + suffix } var arguments: [String] { ["--grant", grantURL.path] } enum Registration { case missing, matches, disabled, conflict } enum SetupError: LocalizedError { case manualSetup, installApp, grantUnavailable, cliFailed, timeout var errorDescription: String? { switch self { case .manualSetup: return "Use the manual steps for this version of ChatGPT." case .installApp: return "Copy VCC Plus OSS into Applications and open that copy before adding it to ChatGPT." case .grantUnavailable: return "Save a new connection file in VCC Plus before connecting." case .cliFailed: return "ChatGPT could not confirm its MCP settings. Check the entry in Settings → MCP servers." case .timeout: return "ChatGPT took too long to respond. Check the entry in Settings → MCP servers." } } } static func cli(in app: URL?) throws -> URL { guard let app else { throw SetupError.manualSetup } let cli = app.appendingPathComponent("Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex") var code: SecStaticCode? var requirement: SecRequirement? guard FileManager.default.isExecutableFile(atPath: cli.path), SecStaticCodeCreateWithPath(cli as CFURL, [], &code) == errSecSuccess, let code, SecRequirementCreateWithString(#"anchor apple generic and identifier "codex" and certificate leaf[subject.OU] = "2DC432GLL2""# as CFString, [], &requirement) == errSecSuccess, let requirement, SecStaticCodeCheckValidity(code, [], requirement) == errSecSuccess else { throw SetupError.manualSetup } return cli } private func command(_ cli: URL, _ args: [String]) throws -> (Int32, Data) { let process = Process() let pipe = Pipe() process.executableURL = cli process.arguments = args // Resolve user-level ChatGPT settings, independent of any trusted project in the app launch directory. process.currentDirectoryURL = URL(fileURLWithPath: "/", isDirectory: true) process.standardInput = FileHandle.nullDevice process.standardOutput = pipe process.standardError = pipe try process.run() let terminate = DispatchWorkItem { if process.isRunning { process.terminate() } } let forceStop = DispatchWorkItem { if process.isRunning { kill(process.processIdentifier, SIGKILL) } } DispatchQueue.global().asyncAfter(deadline: .now() + 10, execute: terminate) DispatchQueue.global().asyncAfter(deadline: .now() + 12, execute: forceStop) defer { terminate.cancel(); forceStop.cancel() } let output = pipe.fileHandleForReading.readDataToEndOfFile() process.waitUntilExit() guard process.terminationReason == .exit else { throw SetupError.timeout } return (process.terminationStatus, output) } func registration(cli: URL) throws -> Registration { let (status, bytes) = try command(cli, ["mcp", "get", "--json", name]) let lines = String(decoding: bytes, as: UTF8.self).components(separatedBy: .newlines) if status != 0 { guard lines.contains("Error: No MCP server named '\(name)' found.") else { throw SetupError.cliFailed } return .missing } // The CLI can emit a startup warning on stderr before printing its JSON record. guard let start = lines.firstIndex(where: { $0.first == "{" }), let entry = (try? JSONSerialization.jsonObject(with: Data(lines[start...].joined(separator: "\n").utf8))) as? [String: Any], entry["name"] as? String == name, let transport = entry["transport"] as? [String: Any] else { throw SetupError.cliFailed } guard transport["type"] as? String == "stdio", transport["command"] as? String == helper.path, transport["args"] as? [String] == arguments else { return .conflict } return entry["enabled"] as? Bool == true ? .matches : .disabled } func configure(app: URL?, add: Bool) throws -> String { let cli = try Self.cli(in: app) guard FileManager.default.isReadableFile(atPath: grantURL.path) else { throw SetupError.grantUnavailable } let volume = try helper.resourceValues(forKeys: [.volumeIsReadOnlyKey]) guard FileManager.default.isExecutableFile(atPath: helper.path), !(helper.path.hasPrefix("/Volumes/") && volume.volumeIsReadOnly == true), !helper.path.contains("/AppTranslocation/") else { throw SetupError.installApp } switch try registration(cli: cli) { case .matches: return "This connection is saved in ChatGPT. Restart ChatGPT if needed, then type /mcp to check the live connection." case .disabled: return "This connection is saved but disabled. Enable it in ChatGPT Settings → MCP servers." case .conflict: return "ChatGPT already uses this server name for another connection. Choose a different name in manual setup." case .missing: guard add else { return "This connection has not been added to ChatGPT yet." } } let (status, _) = try command(cli, ["mcp", "add", name, "--", helper.path] + arguments) guard status == 0, try registration(cli: cli) == .matches else { throw SetupError.cliFailed } return "Added to ChatGPT. In Settings → MCP servers, select Restart. Start a local chat and type /mcp to check the live connection." } } /// The editable starter is a runtime resource also used by Book 12. Connection details are composed at /// copy time so an edited draft cannot retain a previous connection's grant path. struct MCPProjectSetupPrompt { static let resourcePath = "PROJECT_SETUP_PREAMBLE.txt" let starter: String var text: String enum PromptError: LocalizedError { case unavailable, empty var errorDescription: String? { switch self { case .unavailable: return "The project setup starter could not be read from this app’s runtime resources." case .empty: return "The project setup prompt is empty. Enter your instructions or reset to the starter." } } } init(starter: String) throws { guard !starter.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw PromptError.empty } self.starter = starter text = starter } static func load(runtimeTemplates: URL?) throws -> Self { guard let runtimeTemplates, let text = try? String(contentsOf: runtimeTemplates.appendingPathComponent(resourcePath), encoding: .utf8) else { throw PromptError.unavailable } return try Self(starter: text) } var canCopy: Bool { !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } mutating func reset() { text = starter } func connectionDetails(_ connection: MCPChatGPTConnection) throws -> String { // Encode paths as data, including any embedded whitespace or quotation marks. // Never open the grant file: its token and other contents stay on this Mac. let details: [String: Any] = ["name": connection.name, "command": connection.helper.path, "arguments": connection.arguments] let bytes = try JSONSerialization.data(withJSONObject: details, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) return String(decoding: bytes, as: UTF8.self) } func rendered(connection: MCPChatGPTConnection, firstPrompt: String) throws -> String { guard canCopy else { throw PromptError.empty } return """ \(text.trimmingCharacters(in: .whitespacesAndNewlines)) VCC Plus connection details (configuration only; verify tool discovery and a successful request separately): \(try connectionDetails(connection)) First read-only check after discovering this connection’s tools: \(firstPrompt) """ } } struct MCPChatGPTSetup: View { let grantURL: URL let firstPrompt: String @State private var message = "" @State private var working = false @State private var expanded = false @State private var projectPrompt: MCPProjectSetupPrompt? @State private var promptMessage = "" @State private var editingPrompt = false private func configure(add: Bool) { guard !working else { return } let setup = MCPChatGPTConnection(grantURL: grantURL) let app = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.openai.codex") working = true Task { @MainActor in let result = await Task.detached(priority: .userInitiated) { do { return try setup.configure(app: app, add: add) } catch { return error.localizedDescription } }.value message = result working = false } } private func copy(_ value: String) { NSPasteboard.general.clearContents() NSPasteboard.general.setString(value, forType: .string) } private func copyProjectPrompt() { guard let projectPrompt else { return } do { let value = try projectPrompt.rendered(connection: MCPChatGPTConnection(grantURL: grantURL), firstPrompt: firstPrompt) copy(value) promptMessage = "Project setup prompt copied." } catch { promptMessage = error.localizedDescription } } @MainActor private func loadProjectPrompt() async { guard projectPrompt == nil else { return } let templates = Bundle.main.url(forResource: "RuntimeTemplates", withExtension: nil) let result = await Task.detached(priority: .userInitiated) { Result { try MCPProjectSetupPrompt.load(runtimeTemplates: templates) } }.value guard !Task.isCancelled, projectPrompt == nil else { return } switch result { case .success(let prompt): projectPrompt = prompt case .failure(let error): promptMessage = error.localizedDescription } } private var projectPromptEditor: some View { VStack(alignment: .leading, spacing: 12) { Text("Project Setup Prompt").font(.title2) Text("Edit the starter for your project. It authorizes setup only within the permissions you exported. Copying does not change your connections.") .foregroundStyle(.secondary) TextEditor(text: Binding(get: { projectPrompt?.text ?? "" }, set: { projectPrompt?.text = $0; promptMessage = "" })) .font(.body.monospaced()) .scrollContentBackground(.hidden) .padding(6) .background(.background, in: RoundedRectangle(cornerRadius: 6)) .overlay(RoundedRectangle(cornerRadius: 6).stroke(.quaternary)) .accessibilityLabel("Project setup instructions") .accessibilityIdentifier("mcp.projectSetup.instructions") Text("The current connection name, helper path and saved connection path are appended when you copy. Connection file contents are never included.") .font(.callout).foregroundStyle(.secondary) if let projectPrompt, let details = try? projectPrompt.connectionDetails(MCPChatGPTConnection(grantURL: grantURL)) { DisclosureGroup("Included connection details") { ScrollView { Text(details).font(.callout.monospaced()).textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) }.frame(maxHeight: 100) } } if !promptMessage.isEmpty { Text(promptMessage).font(.callout).textSelection(.enabled) } HStack { Button("Reset to Starter") { projectPrompt?.reset(); promptMessage = "" } .accessibilityIdentifier("mcp.projectSetup.reset") Spacer() Button("Done") { editingPrompt = false }.keyboardShortcut(.cancelAction) Button("Copy Project Setup Prompt") { copyProjectPrompt() } .disabled(projectPrompt?.canCopy != true) .keyboardShortcut(.defaultAction) .accessibilityIdentifier("mcp.projectSetup.editorCopy") } } .padding(20) .frame(minWidth: 520, idealWidth: 640, minHeight: 400, idealHeight: 540) } private func field(_ label: String, _ value: String) -> some View { HStack(alignment: .firstTextBaseline) { Text(label).frame(width: 85, alignment: .leading) Text(value).font(.callout.monospaced()).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) Button { copy(value) } label: { Image(systemName: "doc.on.doc") }.accessibilityLabel("Copy " + label) } } var body: some View { let setup = MCPChatGPTConnection(grantURL: grantURL) VStack(alignment: .leading, spacing: 8) { Text("ChatGPT for Mac").font(.headline) HStack { Button("Add to ChatGPT") { configure(add: true) } Button("Check Setup") { configure(add: false) } Button("Copy First Prompt") { copy(firstPrompt) } }.disabled(working) HStack { Button("Copy Project Setup Prompt") { copyProjectPrompt() } .disabled(projectPrompt?.canCopy != true) .accessibilityIdentifier("mcp.projectSetup.copy") Button("Edit…") { editingPrompt = true } .disabled(projectPrompt == nil) .accessibilityLabel("Edit project setup prompt") .accessibilityIdentifier("mcp.projectSetup.edit") } Text("An editable starter that authorizes setup within your exported permissions. Copying does not change your connections.") .font(.callout).foregroundStyle(.secondary) if !promptMessage.isEmpty { Text(promptMessage).font(.callout).textSelection(.enabled) } if working { ProgressView().controlSize(.small) } if !message.isEmpty { Text(message).font(.callout).textSelection(.enabled) } DisclosureGroup("Manual setup", isExpanded: $expanded) { VStack(alignment: .leading, spacing: 6) { Text("In ChatGPT Settings → MCP servers, choose Add server and select STDIO. Enter each argument separately.") field("Name", setup.name) field("Command", setup.helper.path) field("Argument 1", setup.arguments[0]) field("Argument 2", setup.arguments[1]) Text("Save, select Restart in ChatGPT, and type /mcp in a local chat. Paste the first prompt to try VCC Plus.") Link("ChatGPT MCP instructions", destination: URL(string: "https://learn.chatgpt.com/docs/extend/mcp")!) }.padding(.top, 4) } } .task { await loadProjectPrompt() } .sheet(isPresented: $editingPrompt) { projectPromptEditor } } }