Branchwell

PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / PulseCanvasMCP.swift

1#if os(macOS) && DIRECT_BUILD && !STORE_BUILD
2import CoreFoundation
3import Darwin
4import Foundation
5
6struct PulseMCPError: LocalizedError {
7 let code: String
8 let message: String
9 init(_ code: String, _ message: String) { self.code = code; self.message = message }
10 var errorDescription: String? { message }
11 var payload: [String: Any] { ["code": code, "message": message] }
12}
13
14enum PulseMCP {
15 typealias Object = [String: Any]
16 static let argument = "--mcp"
17 static let maxMessage = 2_000_000
18 private static let versions = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
19
20 struct Tool {
21 let name: String
22 let description: String
23 let input: Object
24 let output: Object
25 let permission: String?
26 var schema: Object {
27 ["name": name, "description": description, "inputSchema": input, "outputSchema": output,
28 "annotations": ["readOnlyHint": permission == nil]]
29 }
30 }
31
32 static func object(_ properties: Object, required: [String] = [], open: Bool = false) -> Object {
33 ["type": "object", "properties": properties, "required": required, "additionalProperties": open]
34 }
35
36 static func text(_ values: [String]? = nil, limit: Int = 4096) -> Object {
37 var schema: Object = ["type": "string", "minLength": 1, "maxLength": limit]
38 if let values { schema["enum"] = values }
39 return schema
40 }
41 static func number(_ min: Double, _ max: Double, integer: Bool = false) -> Object {
42 ["type": integer ? "integer" : "number", "minimum": min, "maximum": max]
43 }
44 static func array(_ items: Object, max: Int = 10_000) -> Object {
45 ["type": "array", "items": items, "maxItems": max]
46 }
47 static let boolean = ["type": "boolean"]
48 static let resolutions = [720, 1080, 2160]
49 static let aspectNames = ["wide", "landscape", "portrait", "phone", "square"]
50 static var format: Object {
51 ["aspect": text(aspectNames), "resolution": ["type": "integer", "enum": resolutions],
52 "fps": ["type": "integer", "enum": [24, 30, 60]]]
53 }
54 static let id = text(limit: 256)
55 static let path = text()
56 static let revision = text(limit: 64)
57 static let requestKey = text(limit: 128)
58 static let seconds = number(0, 86_400)
59 static let bars = number(1, 128, integer: true)
60 static let timelineEntry = object(
61 ["visualizerId": id, "startSeconds": seconds, "endSeconds": seconds, "bars": bars],
62 required: ["visualizerId", "startSeconds", "endSeconds"])
63 static let playback = object(
64 ["ready": boolean, "playing": boolean, "positionSeconds": seconds, "durationSeconds": seconds,
65 "volume": number(0, 1), "mode": text(["studio", "radio"]), "title": text(), "revision": revision],
66 required: ["ready", "playing", "positionSeconds", "durationSeconds", "volume", "mode", "title", "revision"])
67 static let visualizer = object(
68 ["id": id, "name": text(), "category": text(), "engine": text(["metal", "projectM"]),
69 "available": boolean, "favorite": boolean, "settings": ["type": "object"], "controls": ["type": "object"]],
70 required: ["id", "name", "category", "engine", "available", "favorite"])
71 static let project = object(
72 ["id": id, "revision": revision, "soundtrackPath": path, "durationSeconds": seconds, "seed": id,
73 "barsPerScene": bars, "visualizerId": id, "timeline": array(timelineEntry),
74 "exportSettings": object(format.merging(["fps": ["type": "integer", "enum": [24, 30, 60, 120]]]) { _, actual in actual }, required: ["aspect", "resolution", "fps"]), "studioEnabled": boolean],
75 required: ["revision", "durationSeconds", "visualizerId", "timeline", "exportSettings", "studioEnabled"])
76 static let job = object(
77 ["id": id, "phase": text(["queued", "preparing", "rendering", "muxing", "validating", "completed", "failed", "cancelled"]),
78 "progress": number(0, 1), "framesRendered": ["type": "integer"], "totalFrames": ["type": "integer"],
79 "etaSeconds": ["type": "number"], "destination": path, "projectPath": path, "manifestPath": path,
80 "previewOnly": boolean, "error": object(["code": text(), "message": text()], required: ["code", "message"]),
81 "artifact": object(["path": path, "durationSeconds": seconds, "width": ["type": "integer"],
82 "height": ["type": "integer"], "fps": ["type": "number"], "expectedFrames": ["type": "integer"],
83 "videoCodec": text(), "audioCodec": text(), "bytes": ["type": "integer"]],
84 required: ["path", "durationSeconds", "width", "height", "fps", "expectedFrames", "videoCodec", "audioCodec", "bytes"])],
85 required: ["id", "phase", "progress", "framesRendered", "totalFrames", "destination", "previewOnly"])
86 static let visualRanges: [String: ClosedRange<Double>] = [
87 "speed": 0.05...3, "zoomSpeed": 0...3, "chaos": 0...1, "brightness": 0.1...3,
88 "liquidDetail": 0...1, "particleSize": 0.3...6, "fog": 0...1, "zoom": 0.3...2,
89 "rotation": -3.14...3.14, "motionBlur": 0...0.9, "strobeSensitivity": 0.25...4,
90 "strobeStrength": 0.1...1, "haloCount": 1...12, "palette": 0...4
91 ]
92 static let controlProperties: Object = {
93 var properties: Object = visualRanges.mapValues { number($0.lowerBound, $0.upperBound) }
94 for key in ["haloCount", "palette"] {
95 let range = visualRanges[key]!
96 properties[key] = number(range.lowerBound, range.upperBound, integer: true)
97 }
98 properties["strobeEnabled"] = boolean
99 return properties
100 }()
101
102 static let tools: [Tool] = {
103 func tool(_ name: String, _ description: String, _ input: Object = [:], _ required: [String] = [],
104 output: Object, permission: String? = nil) -> Tool {
105 Tool(name: name, description: description, input: object(input, required: required), output: output, permission: permission)
106 }
107 let jobResult = object(["job": job], required: ["job"])
108 let kind = text(["visualizer", "radioSong"])
109 let projectChange = ["expectedRevision": revision]
110 let start = format.merging(["path": path, "expectedRevision": revision, "requestKey": requestKey,
111 "overwrite": boolean, "previewSeconds": number(0.5, 30)]) { first, _ in first }
112 let generate = format.merging(["songPath": path, "projectPath": path, "outputPath": path, "barsPerScene": bars,
113 "expectedRevision": revision, "requestKey": requestKey, "seed": id,
114 "fallback": text(["metal", "available", "error"]), "visualizerIds": array(id, max: 500),
115 "strobeEnabled": boolean, "previewOnly": boolean,
116 "previewSeconds": number(0.5, 30)]) { first, _ in first }
117 return [
118 tool("get_app_status", "Check whether the Mac app is running and agent access is enabled.",
119 output: object(["running": boolean, "enabled": boolean, "edition": text(), "version": text(),
120 "playback": boolean, "editing": boolean, "rendering": boolean, "pendingExports": ["type": "integer"]],
121 required: ["running", "enabled", "edition", "version", "playback", "editing", "rendering", "pendingExports"])),
122 tool("get_capabilities", "Read current permissions, supported export formats, and effect controls.",
123 output: object(["edition": text(), "resolutions": array(["type": "integer"]), "frameRates": array(["type": "integer"]),
124 "aspects": array(text()), "engines": array(text()), "inputFolder": path, "outputFolder": path,
125 "videoCodec": text(), "audioCodec": text(), "controls": ["type": "object"], "maxPendingExports": ["type": "integer"]],
126 required: ["edition", "resolutions", "frameRates", "aspects", "engines", "videoCodec", "audioCodec", "controls", "maxPendingExports"])),
127 tool("list_visualizers", "Find installed effects by stable ID, name, category, engine or favorite state.",
128 ["query": text(limit: 256), "engine": text(["metal", "projectM"]), "category": text(limit: 256),
129 "favoritesOnly": boolean, "offset": number(0, 100_000, integer: true), "limit": number(1, 200, integer: true)],
130 output: object(["visualizers": array(visualizer, max: 200), "total": ["type": "integer"], "nextOffset": ["type": "integer"]],
131 required: ["visualizers", "total"])),
132 tool("get_visualizer", "Read one installed visualizer and its saved appearance.", ["id": id], ["id"], output: visualizer),
133 tool("list_favorites", "List saved visualizers or radio songs by stable ID.", ["kind": kind], ["kind"],
134 output: object(["kind": kind, "favorites": array(["type": "object"])], required: ["kind", "favorites"])),
135 tool("list_radio_songs", "List tracks in the current or configured Radio catalog without starting playback.",
136 ["offset": number(0, 500, integer: true), "limit": number(1, 200, integer: true)],
137 output: object(["songs": array(["type": "object"], max: 200), "total": ["type": "integer"], "nextOffset": ["type": "integer"]],
138 required: ["songs", "total"])),
139 tool("set_favorite", "Set or remove a saved favorite explicitly. Repeating the same request preserves the current saved look.",
140 ["kind": kind, "id": id, "favorite": boolean], ["kind", "id", "favorite"],
141 output: object(["kind": kind, "id": id, "favorite": boolean], required: ["kind", "id", "favorite"]), permission: "editing"),
142 tool("load_song", "Prepare an existing local song and select it for Studio.",
143 ["path": path, "expectedRevision": revision], ["path", "expectedRevision"], output: playback, permission: "playback"),
144 tool("get_playback_state", "Read the current transport position in seconds, duration, volume, and project revision.", output: playback),
145 tool("set_playback_state", "Play, pause, or stop explicitly.",
146 ["state": text(["play", "pause", "stop"])], ["state"], output: playback, permission: "playback"),
147 tool("seek", "Seek Studio audio to a position in seconds.", ["seconds": seconds], ["seconds"], output: playback, permission: "playback"),
148 tool("set_volume", "Set transport volume from zero to one.", ["volume": number(0, 1)], ["volume"], output: playback, permission: "playback"),
149 tool("get_project", "Read the editable Studio project and concurrency revision.", output: project),
150 tool("create_project", "Start a new editable project using the loaded song and current visualizer.",
151 projectChange.merging(["barsPerScene": bars]) { first, _ in first }, ["expectedRevision"], output: project, permission: "editing"),
152 tool("open_project", "Open an existing PulseCanvas project and its authorized soundtrack.",
153 ["path": path, "expectedRevision": revision], ["path", "expectedRevision"], output: project, permission: "editing"),
154 tool("save_project", "Save the editable project to an authorized .pulsecanvas path.",
155 ["path": path, "overwrite": boolean, "expectedRevision": revision, "requestKey": requestKey],
156 ["path", "expectedRevision", "requestKey"], output: object(["path": path, "project": project], required: ["path", "project"]),
157 permission: "editing"),
158 tool("analyze_song", "Read detected BPM and beat or bar grid boundaries on the loaded song.",
159 ["beatsPerSection": number(1, 512, integer: true)], output: object(
160 ["bpm": ["type": "number"], "boundariesSeconds": array(seconds, max: 500_000)],
161 required: ["boundariesSeconds"])),
162 tool("set_timeline", "Replace the entire contiguous full-song timeline using stable visualizer IDs.",
163 ["segments": array(timelineEntry), "expectedRevision": revision], ["segments", "expectedRevision"],
164 output: project, permission: "editing"),
165 tool("set_visualizer", "Select a visualizer in the editor, or assign it to an existing timeline section.",
166 ["id": id, "expectedRevision": revision, "section": number(0, 9999, integer: true)], ["id", "expectedRevision"],
167 output: project, permission: "editing"),
168 tool("set_visualizer_settings", "Update applicable appearance controls for an installed visualizer.",
169 ["id": id, "settings": object(controlProperties), "expectedRevision": revision], ["id", "settings", "expectedRevision"],
170 output: project, permission: "editing"),
171 tool("start_export", "Queue a full-song MP4 using a snapshot of the current Studio project.", start,
172 ["path", "expectedRevision", "requestKey"], output: jobResult, permission: "rendering"),
173 tool("render_preview", "Queue a short MP4 using the same renderer and settings as the full export.", start,
174 ["path", "expectedRevision", "requestKey"], output: jobResult, permission: "rendering"),
175 tool("get_export_status", "Read an export's progress, failure, or validated media artifact.", ["id": id], ["id"], output: jobResult),
176 tool("list_exports", "Read current and recent retained export jobs.", ["limit": number(1, 100, integer: true)],
177 output: object(["jobs": array(job, max: 100)], required: ["jobs"])),
178 tool("cancel_export", "Cancel a queued or running export by its durable job ID.", ["id": id], ["id"], output: jobResult, permission: "rendering"),
179 tool("create_music_video", "Analyze an authorized song, save a beat-aligned project, and queue an export. Explicit fallback and strobe choices are required.",
180 generate, ["songPath", "projectPath", "outputPath", "fallback", "strobeEnabled", "expectedRevision", "requestKey"],
181 output: object(["projectPath": path, "project": project, "job": job, "usedFallback": boolean],
182 required: ["projectPath", "project", "job", "usedFallback"]), permission: "rendering")
183 ]
184 }()
185
186 static func valid(_ value: Any, schema: Object) -> Bool {
187 switch schema["type"] as? String {
188 case "object":
189 guard let dictionary = value as? Object else { return false }
190 let fields = schema["properties"] as? [String: Object] ?? [:]
191 if let required = schema["required"] as? [String], !required.allSatisfy({ dictionary[$0] != nil }) { return false }
192 return dictionary.allSatisfy { key, value in
193 fields[key].map { valid(value, schema: $0) } ?? (schema["additionalProperties"] as? Bool != false)
194 }
195 case "array":
196 guard let array = value as? [Any], let items = schema["items"] as? Object,
197 array.count <= (schema["maxItems"] as? Int ?? Int.max) else { return false }
198 return array.allSatisfy { valid($0, schema: items) }
199 case "string":
200 guard let string = value as? String, string.count >= (schema["minLength"] as? Int ?? 0),
201 string.count <= (schema["maxLength"] as? Int ?? Int.max),
202 !string.utf8.contains(0) else { return false }
203 return (schema["enum"] as? [String])?.contains(string) ?? true
204 case "boolean":
205 return (value as? NSNumber).map { CFGetTypeID($0) == CFBooleanGetTypeID() } ?? false
206 case "number", "integer":
207 guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return false }
208 let amount = number.doubleValue
209 guard amount.isFinite, amount >= (schema["minimum"] as? Double ?? -.infinity),
210 amount <= (schema["maximum"] as? Double ?? .infinity),
211 schema["type"] as? String != "integer" || amount.rounded() == amount else { return false }
212 return (schema["enum"] as? [Int])?.contains(number.intValue) ?? true
213 default: return false
214 }
215 }
216
217 static func run() {
218 var initialized = false
219 while let line = readLine(strippingNewline: true) {
220 guard line.utf8.count <= maxMessage,
221 let message = (try? JSONSerialization.jsonObject(with: Data(line.utf8))) as? Object else {
222 send(["jsonrpc": "2.0", "id": NSNull(), "error": ["code": -32700, "message": "Invalid JSON-RPC message"]])
223 continue
224 }
225 let id = message["id"] ?? NSNull()
226 func respond(_ result: Object) { send(["jsonrpc": "2.0", "id": id, "result": result]) }
227 func error(_ code: Int, _ reason: String) { send(["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": reason]]) }
228 guard message["jsonrpc"] as? String == "2.0", let method = message["method"] as? String else {
229 error(-32600, "Invalid request"); continue
230 }
231 guard message["id"] != nil else { continue }
232 let params = message["params"] as? Object ?? [:]
233 switch method {
234 case "initialize":
235 guard !initialized, let version = params["protocolVersion"] as? String else {
236 error(-32602, "Expected one initialize request with a protocol version"); continue
237 }
238 initialized = true
239 respond(["protocolVersion": versions.contains(version) ? version : versions[0],
240 "capabilities": ["tools": ["listChanged": false]],
241 "serverInfo": ["name": "pulsecanvas", "title": "PulseCanvas Studio",
242 "version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "development"],
243 "instructions": "Open PulseCanvas Studio on this Mac and enable Settings → Agent access. Read get_app_status and get_capabilities before changing data."])
244 case "ping": respond([:])
245 case "tools/list" where initialized: respond(["tools": tools.map(\.schema)])
246 case "tools/call" where initialized:
247 guard let name = params["name"] as? String, let tool = tools.first(where: { $0.name == name }) else {
248 error(-32602, "Unknown PulseCanvas tool"); continue
249 }
250 let arguments = params["arguments"] ?? Object()
251 guard let args = arguments as? Object, valid(args, schema: tool.input) else {
252 error(-32602, "Arguments do not match the tool input schema"); continue
253 }
254 let result = PulseMCPMailbox.call(name, args)
255 if let failure = result["error"] as? Object {
256 respond(["isError": true, "content": [["type": "text", "text": jsonText(failure)]]])
257 } else if let value = result["value"] as? Object, valid(value, schema: tool.output) {
258 respond(["structuredContent": value, "content": [["type": "text", "text": jsonText(value)]]])
259 } else {
260 respond(["isError": true, "content": [["type": "text", "text": "INVALID_RESPONSE: PulseCanvas returned unexpected data."]]])
261 }
262 default: error(-32601, "Method not available")
263 }
264 }
265 }
266
267 static func jsonText(_ object: Object) -> String {
268 guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes]) else { return "{}" }
269 return String(decoding: data, as: UTF8.self)
270 }
271 private static func send(_ object: Object) {
272 FileHandle.standardOutput.write(Data((jsonText(object) + "\n").utf8))
273 }
274}
275
276/// Both processes are the app's executable. A per-user directory lets the sandboxed
277/// build use the same local transport without network server entitlements.
278enum PulseMCPMailbox {
279 typealias Object = PulseMCP.Object
280 static var configuredRoot: URL {
281 UserDataStorage.defaultSupport.appendingPathComponent("AgentConnection", isDirectory: true)
282 }
283 private static let unavailable = PulseMCPError("APP_UNAVAILABLE", "Open PulseCanvas Studio on this Mac, then retry.")
284 private static let lifetime: TimeInterval = 180
285
286 static func root() throws -> URL {
287 let directory = configuredRoot
288 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true,
289 attributes: [.posixPermissions: 0o700])
290 var info = stat()
291 guard lstat(directory.path, &info) == 0, info.st_uid == geteuid(),
292 info.st_mode & S_IFMT == S_IFDIR, info.st_mode & 0o077 == 0 else {
293 throw PulseMCPError("CONNECTION_DIRECTORY", "PulseCanvas needs a private AgentConnection directory.")
294 }
295 return directory
296 }
297
298 static func lock(_ root: URL) throws -> Int32 {
299 let fd = Darwin.open(root.appendingPathComponent("host.lock").path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)
300 guard fd >= 0 else { throw unavailable }
301 return fd
302 }
303
304 static func call(_ name: String, _ arguments: Object) -> Object {
305 do {
306 let root = try root()
307 let fd = try lock(root)
308 defer { close(fd) }
309 func hostIsRunning() -> Bool {
310 if flock(fd, LOCK_EX | LOCK_NB) == 0 { flock(fd, LOCK_UN); return false }
311 return errno == EWOULDBLOCK
312 }
313 guard hostIsRunning() else {
314 if name == "get_app_status" { return ["value": PulseMCPAccess.offlineStatus] }
315 throw unavailable
316 }
317 let id = UUID().uuidString
318 let request = root.appendingPathComponent(id + ".request")
319 let response = root.appendingPathComponent(id + ".response")
320 let deadline = Date().addingTimeInterval(lifetime)
321 let message: Object = ["name": name, "arguments": arguments, "deadline": deadline.timeIntervalSince1970]
322 let data = try JSONSerialization.data(withJSONObject: message)
323 guard data.count <= PulseMCP.maxMessage else {
324 throw PulseMCPError("INVALID_ARGUMENTS", "Tool arguments exceed the size limit.")
325 }
326 try data.write(to: request, options: .atomic)
327 defer {
328 try? FileManager.default.removeItem(at: request)
329 try? FileManager.default.removeItem(at: response)
330 }
331 while deadline.timeIntervalSinceNow > 0 {
332 if let data = try? Data(contentsOf: response), let result = try? JSONSerialization.jsonObject(with: data) as? Object {
333 return result
334 }
335 guard hostIsRunning() else { throw unavailable }
336 Thread.sleep(forTimeInterval: 0.05)
337 }
338 throw PulseMCPError("CONNECTION_TIMEOUT", "PulseCanvas did not reply. Reuse the same request key when retrying an operation that writes a file.")
339 } catch let error as PulseMCPError { return ["error": error.payload] }
340 catch { return ["error": unavailable.payload] }
341 }
342
343 @MainActor
344 final class Host {
345 private var timer: Timer?
346 private var fd: Int32 = -1
347 private var directory: URL?
348 private var inFlight = Set<UUID>()
349 private var lastSweep = Date.distantPast
350
351 func start(handler: @escaping @MainActor (String, Object) async -> Object) {
352 guard timer == nil else { return }
353 do {
354 let directory = try root()
355 let fd = try lock(directory)
356 guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
357 close(fd)
358 return
359 }
360 self.fd = fd
361 self.directory = directory
362 let timer = Timer(timeInterval: 0.125, repeats: true) { [weak self] _ in
363 MainActor.assumeIsolated { self?.consume(handler) }
364 }
365 self.timer = timer
366 RunLoop.main.add(timer, forMode: .common)
367 } catch {
368 NSLog("PulseCanvas could not open its local agent connection.")
369 }
370 }
371
372 var isRunning: Bool { fd >= 0 }
373
374 private func consume(_ handler: @escaping @MainActor (String, Object) async -> Object) {
375 guard inFlight.count < 16, let directory,
376 let files = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isRegularFileKey, .contentModificationDateKey, .fileSizeKey], options: [.skipsHiddenFiles])
377 else { return }
378 let now = Date()
379 let sweep = now.timeIntervalSince(lastSweep) > 60
380 if sweep { lastSweep = now }
381 for file in files {
382 guard let id = UUID(uuidString: file.deletingPathExtension().lastPathComponent), !inFlight.contains(id),
383 let properties = try? file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .contentModificationDateKey, .fileSizeKey]),
384 properties.isRegularFile == true, properties.isSymbolicLink != true else { continue }
385 if sweep, let date = properties.contentModificationDate, now.timeIntervalSince(date) > lifetime + 10 {
386 if ["request", "response"].contains(file.pathExtension) { try? FileManager.default.removeItem(at: file) }
387 continue
388 }
389 guard file.pathExtension == "request", inFlight.count < 16,
390 (properties.fileSize ?? Int.max) <= PulseMCP.maxMessage,
391 let data = try? Data(contentsOf: file), let message = try? JSONSerialization.jsonObject(with: data) as? Object,
392 let name = message["name"] as? String, let args = message["arguments"] as? Object,
393 let deadline = message["deadline"] as? Double,
394 deadline > now.timeIntervalSince1970, deadline <= now.timeIntervalSince1970 + lifetime
395 else { continue }
396 inFlight.insert(id)
397 Task {
398 let result = await handler(name, args)
399 defer { inFlight.remove(id) }
400 guard Date().timeIntervalSince1970 < deadline, FileManager.default.fileExists(atPath: file.path),
401 let response = try? JSONSerialization.data(withJSONObject: result) else { return }
402 let target = file.deletingPathExtension().appendingPathExtension("response")
403 // The bridge owns its request until it has read the reply. Keep
404 // this ID claimed until the request is removed by that bridge.
405 try? response.write(to: target, options: .atomic)
406 try? FileManager.default.removeItem(at: file)
407 }
408 }
409 }
410
411 deinit { timer?.invalidate(); if fd >= 0 { close(fd) } }
412 }
413}
414#endif