Branchwell

Glimmer / app · glimmertoday.ai / native / Glimmer / CoachMCP.swift

1#if os(macOS)
2import Security
3import SwiftUI
4
5enum CoachMCP {
6 static let preference = "coach-mcp-endpoint"
7 private static let keychainService = "com.protomota.glimmer.coach-mcp"
8
9 static func url(_ address: String) -> URL? {
10 guard let parts = URLComponents(string: address.trimmingCharacters(in: .whitespacesAndNewlines)),
11 parts.scheme == "http", parts.host == "127.0.0.1",
12 parts.port != nil, parts.user == nil, parts.password == nil,
13 parts.query == nil, parts.fragment == nil,
14 !parts.path.isEmpty, let url = parts.url else { return nil }
15 return url
16 }
17
18 private static func keychainQuery(for url: URL) -> [String: Any] {
19 [kSecClass as String: kSecClassGenericPassword,
20 kSecAttrService as String: keychainService, kSecAttrAccount as String: url.absoluteString]
21 }
22
23 static func token(for url: URL) -> String? {
24 var query = keychainQuery(for: url)
25 query[kSecReturnData as String] = true
26 var item: CFTypeRef?
27 guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess,
28 let data = item as? Data else { return nil }
29 return String(data: data, encoding: .utf8)
30 }
31
32 static func saveToken(_ token: String, for url: URL) throws {
33 let query = keychainQuery(for: url)
34 let value = [kSecValueData as String: Data(token.utf8)]
35 let status = SecItemUpdate(query as CFDictionary, value as CFDictionary)
36 if status == errSecItemNotFound {
37 guard SecItemAdd(query.merging(value) { _, value in value } as CFDictionary, nil) == errSecSuccess else {
38 throw CoachConnectionError.keychain
39 }
40 } else if status != errSecSuccess {
41 throw CoachConnectionError.keychain
42 }
43 }
44
45 static func removeToken(for url: URL) throws {
46 let status = SecItemDelete(keychainQuery(for: url) as CFDictionary)
47 guard status == errSecSuccess || status == errSecItemNotFound else { throw CoachConnectionError.keychain }
48 }
49
50 static func test(_ url: URL, token: String) async throws {
51 _ = try await withSession(url, token: token) { connection in
52 let result = try await connection.call("tools/list", id: 2)
53 guard let tools = result?["tools"] as? [[String: Any]],
54 tools.contains(where: { $0["name"] as? String == "coach_respond" }) else {
55 throw CoachConnectionError.missingTool
56 }
57 return true
58 }
59 }
60
61 static func reply(endpoint: String, prompt: String) async throws -> CoachReply {
62 guard let url = url(endpoint), let token = token(for: url) else { throw CoachConnectionError.invalidConnection }
63 return try await withSession(url, token: token) { connection in
64 let result = try await connection.call("tools/call", id: 2, params: [
65 "name": "coach_respond",
66 "arguments": ["instructions": CoachGuidanceInstructions.text, "prompt": prompt]
67 ])
68 guard result?["isError"] as? Bool != true,
69 let result, let payload = result["structuredContent"] as? [String: Any] else {
70 throw CoachConnectionError.invalidReply
71 }
72 let reply = try JSONDecoder().decode(CoachReply.self, from: JSONSerialization.data(withJSONObject: payload))
73 guard !reply.answer.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
74 throw CoachConnectionError.invalidReply
75 }
76 return reply
77 }
78 }
79
80 /// Asks the connected writing agent's `toolkit_respond` tool for a Toolkit result. Only the text the
81 /// person typed for this tool is sent, never journal records.
82 static func toolkit(endpoint: String, tool: ToolkitTool, input: [String: Any], prompt: String) async throws -> [String: Any] {
83 guard let url = url(endpoint), let token = token(for: url) else { throw CoachConnectionError.invalidConnection }
84 return try await withSession(url, token: token) { connection in
85 let result = try await connection.call("tools/call", id: 2, params: [
86 "name": "toolkit_respond",
87 "arguments": ["tool": tool.rawValue, "instructions": tool.instructions, "prompt": prompt, "input": input]
88 ])
89 guard result?["isError"] as? Bool != true,
90 let payload = result?["structuredContent"] as? [String: Any] else {
91 throw CoachConnectionError.invalidReply
92 }
93 return payload
94 }
95 }
96
97 private static func withSession<T>(_ url: URL, token: String, operation: (CoachMCPSession) async throws -> T) async throws -> T {
98 let connection = CoachMCPSession(url: url, token: token)
99 defer { connection.finish() }
100 try await connection.start()
101 return try await operation(connection)
102 }
103}
104
105private enum CoachConnectionError: Error {
106 case invalidConnection, invalidReply, keychain, missingTool
107}
108
109/// A one-turn Streamable HTTP client. The peer never receives access to Glimmer tools.
110private final class CoachMCPSession: NSObject, URLSessionTaskDelegate {
111 let url: URL
112 let token: String
113 private var sessionID: String?
114 private var version = "2025-11-25"
115 private lazy var session: URLSession = {
116 let options = URLSessionConfiguration.ephemeral
117 options.timeoutIntervalForRequest = 25
118 options.timeoutIntervalForResource = 55
119 options.httpShouldSetCookies = false
120 options.connectionProxyDictionary = [:]
121 return URLSession(configuration: options, delegate: self, delegateQueue: nil)
122 }()
123
124 init(url: URL, token: String) {
125 self.url = url
126 self.token = token
127 }
128
129 func start() async throws {
130 let supportedVersions = ["2025-11-25", "2025-06-18", "2025-03-26"]
131 let response = try await call("initialize", id: 1, params: [
132 "protocolVersion": version,
133 "capabilities": [String: String](),
134 "clientInfo": ["name": "Glimmer Coach", "version": "1.0"]
135 ])
136 guard let agreed = response?["protocolVersion"] as? String, supportedVersions.contains(agreed) else {
137 throw CoachConnectionError.invalidConnection
138 }
139 version = agreed
140 _ = try await call("notifications/initialized")
141 }
142
143 func call(_ method: String, id: Int? = nil, params: [String: Any]? = nil) async throws -> [String: Any]? {
144 var request = makeRequest(method: "POST")
145 var body: [String: Any] = ["jsonrpc": "2.0", "method": method]
146 if let id { body["id"] = id }
147 if let params { body["params"] = params }
148 request.httpBody = try JSONSerialization.data(withJSONObject: body)
149 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
150 request.setValue("application/json, text/event-stream", forHTTPHeaderField: "Accept")
151 let (bytes, response) = try await session.bytes(for: request)
152 guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode) else {
153 throw CoachConnectionError.invalidConnection
154 }
155 if method == "initialize" { sessionID = http.value(forHTTPHeaderField: "Mcp-Session-Id") }
156 guard let id else { return nil }
157
158 if http.mimeType == "text/event-stream" {
159 var event = Data()
160 var line = Data()
161 for try await byte in bytes {
162 if byte != 0x0A {
163 guard line.count < 64_000 else { throw CoachConnectionError.invalidReply }
164 line.append(byte)
165 continue
166 }
167 if line.last == 0x0D { line.removeLast() }
168 if line.isEmpty {
169 if let result = try decode(event, id: id) { return result }
170 event.removeAll(keepingCapacity: true)
171 } else if line.starts(with: "data:".utf8) {
172 let field = line.dropFirst(5)
173 let value = field.first == 0x20 ? field.dropFirst() : field
174 guard event.count + value.count < 64_000 else { throw CoachConnectionError.invalidReply }
175 if !event.isEmpty { event.append(0x0A) }
176 event.append(contentsOf: value)
177 }
178 line.removeAll(keepingCapacity: true)
179 }
180 } else if http.mimeType == "application/json" {
181 var data = Data()
182 for try await byte in bytes {
183 guard data.count < 64_000 else { throw CoachConnectionError.invalidReply }
184 data.append(byte)
185 }
186 if let result = try decode(data, id: id) { return result }
187 }
188 throw CoachConnectionError.invalidReply
189 }
190
191 private func decode(_ data: Data, id: Int) throws -> [String: Any]? {
192 guard !data.isEmpty else { return nil }
193 let packet = try JSONSerialization.jsonObject(with: data) as? [String: Any]
194 guard packet?["id"] as? Int == id else { return nil }
195 guard let result = packet?["result"] as? [String: Any] else { throw CoachConnectionError.invalidReply }
196 return result
197 }
198
199 private func makeRequest(method: String) -> URLRequest {
200 var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
201 request.httpMethod = method
202 request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
203 if let sessionID { request.setValue(sessionID, forHTTPHeaderField: "Mcp-Session-Id") }
204 request.setValue(version, forHTTPHeaderField: "MCP-Protocol-Version")
205 return request
206 }
207
208 func finish() {
209 if sessionID != nil {
210 var request = makeRequest(method: "DELETE")
211 request.timeoutInterval = 3
212 session.dataTask(with: request).resume()
213 }
214 session.finishTasksAndInvalidate()
215 }
216
217 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
218 newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {
219 completionHandler(nil)
220 }
221}
222
223/// The address and token for a local MCP server that provides coach_respond, shown when Coach uses one.
224struct CoachServerFields: View {
225 @AppStorage(CoachMCP.preference) private var endpoint = ""
226 @State private var address = ""
227 @State private var token = ""
228 @State private var status: String?
229 @State private var probe: Task<Void, Never>?
230
231 var body: some View {
232 VStack(alignment: .leading, spacing: 10) {
233 Text("Connect a local MCP server that provides a coach_respond tool, and optionally toolkit_respond for the Toolkit.")
234 .font(.callout).foregroundStyle(.secondary)
235 .fixedSize(horizontal: false, vertical: true)
236 TextField("Local MCP URL", text: $address, prompt: Text("http://127.0.0.1:8400/mcp"))
237 .glimmerField()
238 SecureField(endpoint.isEmpty ? "Server token" : "Replace server token", text: $token).glimmerField()
239 HStack {
240 Button(probe == nil ? "Test and connect" : "Testing…", action: connect)
241 .glimmerButton()
242 .disabled(probe != nil || CoachMCP.url(address) == nil || token.trimmingCharacters(in: .whitespaces).isEmpty)
243 if !endpoint.isEmpty {
244 Button("Disconnect", action: disconnect).glimmerButton()
245 .disabled(probe != nil)
246 }
247 }
248 if let status { Text(status).font(.callout).foregroundStyle(.secondary) }
249 }
250 .onAppear { address = endpoint }
251 .onDisappear { probe?.cancel() }
252 }
253
254 private func connect() {
255 guard let url = CoachMCP.url(address) else { return }
256 let secret = token.trimmingCharacters(in: .whitespacesAndNewlines)
257 probe = Task {
258 defer { probe = nil }
259 do {
260 try await CoachMCP.test(url, token: secret)
261 try Task.checkCancellation()
262 try CoachMCP.saveToken(secret, for: url)
263 if let old = CoachMCP.url(endpoint), old != url { try? CoachMCP.removeToken(for: old) }
264 endpoint = url.absoluteString
265 token = ""
266 status = "Connected. Coach will use this server on this Mac."
267 } catch CoachConnectionError.missingTool {
268 status = "The server answered, but couldn’t find a coach_respond tool."
269 } catch {
270 if !Task.isCancelled { status = "Couldn’t connect. Check the local server address and token." }
271 }
272 }
273 }
274
275 private func disconnect() {
276 if let url = CoachMCP.url(endpoint) { try? CoachMCP.removeToken(for: url) }
277 endpoint = ""
278 token = ""
279 status = "Disconnected. Choose another way for Coach to reply."
280 }
281}
282#endif