Branchwell

Jotley / app · jotley.ai / scripts / mcp-integration.swift

Raw 42.7 KB on d2c8e7812d9b8c1cc5857eb6dc912d99bc5c9048
1import AppKit
2import CoreData
3import Foundation
4import MCP
5import SwiftUI
6@testable import Jotley
7
8#if !JOTLEY_MCP_DEMO
9@main
10#endif
11struct MCPIntegration {
12 @MainActor static func main() {
13 Task { @MainActor in
14 do {
15 try await checks()
16 print("PASS: Jotley MCP integration checks")
17 exit(0)
18 } catch {
19 fputs("FAIL: \(error.localizedDescription)\n", stderr)
20 exit(1)
21 }
22 }
23 NSApplication.shared.run()
24 }
25
26 @MainActor static func fixture() throws -> SharedPersistenceController {
27 let store = try SharedPersistenceController(inMemory: true)
28 let note = try store.create(title: "Release planning", text: "Maya owns the onboarding review on Friday. Alex will test accessibility. Ship after both checks pass.",
29 id: UUID(uuidString: "11111111-1111-4111-8111-111111111111")!)
30 note.setValue("Maya: onboarding review Friday. Alex: accessibility checks. Release follows approval.", forKey: "summary")
31 note.setValue("Follow up with Maya on Thursday.", forKey: "notes")
32 let tag = NSEntityDescription.insertNewObject(forEntityName: "Tag", into: store.context)
33 tag.setValue(UUID(), forKey: "id"); tag.setValue("launch", forKey: "name")
34 note.mutableSetValue(forKey: "tags").add(tag)
35 let garden = try store.create(title: "Garden ideas", text: "Plant basil and rosemary in the sunny corner.")
36 garden.setValue(Date().addingTimeInterval(-86400), forKey: "timestamp")
37 try store.save()
38 return store
39 }
40
41 static func expect(_ condition: @autoclosure () -> Bool, _ message: String) throws {
42 if !condition() { throw NSError(domain: "MCPIntegration", code: 1, userInfo: [NSLocalizedDescriptionKey: message]) }
43 }
44
45 static func text(_ content: [Tool.Content]) -> String {
46 content.compactMap { if case .text(let value, _, _) = $0 { return value }; return nil }.joined(separator: "\n")
47 }
48
49 static func connect(endpoint: String, token: String) async throws -> Client {
50 let client = Client(name: "Jotley integration client", version: "1.0", configuration: .strict)
51 let transport = HTTPClientTransport(endpoint: URL(string: endpoint)!, streaming: false, requestModifier: { request in
52 var request = request
53 request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
54 return request
55 })
56 _ = try await client.connect(transport: transport)
57 return client
58 }
59
60 static func request(endpoint: String, token: String?, headers: [String: String] = [:], method: String = "POST", body: String = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}") async throws -> Int {
61 var request = URLRequest(url: URL(string: endpoint)!)
62 request.httpMethod = method
63 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
64 request.setValue("application/json, text/event-stream", forHTTPHeaderField: "Accept")
65 request.setValue("2025-11-25", forHTTPHeaderField: "MCP-Protocol-Version")
66 if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }
67 for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }
68 if method == "POST" { request.httpBody = Data(body.utf8) }
69 let (_, response) = try await URLSession.shared.data(for: request)
70 return (response as! HTTPURLResponse).statusCode
71 }
72
73 @MainActor private static func customWordChecks(client: Client, service: JotleyMCPService, defaults: UserDefaults) async throws {
74 defaults.set("PulseCanvas", forKey: CustomSpeechWords.defaultsKey)
75 let listed = try await client.callTool(name: "list_custom_words", arguments: [:])
76 let state = try JSONSerialization.jsonObject(with: Data(text(listed.content).utf8)) as! [String: Any]
77 try expect(state["words"] as? [String] == ["PulseCanvas"], "MCP did not read the Settings preference")
78 let patch: [String: Value] = ["expected_revision": .string(state["revision"] as! String), "add": ["Textley", "pulsecanvas"]]
79 let denied = try await client.callTool(name: "update_custom_words", arguments: patch)
80 try expect(denied.isError == true, "Read-only MCP allowed a Custom Words change")
81 service.setAllowsWriting(true)
82 defer { service.setAllowsWriting(false) }
83 let applied = try await client.callTool(name: "update_custom_words", arguments: patch)
84 try expect(applied.isError != true && CustomSpeechWords.saved(in: defaults) == ["PulseCanvas", "Textley"], "MCP failed to save to the Settings preference")
85 let stale = try await client.callTool(name: "update_custom_words", arguments: patch)
86 try expect(stale.isError == true, "MCP accepted a stale word-list revision")
87 let revised = try JSONSerialization.jsonObject(with: Data(text(applied.content).utf8)) as! [String: Any]
88 let removed = try await client.callTool(name: "update_custom_words", arguments: ["expected_revision": .string(revised["revision"] as! String), "remove": ["pulsecanvas"]])
89 try expect(removed.isError != true && CustomSpeechWords.saved(in: defaults) == ["Textley"], "MCP failed to remove only the requested word")
90 print("PASS: Custom Words shares the Settings preference, checks revisions and respects Read only")
91 }
92
93 @MainActor static func checks() async throws {
94 try desktopConfigurationChecks()
95 try checklistChecks()
96 let store = try fixture()
97 let suite = "JotleyMCPTests.\(UUID().uuidString)"
98 let defaults = UserDefaults(suiteName: suite)!
99 defer { defaults.removePersistentDomain(forName: suite) }
100 let token = String(repeating: "a", count: 64) // Synthetic test credential, never a real client token.
101 let service = JotleyMCPService(defaults: defaults, port: 0, token: token)
102 await service.attach(store: store)
103 try expect(!service.enabled && !service.allowsWriting, "MCP must default to off and read only")
104 await service.setEnabled(true)
105 try expect(service.enabled, service.errorMessage ?? "Server did not start")
106 let endpoint = service.endpoint
107 try expect(URL(string: endpoint)?.host == "127.0.0.1", "Server must bind to loopback")
108
109 let missing = try await request(endpoint: endpoint, token: nil)
110 let wrong = try await request(endpoint: endpoint, token: "wrong")
111 let origin = try await request(endpoint: endpoint, token: token, headers: ["Origin": "https://example.com"])
112 let host = try await request(endpoint: endpoint, token: token, headers: ["Host": "attacker.example"])
113 let invalidVersion = try await request(endpoint: endpoint, token: token, headers: ["MCP-Protocol-Version": "1900-01-01"])
114 let get = try await request(endpoint: endpoint, token: token, method: "GET")
115 let malformed = try await request(endpoint: endpoint, token: token, body: "not json")
116 let oversized = try await request(endpoint: endpoint, token: token, body: String(repeating: "x", count: 1048577))
117 try expect(missing == 401 && wrong == 401, "Unauthenticated access was accepted")
118 try expect(origin == 403 && host == 403, "Browser/DNS rebinding guards failed")
119 try expect(invalidVersion == 400 && get == 405 && malformed == 400 && oversized == 413, "HTTP validation failed")
120 print("PASS: authentication, Origin/Host, protocol version, methods, malformed and oversized bodies")
121
122 let client = try await connect(endpoint: endpoint, token: token)
123 try expect(service.lastClientName == "Jotley integration client", "The real client handshake was not shown")
124 await service.testConnection()
125 try expect(service.testMessage?.contains("passed") == true, "The built-in connection test failed")
126 try expect(service.lastClientName == "Jotley integration client", "Self-test replaced the real agent indicator")
127 let tools = try await client.listTools().tools
128 try expect(Set(tools.map(\.name)) == ["list_notes", "search_notes", "read_note", "create_note", "update_note", "replace_note_text", "duplicate_note", "delete_note", "list_tags", "create_tag", "update_tag", "delete_tag", "list_folders", "create_folder", "update_folder", "delete_folder", "set_note_tags", "move_note", "list_summary_templates", "generate_note_summary", "create_summary_template", "update_summary_template", "delete_summary_template", "list_custom_words", "update_custom_words"], "Unexpected tools")
129 try expect(tools.filter { $0.annotations.readOnlyHint == true }.count == 7, "Read-only annotations missing")
130 try expect(tools.first { $0.name == "delete_note" }?.annotations.destructiveHint == true, "Deletion must be marked destructive")
131 let listed = try await client.callTool(name: "list_notes", arguments: ["limit": 1])
132 let listedJSON = try JSONSerialization.jsonObject(with: Data(text(listed.content).utf8)) as! [String: Any]
133 try expect((listedJSON["notes"] as? [Any])?.count == 1 && listedJSON["next_offset"] as? Int == 1, "List pagination failed")
134 let searched = try await client.callTool(name: "search_notes", arguments: ["query": "Maya"])
135 try expect(text(searched.content).contains("Release planning") && !text(searched.content).contains("Garden ideas"), "Text search failed")
136 let tagged = try await client.callTool(name: "search_notes", arguments: ["query": "launch"])
137 try expect(text(tagged.content).contains("Release planning"), "Tag search failed")
138 let noteID: Value = "11111111-1111-4111-8111-111111111111"
139 let read = try await client.callTool(name: "read_note", arguments: ["id": noteID])
140 try expect(text(read.content).contains("onboarding review") && text(read.content).contains("Follow up with Maya"), "Full note retrieval failed")
141 try expect(service.lastToolName == "read_note" && service.lastToolDate != nil, "Successful reads were not reported in Settings")
142 let chunk = try await client.callTool(name: "read_note", arguments: ["id": noteID, "section": "transcript", "offset": 5, "limit": 10])
143 let chunkJSON = try JSONSerialization.jsonObject(with: Data(text(chunk.content).utf8)) as! [String: Any]
144 try expect(chunkJSON["content"] as? String == "owns the o" && chunkJSON["next_offset"] as? Int == 15, "Transcript chunking failed")
145 for arguments: [String: Value] in [["id": "bad"], ["id": noteID, "section": "audio"], ["id": noteID, "limit": -1], ["id": noteID, "limit": 1.5], ["id": noteID, "unknown": true]] {
146 let result = try await client.callTool(name: "read_note", arguments: arguments)
147 try expect(result.isError == true, "Invalid arguments were accepted")
148 }
149 let unknown = try await client.callTool(name: "delete_note", arguments: ["id": noteID])
150 let remainingNotes = try store.notes().count
151 try expect(unknown.isError == true && remainingNotes == 2, "A write tool changed the library")
152 print("PASS: SDK initialization, discovery, metadata pagination, text/tag search, chunked reads and invalid arguments")
153
154 try await customWordChecks(client: client, service: service, defaults: defaults)
155 if ProcessInfo.processInfo.environment["JOTLEY_BRIDGE_CHECK"] != nil {
156 try await desktopBridgeCheck(endpoint: endpoint, token: token, writing: false)
157 try await desktopBridgeCheck(endpoint: endpoint, token: token, writing: false, native: true)
158 service.setAllowsWriting(true)
159 try await desktopBridgeCheck(endpoint: endpoint, token: token, writing: true)
160 try await desktopBridgeCheck(endpoint: endpoint, token: token, writing: true, native: true)
161 service.setAllowsWriting(false)
162 }
163 try await writeChecks(client: client, service: service, store: store, noteID: noteID)
164 try await organizationChecks(client: client, service: service, store: store)
165
166 let second = try await connect(endpoint: endpoint, token: token)
167 async let firstCall = client.callTool(name: "search_notes", arguments: ["query": "Maya"])
168 async let secondCall = second.callTool(name: "search_notes", arguments: ["query": "basil"])
169 let parallel = try await (firstCall, secondCall)
170 try expect(text(parallel.0.content).contains("Release planning") && text(parallel.1.content).contains("Garden ideas"), "Concurrent clients crossed responses")
171 await client.disconnect(); await second.disconnect()
172
173 await service.rotateToken()
174 let revoked = try await request(endpoint: service.endpoint, token: token)
175 try expect(service.enabled && revoked == 401, "Rotated credential was still accepted")
176 await service.setEnabled(false, persistPreference: false)
177 try expect(defaults.bool(forKey: JotleyMCPService.enabledKey), "App shutdown lost the enabled preference")
178 await service.setEnabled(false)
179 try expect(!service.enabled && !defaults.bool(forKey: JotleyMCPService.enabledKey), "Disable did not persist")
180 do {
181 _ = try await request(endpoint: service.endpoint, token: token)
182 throw NSError(domain: "MCPIntegration", code: 2, userInfo: [NSLocalizedDescriptionKey: "Disabled listener still accepted requests"])
183 } catch let error as NSError where error.domain == NSURLErrorDomain { }
184 print("PASS: concurrent clients, token revocation, shutdown preference and disabled listener")
185
186 if CommandLine.arguments.contains("--content-only") {
187 print("PASS: authenticated MCP content, organization and template checks; Keychain persistence check not requested")
188 return
189 }
190 // Exercise the production Keychain path under the harness's separate identity.
191 func configuredToken(_ service: JotleyMCPService) throws -> String {
192 guard let config = service.clientConfiguration,
193 let json = try JSONSerialization.jsonObject(with: Data(config.utf8)) as? [String: Any],
194 let servers = json["mcpServers"] as? [String: [String: Any]],
195 let headers = servers["jotley"]?["headers"] as? [String: String],
196 let header = headers["Authorization"], header.hasPrefix("Bearer ") else {
197 throw LocalError.message("Copied client configuration is invalid")
198 }
199 return String(header.dropFirst(7))
200 }
201 let reusablePort = URL(string: endpoint)!.port!
202 let persisted = JotleyMCPService(defaults: defaults, port: reusablePort)
203 await persisted.attach(store: store)
204 await persisted.setEnabled(true)
205 try expect(persisted.enabled, persisted.errorMessage ?? "Keychain-backed server did not start")
206 let savedToken = try configuredToken(persisted)
207 persisted.setAllowsWriting(true)
208 let savedClient = try await connect(endpoint: persisted.endpoint, token: savedToken)
209 _ = try await savedClient.listTools()
210 await savedClient.disconnect()
211 await persisted.setEnabled(false, persistPreference: false)
212 let relaunched = JotleyMCPService(defaults: defaults, port: reusablePort)
213 await relaunched.attach(store: store)
214 let restoredToken = try configuredToken(relaunched)
215 try expect(savedToken == restoredToken && relaunched.enabled && relaunched.allowsWriting, "Token, enable or access preference did not survive service recreation")
216 await relaunched.rotateToken()
217 let rotatedToken = try configuredToken(relaunched)
218 let revokedSaved = try await request(endpoint: relaunched.endpoint, token: savedToken)
219 let validNew = try await request(endpoint: relaunched.endpoint, token: rotatedToken)
220 try expect(savedToken != rotatedToken && revokedSaved == 401 && validNew == 200, "Keychain rotation did not revoke old access")
221 await relaunched.setEnabled(false)
222 print("PASS: sandbox Keychain generation, copied configuration, restored enable preference and persisted rotation")
223 }
224
225 static func desktopConfigurationChecks() throws {
226 let incoming = Data(#"{"mcpServers":{"jotley":{"type":"http","url":"http://127.0.0.1:17321/mcp","headers":{"Authorization":"Bearer test"}}}}"#.utf8)
227 let existing = Data(#"{"keep":"value","mcpServers":{"other":{"command":"other"},"jotley":{"url":"old"}}}"#.utf8)
228 let merged = try JotleyMCPDesktopSetup.mergedProjectConfiguration(existing: existing, connection: incoming)
229 let root = try JSONSerialization.jsonObject(with: merged.data) as! [String: Any]
230 let servers = root["mcpServers"] as! [String: Any]
231 try expect(root["keep"] as? String == "value" && servers["other"] != nil && merged.replacesConnection, "Project merge lost settings or did not identify replacement")
232 let unchanged = try JotleyMCPDesktopSetup.mergedProjectConfiguration(existing: merged.data, connection: incoming)
233 try expect(!unchanged.replacesConnection && unchanged.data == merged.data, "Identical setup was not idempotent")
234 let new = try JotleyMCPDesktopSetup.mergedProjectConfiguration(existing: nil, connection: incoming)
235 try expect(!new.replacesConnection, "New configuration requires replacement")
236 for source in ["[]", "not json", "{\"mcpServers\":[]}"] {
237 do {
238 _ = try JotleyMCPDesktopSetup.mergedProjectConfiguration(existing: Data(source.utf8), connection: incoming)
239 throw LocalError.message("Invalid configuration was accepted")
240 } catch is JotleyMCPDesktopSetup.SetupError { }
241 catch let error as NSError where error.domain == NSCocoaErrorDomain { }
242 }
243 print("PASS: desktop project merge preserves other entries, detects replacement and rejects invalid files")
244 }
245
246 @MainActor static func desktopBridgeCheck(endpoint: String, token: String, writing: Bool, native: Bool = false) async throws {
247 guard let script = Bundle.main.url(forResource: "mcp-desktop-bridge-check", withExtension: "cjs"),
248 let bridge = Bundle.main.url(forResource: "JotleyClaudeMCP", withExtension: nil)?.appendingPathComponent("server.js") else {
249 throw LocalError.message("Desktop bridge test resources are missing")
250 }
251 let process = Process()
252 guard let node = ProcessInfo.processInfo.environment["JOTLEY_NODE_BINARY"] else {
253 throw LocalError.message("Set JOTLEY_NODE_BINARY to the Node executable used for bridge verification")
254 }
255 process.executableURL = URL(fileURLWithPath: node)
256 process.arguments = [script.path]
257 var environment = ProcessInfo.processInfo.environment
258 environment["JOTLEY_MCP_URL"] = endpoint
259 environment["JOTLEY_MCP_TOKEN"] = token
260 environment["JOTLEY_BRIDGE_SCRIPT"] = bridge.path
261 environment["JOTLEY_BRIDGE_WRITE"] = writing ? "1" : "0"
262 if native {
263 environment["JOTLEY_NATIVE_BRIDGE_BINARY"] = Bundle.main.bundleURL.appendingPathComponent("Contents/MacOS/JotleyBridge").path
264 environment["JOTLEY_MCP_TEST_ENDPOINT"] = endpoint
265 environment["JOTLEY_MCP_TEST_TOKEN"] = token
266 }
267 process.environment = environment
268 let status: Int32 = try await withCheckedThrowingContinuation { continuation in
269 process.terminationHandler = { continuation.resume(returning: $0.terminationStatus) }
270 do { try process.run() } catch { continuation.resume(throwing: error) }
271 }
272 try expect(status == 0, "Desktop extension bridge verification failed")
273 }
274
275 @MainActor static func checklistChecks() throws {
276 let source = "- [ ] **Maya**: Review onboarding.\n + [x] 📝 **Alex**: Test accessibility.\n* [X] Ship.\n1. [ ] Follow up.\n- [Guide](https://example.com)\n- [Maya] is a literal label.\n- `[ ]` is code."
277 let lines = ParsedNoteMarkdown.rendering(source).lines
278 try expect(lines.prefix(4).map(\.taskState) == [.unchecked, .checked, .checked, .unchecked], "Task-list state was not parsed")
279 try expect(String(lines[0].text.characters) == "Maya: Review onboarding." && lines[1].indentation == 2 && String(lines[1].text.characters).hasPrefix("📝 Alex:"), "Task markers leaked or Unicode/inline formatting was lost")
280 try expect(lines.dropFirst(4).allSatisfy { $0.taskState == nil } && String(lines[5].text.characters).hasPrefix("[Maya]"), "Literal brackets or links became tasks")
281 try expect("- [ ] Maya: Review.\n- [X] Alex: Test.".previewSnippet() == "Maya: Review. Alex: Test.", "Sidebar preview leaked task brackets")
282 for heading in ["", "## Action Items\n", "## Key Points\n"] {
283 let summary = StructuredSummary(ParsedNoteMarkdown.rendering(heading + "- [ ] Maya: Review.\n- [x] Alex: Test."))
284 let items = (summary.overview?.items ?? []) + summary.sections.flatMap(\.items)
285 try expect(items.map(\.taskState) == [.unchecked, .checked] && items[0].label.map { String($0.characters) } == "Maya", "Structured summary dropped checkbox state or owner label")
286 }
287 for tail in ["- [", "- [x", "- [ ]", "- [X]"] {
288 try expect(ParsedNoteMarkdown.rendering(tail, isStreaming: true).lines.allSatisfy { $0.text.characters.isEmpty }, "Incomplete streamed task marker was exposed")
289 }
290 print("PASS: Markdown tasks render checked/unchecked state without raw brackets; previews, owner labels, nesting, Unicode and literal brackets preserved")
291 }
292
293 @MainActor static func organizationChecks(client: Client, service: JotleyMCPService, store: SharedPersistenceController) async throws {
294 func json(_ result: (content: [Tool.Content], isError: Bool?)) throws -> [String: Any] {
295 try expect(result.isError != true, "Organization tool failed: \(text(result.content))")
296 return try JSONSerialization.jsonObject(with: Data(text(result.content).utf8)) as! [String: Any]
297 }
298 func read(_ id: Value) async throws -> [String: Any] { try json(await client.callTool(name: "read_note", arguments: ["id": id])) }
299 func revision(_ id: Value) async throws -> Value { .string(try await read(id)["revision"] as! String) }
300 let fake: Value = "11111111-1111-4111-8111-111111111111"
301 for name in ["create_tag", "update_tag", "delete_tag", "create_folder", "update_folder", "delete_folder", "set_note_tags", "move_note", "generate_note_summary"] {
302 var arguments: [String: Value] = ["id": fake, "expected_revision": "unused"]
303 if name.hasPrefix("create_") { arguments = ["name": "Denied"] }
304 if name == "update_tag" { arguments["name"] = "Denied" }
305 if name == "set_note_tags" { arguments["tag_ids"] = [] }
306 if name == "move_note" { arguments["folder_id"] = .null }
307 if name == "generate_note_summary" { arguments["template"] = .string(LocalSummaryTemplate.auto.key) }
308 let denied = try await client.callTool(name: name, arguments: arguments)
309 try expect(denied.isError == true && text(denied.content).contains("read only"), "Read only allowed \(name)")
310 }
311 service.setAllowsWriting(true)
312 let created = try json(await client.callTool(name: "create_note", arguments: ["title": "Organization fixture", "transcript": "Maya will review the launch.", "summary": "Original summary"]))
313 let id = Value.string(created["id"] as! String)
314 let tag = try json(await client.callTool(name: "create_tag", arguments: ["name": "Release Review"]))
315 let tagID = Value.string(tag["id"] as! String)
316 let same = try json(await client.callTool(name: "create_tag", arguments: ["name": "release-review"]))
317 try expect(same["id"] as? String == tag["id"] as? String, "Equivalent tag names duplicated")
318 let folder = try json(await client.callTool(name: "create_folder", arguments: ["name": "Launches"]))
319 let folderID = Value.string(folder["id"] as! String)
320 _ = try json(await client.callTool(name: "set_note_tags", arguments: ["id": id, "expected_revision": try await revision(id), "tag_ids": .array([tagID])]))
321 let moved = try json(await client.callTool(name: "move_note", arguments: ["id": id, "expected_revision": try await revision(id), "folder_id": folderID]))
322 try expect(moved["folder"] as? String == "Launches" && moved["tags"] as? [String] == ["Release-Review"], "Membership assignment failed")
323 let filtered = try json(await client.callTool(name: "search_notes", arguments: ["query": "Maya", "folder_id": folderID, "tag_id": tagID]))
324 try expect((filtered["notes"] as? [[String: Any]])?.count == 1, "Combined folder/tag filtering failed")
325 func libraryItem(_ name: String, id: Value) async throws -> [String: Any] {
326 let result = try json(await client.callTool(name: "list_" + name, arguments: [:]))
327 return (result[name] as! [[String: Any]]).first { $0["id"] as? String == id.stringValue }!
328 }
329 let currentTag = try await libraryItem("tags", id: tagID)
330 let oldRevision = try await revision(id)
331 _ = try json(await client.callTool(name: "update_tag", arguments: ["id": tagID, "expected_revision": .string(currentTag["revision"] as! String), "name": "Launch Ready"]))
332 let changedRevision = try await revision(id)
333 try expect(changedRevision != oldRevision, "Global tag rename did not invalidate the note revision")
334 let stale = try await client.callTool(name: "move_note", arguments: ["id": id, "expected_revision": oldRevision, "folder_id": .null])
335 try expect(stale.isError == true, "Stale organization edit accepted")
336 let currentFolder = try await libraryItem("folders", id: folderID)
337 _ = try json(await client.callTool(name: "update_folder", arguments: ["id": folderID, "expected_revision": .string(currentFolder["revision"] as! String), "name": "Launch work", "sort_order": 3]))
338 let note = try store.notes().first { $0.localNoteID?.uuidString == id.stringValue }!
339 let operation = store.beginNoteOperation(for: note.objectID)
340 let busyTag = try await libraryItem("tags", id: tagID)
341 let blocked = try await client.callTool(name: "delete_tag", arguments: ["id": tagID, "expected_revision": .string(busyTag["revision"] as! String)])
342 try expect(blocked.isError == true, "Deleting a tag changed an actively generated note")
343 store.endNoteOperation(lease: operation)
344 let templates = try json(await client.callTool(name: "list_summary_templates", arguments: [:]))
345 try expect((templates["templates"] as? [[String: Any]])?.count == LocalSummaryTemplate.allCases.count, "Native summary templates missing")
346 let custom = try json(await client.callTool(name: "create_summary_template", arguments: ["name": "MCP fixture \(UUID())", "instructions": "Only include decisions and action items."]))
347 let templateID = Value.string(custom["id"] as! String)
348 let templateRevision = Value.string(custom["revision"] as! String)
349 let templateKey = Value.string(custom["key"] as! String)
350 service.setAllowsWriting(false)
351 let readonlyTemplate = try await client.callTool(name: "delete_summary_template", arguments: ["id": templateID, "expected_revision": templateRevision])
352 try expect(readonlyTemplate.isError == true, "Read-only MCP deleted a template")
353 service.setAllowsWriting(true)
354 let editedTemplate = try json(await client.callTool(name: "update_summary_template", arguments: ["id": templateID, "expected_revision": templateRevision, "name": "Edited \(UUID())", "instructions": "Use Next Steps with owners and dates."]))
355 let staleTemplate = try await client.callTool(name: "delete_summary_template", arguments: ["id": templateID, "expected_revision": templateRevision])
356 try expect(staleTemplate.isError == true, "Stale template deletion was accepted")
357 JotleyMCPTools.summaryGeneratorForTesting = { _, template, _ in
358 try expect(template.key == templateKey.stringValue && template.prompt == "Use Next Steps with owners and dates.", "Custom template instructions did not reach native generation")
359 return "## Next Steps\n- Review launch."
360 }
361 _ = try json(await client.callTool(name: "generate_note_summary", arguments: ["id": id, "expected_revision": try await revision(id), "template": templateKey]))
362 try expect(note.text("summaryType") == templateKey.stringValue, "Custom template key was not saved")
363 _ = try json(await client.callTool(name: "delete_summary_template", arguments: ["id": templateID, "expected_revision": .string(editedTemplate["revision"] as! String)]))
364 try expect(note.text("summary") == "## Next Steps\n- Review launch.", "Deleting a template modified a saved summary")
365 let missingTemplate = try await client.callTool(name: "generate_note_summary", arguments: ["id": id, "expected_revision": try await revision(id), "template": templateKey])
366 try expect(missingTemplate.isError == true, "Deleted template silently fell back to Auto")
367 print("PASS: custom template MCP CRUD, read-only enforcement, revision conflicts, native generation and summary-preserving deletion")
368 JotleyMCPTools.summaryGeneratorForTesting = { _, _, _ in "- [ ] Review launch." }
369 defer { JotleyMCPTools.summaryGeneratorForTesting = nil }
370 let generated = try json(await client.callTool(name: "generate_note_summary", arguments: ["id": id, "expected_revision": try await revision(id), "template": .string(LocalSummaryTemplate.auto.key)]))
371 try expect(generated["title"] as? String == "Organization fixture" && note.text("summary") == "- [ ] Review launch." && note.text("transcription") == "Maya will review the launch.", "Native summary generation changed unrelated fields")
372 JotleyMCPTools.summaryGeneratorForTesting = { _, _, _ in
373 service.setAllowsWriting(false)
374 return "Must not save"
375 }
376 let revoked = try await client.callTool(name: "generate_note_summary", arguments: ["id": id, "expected_revision": try await revision(id), "template": .string(LocalSummaryTemplate.auto.key)])
377 try expect(revoked.isError == true && note.text("summary") == "- [ ] Review launch.", "Permission revocation during native generation still wrote content")
378 service.setAllowsWriting(true)
379 let finalFolder = try await libraryItem("folders", id: folderID)
380 _ = try json(await client.callTool(name: "delete_folder", arguments: ["id": folderID, "expected_revision": .string(finalFolder["revision"] as! String)]))
381 let finalTag = try await libraryItem("tags", id: tagID)
382 _ = try json(await client.callTool(name: "delete_tag", arguments: ["id": tagID, "expected_revision": .string(finalTag["revision"] as! String)]))
383 let preserved = try await read(id)
384 try expect(preserved["folder"] as? String == "" && (preserved["tags"] as? [String])?.isEmpty == true && note.text("summary") == "- [ ] Review launch.", "Organization deletion deleted or altered note content")
385 _ = try json(await client.callTool(name: "delete_note", arguments: ["id": id, "expected_revision": try await revision(id)]))
386 service.setAllowsWriting(false)
387 print("PASS: tag/folder CRUD, membership, combined filters, stale revisions, processing protection, native regeneration and in-flight permission revocation; organization deletion preserves notes")
388 }
389
390 @MainActor static func writeChecks(client: Client, service: JotleyMCPService, store: SharedPersistenceController, noteID: Value) async throws {
391 func json(_ result: (content: [Tool.Content], isError: Bool?)) throws -> [String: Any] {
392 try expect(result.isError != true, "Tool failed: \(text(result.content))")
393 return try JSONSerialization.jsonObject(with: Data(text(result.content).utf8)) as! [String: Any]
394 }
395 func read(_ id: Value) async throws -> [String: Any] { try json(await client.callTool(name: "read_note", arguments: ["id": id])) }
396 func revision(_ id: Value) async throws -> Value { .string(try await read(id)["revision"] as! String) }
397 let initial = try await read(noteID)
398 let originalRevision = Value.string(initial["revision"] as! String)
399 for name in ["create_note", "update_note", "replace_note_text", "duplicate_note", "delete_note"] {
400 let arguments: [String: Value]
401 switch name {
402 case "create_note": arguments = ["title": "Blocked"]
403 case "update_note": arguments = ["id": noteID, "expected_revision": originalRevision, "changes": ["title": "Blocked"]]
404 case "replace_note_text": arguments = ["id": noteID, "expected_revision": originalRevision, "field": "summary", "old_text": "Maya", "new_text": "Blocked"]
405 default: arguments = ["id": noteID, "expected_revision": originalRevision]
406 }
407 let denied = try await client.callTool(name: name, arguments: arguments)
408 try expect(denied.isError == true && text(denied.content).contains("read only"), "Read-only access allowed \(name)")
409 }
410 service.setAllowsWriting(true)
411 let updated = try json(await client.callTool(name: "update_note", arguments: [
412 "id": noteID, "expected_revision": originalRevision, "changes": [
413 "title": "Release checklist", "summary": "- Review onboarding\n- Test accessibility",
414 "description": "Launch review", "notes": "Meet Thursday", "date": "2026-11-08T10:30:00.123Z",
415 "cleaned_transcript": "Clean copy", "source_url": "https://example.com/release", "summary_type": "checklist"
416 ]]))
417 try expect(updated["title"] as? String == "Release checklist" && updated["date"] as? String == "2026-11-08T10:30:00.123Z", "Title/date update failed")
418 try expect(updated["tags"] as? [String] == ["launch"], "Update changed tags")
419 let note = try store.notes().first { $0.localNoteID?.uuidString == noteID.stringValue }!
420 try expect(note.text("transcription").contains("Maya owns") && note.text("sourceDescription") == "Launch review", "Patch overwrote an unrelated field")
421 let stale = try await client.callTool(name: "update_note", arguments: ["id": noteID, "expected_revision": originalRevision, "changes": ["title": "Stale"]])
422 try expect(stale.isError == true && text(stale.content).contains("Revision conflict"), "A stale revision overwrote a change")
423
424 for changes: Value in [["title": "Partial", "date": "yesterday"], ["title": "Partial", "summary": 42], ["title": "Partial", "settings": true], [:]] {
425 let invalid = try await client.callTool(name: "update_note", arguments: ["id": noteID, "expected_revision": try await revision(noteID), "changes": changes])
426 try expect(invalid.isError == true && note.text("title") == "Release checklist", "Invalid changes were partially saved")
427 }
428 let missingRevision = try await client.callTool(name: "delete_note", arguments: ["id": noteID])
429 try expect(missingRevision.isError == true && !note.isDeleted, "Deletion did not require a revision")
430
431 let recording = try store.beginRecording(note)
432 let recordingWrite = try await client.callTool(name: "delete_note", arguments: ["id": noteID, "expected_revision": try await revision(noteID)])
433 try expect(recordingWrite.isError == true && text(recordingWrite.content).contains("recording"), "MCP deleted an active recording")
434 store.endRecording(lease: recording)
435 let generationModel = NotesListViewModel(viewContext: store.context, recorder: ProcessTapRecorder(), persistenceController: store)
436 generationModel.beginSummaryGeneration(for: note.objectID)
437 let generationWrite = try await client.callTool(name: "update_note", arguments: ["id": noteID, "expected_revision": try await revision(noteID), "changes": ["summary": "Unsafe"]])
438 try expect(generationWrite.isError == true && text(generationWrite.content).contains("generating"), "MCP raced generation")
439 generationModel.endSummaryGeneration(for: note.objectID)
440
441 // Exercise a native editor's conflict check against an MCP write.
442 let nativeNote = note as! Note
443 let oldSummary = nativeNote.summary ?? ""
444 let replaced = try json(await client.callTool(name: "replace_note_text", arguments: ["id": noteID, "expected_revision": try await revision(noteID), "field": "summary", "old_text": "Review onboarding", "new_text": "Approve onboarding"]))
445 try expect(replaced["revision"] as? String != updated["revision"] as? String, "Revision did not change")
446 do {
447 try nativeNote.saveEditedSummary("Old editor draft", original: oldSummary, in: store)
448 throw LocalError.message("An old native editor draft overwrote MCP content")
449 } catch let error as LocalError { try expect(error.localizedDescription.contains("changed while"), error.localizedDescription) }
450
451 _ = try json(await client.callTool(name: "update_note", arguments: ["id": noteID, "expected_revision": try await revision(noteID), "changes": ["transcript": "New transcript. Second sentence."]]))
452 try expect(nativeNote.transcriptUtterances.map(\.text).joined(separator: " ").contains("New transcript"), "Transcript timing metadata is stale")
453
454 // A native correction must keep timing, line breaks and metadata after reload.
455 let timedNote = try store.create(title: "Timestamp editor fixture", text: "Review the disign. Ship on Friday.") as! Note
456 let timed = [TranscriptUtterance(id: "review", text: "Review the disign.", start: 0, end: 4, speaker: 1),
457 TranscriptUtterance(id: "ship", text: "Ship on Friday.", start: 18, end: 22, speaker: 2)]
458 try store.saveNoteChanges(timedNote, values: ["transcriptUtterancesJSON": String(decoding: try JSONEncoder().encode(timed), as: UTF8.self)])
459 var edit = TranscriptEditDraft(text: timedNote.transcription!, utterances: timedNote.storedTranscriptUtterances)
460 edit.segments[0].text = "Review the design.\nKeep our branding."
461 try timedNote.saveEditedTranscript(edit, in: store)
462 store.context.refresh(timedNote, mergeChanges: false)
463 try expect(timedNote.transcription == "Review the design.\nKeep our branding.\n\nShip on Friday.", "Native correction flattened paragraph breaks")
464 try expect(timedNote.storedTranscriptUtterances.map(\.start) == [0, 18], "Native correction erased timestamp anchors")
465 try expect(timedNote.transcriptUtterances.map(\.timestampLabel) == ["00:00", "00:18"], "Saved bubbles lost timestamps")
466 var staleEdit = TranscriptEditDraft(text: timedNote.transcription!, utterances: timedNote.storedTranscriptUtterances)
467 staleEdit.segments[1].text = "Stale correction."
468 var updatedTiming = timedNote.storedTranscriptUtterances
469 updatedTiming[1] = TranscriptUtterance(id: "ship", text: "Ship on Friday.", start: 20, end: 24, speaker: 2)
470 try store.saveNoteChanges(timedNote, values: ["transcriptUtterancesJSON": String(decoding: try JSONEncoder().encode(updatedTiming), as: UTF8.self)])
471 do {
472 try timedNote.saveEditedTranscript(staleEdit, in: store)
473 throw LocalError.message("Stale transcript editor overwrote newer timing")
474 } catch let error as LocalError { try expect(error.localizedDescription.contains("changed while"), error.localizedDescription) }
475 print("PASS: native transcript correction, reload, line breaks, timestamps and timing conflict guard")
476
477 let created = try json(await client.callTool(name: "create_note", arguments: ["title": "Agent draft", "transcript": .string(String(repeating: "Long note. ", count: 10000)), "description": "Created through MCP"]))
478 let createdID = Value.string(created["id"] as! String)
479 let longRead = try json(await client.callTool(name: "read_note", arguments: ["id": createdID, "section": "transcript", "offset": 100000]))
480 try expect(longRead["total_characters"] as? Int == 110000, "Long note failed beyond the old request limit")
481 _ = try json(await client.callTool(name: "update_note", arguments: ["id": createdID, "expected_revision": try await revision(createdID), "changes": ["transcript": "aaa"]]))
482 let ambiguous = try await client.callTool(name: "replace_note_text", arguments: ["id": createdID, "expected_revision": try await revision(createdID), "field": "transcript", "old_text": "aa", "new_text": "b"])
483 let unchanged = try json(await client.callTool(name: "read_note", arguments: ["id": createdID, "section": "transcript"]))
484 try expect(ambiguous.isError == true && unchanged["content"] as? String == "aaa", "Overlapping matches were not rejected without changes")
485 let folder = NSEntityDescription.insertNewObject(forEntityName: "Folder", into: store.context)
486 folder.setValue(UUID(), forKey: "id"); folder.setValue("Work", forKey: "name")
487 note.setValue(folder, forKey: "folder")
488 try store.save()
489 let copy = try json(await client.callTool(name: "duplicate_note", arguments: ["id": noteID, "expected_revision": try await revision(noteID), "title": "Release copy"]))
490 let copyID = Value.string(copy["id"] as! String)
491 try expect(copyID != noteID && copy["tags"] as? [String] == ["launch"] && copy["folder"] as? String == "Work", "Copy identity/folder/tags failed")
492 _ = try json(await client.callTool(name: "update_note", arguments: ["id": copyID, "expected_revision": try await revision(copyID), "changes": ["title": "Independent copy"]]))
493 try expect(note.text("title") == "Release checklist", "Editing the copy changed its source")
494
495 for entity in ["NoteChatMessage", "RecordingMarker"] {
496 let child = NSEntityDescription.insertNewObject(forEntityName: entity, into: store.context)
497 child.setValue(UUID(), forKey: "id"); child.setValue(UUID(uuidString: copyID.stringValue!)!, forKey: "noteId")
498 }
499 try store.save()
500 for id in [createdID, copyID] {
501 let deleted = try json(await client.callTool(name: "delete_note", arguments: ["id": id, "expected_revision": try await revision(id)]))
502 try expect(deleted["deleted"] as? Bool == true, "Deletion failed")
503 }
504 for entity in ["NoteChatMessage", "RecordingMarker"] {
505 let request = NSFetchRequest<NSManagedObject>(entityName: entity)
506 let count = try store.context.count(for: request)
507 try expect(count == 0, "Deletion left orphaned \(entity)")
508 }
509 service.setAllowsWriting(false)
510 let revoked = try await client.callTool(name: "update_note", arguments: ["id": noteID, "expected_revision": try await revision(noteID), "changes": ["title": "Revoked"]])
511 try expect(revoked.isError == true, "Permission downgrade did not affect an existing client")
512 // Restore search fixtures for subsequent concurrent-client checks.
513 try store.saveNoteChanges(note, values: ["title": "Release planning", "transcription": "Maya owns the onboarding review on Friday."])
514 print("PASS: read/write permission, atomic edits, dates, stale revisions, active recording/generation, native editor conflicts, long notes, independent copies, deletion and live permission revocation")
515 }
516}