Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / AgentConnectionCheck.swift

1import Darwin
2import Foundation
3
4enum AgentConnectionCheck {
5 struct Result: Equatable {
6 let toolCount: Int
7 let projectCount: Int
8 }
9
10 static func run(command: String, workspaceOverride: String?) throws -> Result {
11 let process = Process()
12 let input = Pipe()
13 let output = Pipe()
14 let writer = input.fileHandleForWriting
15 let reader = output.fileHandleForReading
16 process.executableURL = URL(fileURLWithPath: command)
17 process.arguments = ["--mcp"]
18 let environment = ProcessInfo.processInfo.environment
19 var childEnvironment = environment.filter { ["HOME", "PATH", "TMPDIR"].contains($0.key) }
20 childEnvironment["INKSPRING_NATIVE_WORKSPACE"] = workspaceOverride
21 process.environment = childEnvironment
22 process.standardInput = input
23 process.standardOutput = output
24 process.standardError = FileHandle.nullDevice
25 guard fcntl(writer.fileDescriptor, F_SETNOSIGPIPE, 1) == 0 else {
26 throw WorkspaceError("Couldn’t prepare the local MCP connection.")
27 }
28 try process.run()
29 defer {
30 try? writer.close()
31 try? reader.close()
32 if process.isRunning { process.terminate() }
33 }
34
35 let deadline = DispatchTime.now().uptimeNanoseconds + 8_000_000_000
36 var pending = Data()
37 func send(_ method: String, id: Int? = nil, parameters: [String: Any] = [:]) throws {
38 var request: [String: Any] = ["jsonrpc": "2.0", "method": method, "params": parameters]
39 if let id { request["id"] = id }
40 var line = try JSONSerialization.data(withJSONObject: request)
41 line.append(10)
42 try writer.write(contentsOf: line)
43 }
44
45 func receive(_ id: Int) throws -> [String: Any] {
46 var buffer = [UInt8](repeating: 0, count: 65_536)
47 while pending.count <= 8 * 1024 * 1024 {
48 if let newline = pending.firstIndex(of: 10) {
49 let line = Data(pending[..<newline])
50 pending.removeSubrange(...newline)
51 guard let response = (try? JSONSerialization.jsonObject(with: line)) as? [String: Any],
52 response["jsonrpc"] as? String == "2.0", response["id"] as? Int == id,
53 let result = response["result"] as? [String: Any] else {
54 throw WorkspaceError("Inkspring returned an invalid MCP response.")
55 }
56 return result
57 }
58 let now = DispatchTime.now().uptimeNanoseconds
59 guard now < deadline else { throw WorkspaceError("The local MCP server didn’t respond in time.") }
60 var descriptor = pollfd(fd: reader.fileDescriptor, events: Int16(POLLIN), revents: 0)
61 let ready = poll(&descriptor, 1, Int32((deadline - now + 999_999) / 1_000_000))
62 if ready < 0 && errno == EINTR { continue }
63 if ready == 0 { throw WorkspaceError("The local MCP server didn’t respond in time.") }
64 guard ready > 0 else {
65 throw WorkspaceError("Couldn’t read the local MCP response.")
66 }
67 let count = buffer.withUnsafeMutableBytes {
68 Darwin.read(reader.fileDescriptor, $0.baseAddress, $0.count)
69 }
70 if count < 0 && errno == EINTR { continue }
71 guard count > 0 else {
72 throw WorkspaceError("The local MCP server closed before the connection was verified.")
73 }
74 pending.append(contentsOf: buffer.prefix(count))
75 }
76 throw WorkspaceError("The local MCP server returned too much data.")
77 }
78
79 let version = "2025-11-25"
80 try send("initialize", id: 1, parameters: [
81 "protocolVersion": version, "capabilities": [:],
82 "clientInfo": ["name": "Inkspring Settings",
83 "version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0.0"]
84 ])
85 let server = try receive(1)
86 guard server["protocolVersion"] as? String == version,
87 (server["serverInfo"] as? [String: Any])?["name"] as? String == "inkspring" else {
88 throw WorkspaceError("The command did not start the Inkspring MCP server.")
89 }
90 try send("notifications/initialized")
91 try send("tools/list", id: 2)
92 let catalog = try receive(2)
93 guard let tools = catalog["tools"] as? [[String: Any]],
94 tools.contains(where: { $0["name"] as? String == "list_projects" }) else {
95 throw WorkspaceError("The Inkspring MCP server did not expose its project tool.")
96 }
97 try send("tools/call", id: 3, parameters: ["name": "list_projects", "arguments": [:]])
98 let readback = try receive(3)
99 guard readback["isError"] as? Bool != true,
100 let items = (readback["structuredContent"] as? [String: Any])?["items"] as? [[String: Any]] else {
101 throw WorkspaceError("The MCP server started but couldn’t read the workspace. Check that agent access is enabled.")
102 }
103 return Result(toolCount: tools.count, projectCount: items.count)
104 }
105}