|
| 1 | +import Darwin |
| 2 | +import Foundation |
| 3 | + |
| 4 | +/// One native signed helper per MCP session. This executable owns both local |
| 5 | +/// connections; the model never sees a receipt capability or pairing identity. |
| 6 | +@main struct AgentCatalogMCP { |
| 7 | + static let maxFrame = 100 * 1024 |
| 8 | + static let reader = "get_tts_instructions" |
| 9 | + static let receiver = "submit_explanation_draft" |
| 10 | + static let maxProofs = AgentLimits.proofCount |
| 11 | + static let pin = ProcessInfo.processInfo.environment[AgentPeerSigning.pinEnvironment]?.lowercased() |
| 12 | + static let directory = "/private/tmp/codebasic-tts-mcp-\(getuid())" |
| 13 | + |
| 14 | + struct Proof { |
| 15 | + let profile: String |
| 16 | + let revision: String |
| 17 | + let bodyHash: String |
| 18 | + let token: String |
| 19 | + let expiry: ContinuousClock.Instant |
| 20 | + var key: String { profile + ":" + revision } |
| 21 | + } |
| 22 | + |
| 23 | + static func main() { |
| 24 | + var initialized = false, ready = false |
| 25 | + var proofs: [Proof] = [] |
| 26 | + while let input = readFrame() { |
| 27 | + if input.isEmpty { emit(error(nil, -32700, "Malformed or oversized frame")); continue } |
| 28 | + guard let frame = decode(input), frame["jsonrpc"] as? String == "2.0", |
| 29 | + let method = frame["method"] as? String else { |
| 30 | + emit(error(nil, -32600, "Invalid request")); continue |
| 31 | + } |
| 32 | + guard let id = frame["id"] else { |
| 33 | + if method == "notifications/initialized", initialized { ready = true } |
| 34 | + continue |
| 35 | + } |
| 36 | + guard id is String || id is NSNumber else { emit(error(nil, -32600, "Invalid request id")); continue } |
| 37 | + let params = frame["params"] as? [String: Any] ?? [:] |
| 38 | + switch method { |
| 39 | + case "initialize": |
| 40 | + guard !initialized else { emit(error(id, -32600, "Already initialized")); continue } |
| 41 | + initialized = true |
| 42 | + let requested = params["protocolVersion"] as? String ?? "" |
| 43 | + let version = ["2025-11-25", "2025-06-18", "2025-03-26"].contains(requested) ? requested : "2025-11-25" |
| 44 | + result(id, ["protocolVersion":version, "serverInfo":["name":"codebasic-tts-agent", "version":"2.0"], |
| 45 | + "capabilities":["tools":["listChanged":false]]]) |
| 46 | + case "ping": |
| 47 | + result(id, [:]) |
| 48 | + case "tools/list" where ready: |
| 49 | + result(id, ["tools": tools]) |
| 50 | + case "tools/call" where ready: |
| 51 | + guard let name = params["name"] as? String, let args = params["arguments"] as? [String: Any] else { |
| 52 | + emit(error(id, -32602, "Tool name and arguments required")); continue |
| 53 | + } |
| 54 | + switch name { |
| 55 | + case reader: |
| 56 | + guard Set(args.keys) == ["profile"], let selector = args["profile"] as? String, |
| 57 | + validSelector(selector) else { |
| 58 | + tool(id, "Use an exact built-in profile ID or the ID shown by the app.", failed: true); continue |
| 59 | + } |
| 60 | + guard let reply = exchange(socket: "i.sock", ["schema_version": 2, "profile": selector]), |
| 61 | + reply["schema_version"] as? Int == 2, reply["profile"] as? String == selector, |
| 62 | + let text = reply["instructions"] as? String, AgentBytes.textValid(text), |
| 63 | + let rev = reply["revision"] as? String, UUID(uuidString: rev) != nil, |
| 64 | + let hash = reply["body_sha256"] as? String, hash == AgentBytes.hash(Data(text.utf8)), |
| 65 | + let opaque = reply["proof"] as? String, UUID(uuidString: opaque) != nil else { |
| 66 | + tool(id, "No pinned, approved instruction revision available. Local helper PID: \(getpid()).", failed: true); continue |
| 67 | + } |
| 68 | + let proof = Proof(profile: selector, revision: rev, bodyHash: hash, token: opaque, |
| 69 | + expiry: .now.advanced(by: .seconds(AgentLimits.grantSeconds))) |
| 70 | + proofs.removeAll { $0.key == proof.key || $0.expiry <= .now } |
| 71 | + proofs.append(proof) |
| 72 | + if proofs.count > maxProofs { proofs.removeFirst(proofs.count - maxProofs) } |
| 73 | + tool(id, text, extra: ["schema_version":2, "profile":selector, "revision":rev, |
| 74 | + "body_sha256":hash, "instructions":text]) |
| 75 | + case receiver: |
| 76 | + let required: Set<String> = ["profile", "revision", "idempotency_key", "display_text"] |
| 77 | + let keys = Set(args.keys) |
| 78 | + guard keys == required || keys == required.union(["speech_text"]), |
| 79 | + let profile = args["profile"] as? String, let revision = args["revision"] as? String, |
| 80 | + let retry = args["idempotency_key"] as? String, |
| 81 | + (1...128).contains(retry.utf8.count), retry.range(of: "^[A-Za-z0-9._-]+$", options: .regularExpression) != nil, |
| 82 | + let display = args["display_text"] as? String, AgentBytes.textValid(display), |
| 83 | + args["speech_text"].map({ ($0 as? String).map(AgentBytes.textValid) == true }) ?? true else { |
| 84 | + tool(id, "Invalid plain-text draft arguments.", failed: true); continue |
| 85 | + } |
| 86 | + proofs.removeAll { $0.expiry <= .now } |
| 87 | + guard let proof = proofs.last(where: { $0.profile == profile && $0.revision == revision }) else { |
| 88 | + tool(id, "This helper did not receive that exact revision. Read it first or paste manually.", failed: true); continue |
| 89 | + } |
| 90 | + var request = args |
| 91 | + request["schema_version"] = 2 |
| 92 | + request["body_sha256"] = proof.bodyHash |
| 93 | + request["proof"] = proof.token |
| 94 | + let status = exchange(socket: "d.sock", request)?["status"] as? String |
| 95 | + switch status { |
| 96 | + case "accepted": tool(id, "Queued in the app. Not applied or played.") |
| 97 | + case "duplicate": tool(id, "Already received. Nothing new was queued or played.") |
| 98 | + case "conflict": tool(id, "Retry key already used for different content.", failed: true) |
| 99 | + case "busy": tool(id, "Inbox is full. Nothing was queued.", failed: true) |
| 100 | + case "rate_limited": tool(id, "This grant’s receipt rate limit was reached.", failed: true) |
| 101 | + case "unproven": tool(id, "Revision proof expired, was revoked, or the profile was deleted. Read again or paste manually.", failed: true) |
| 102 | + default: tool(id, "Receipt not confirmed. Retry unchanged or paste manually. Local helper PID: \(getpid()).", failed: true) |
| 103 | + } |
| 104 | + default: |
| 105 | + emit(error(id, -32602, "Unknown tool")) |
| 106 | + } |
| 107 | + default: |
| 108 | + emit(error(id, -32601, "Method unavailable")) |
| 109 | + } |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + static var tools: [[String: Any]] { |
| 114 | + let string = ["type":"string"] |
| 115 | + return [["name":reader, "description":"Read one exact locally approved instruction revision.", |
| 116 | + "inputSchema":["type":"object","properties":["profile":string],"required":["profile"],"additionalProperties":false], |
| 117 | + "annotations":["readOnlyHint":true,"openWorldHint":false]], |
| 118 | + ["name":receiver, "description":"Queue an editable plain-text draft for a revision received by this helper. Never plays.", |
| 119 | + "inputSchema":["type":"object", "properties":["profile":string,"revision":string,"idempotency_key":string, |
| 120 | + "display_text":string,"speech_text":string],"required":["profile","revision","idempotency_key","display_text"], |
| 121 | + "additionalProperties":false], |
| 122 | + "annotations":["readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false]]] |
| 123 | + } |
| 124 | + |
| 125 | + static func validSelector(_ selector: String) -> Bool { |
| 126 | + if ["explain","continue","normalize"].contains(selector) { return true } |
| 127 | + return UUID(uuidString: selector)?.uuidString.lowercased() == selector |
| 128 | + } |
| 129 | + |
| 130 | + static func decode(_ data: Data) -> [String: Any]? { |
| 131 | + guard !data.contains(0), String(data: data, encoding: .utf8) != nil else { return nil } |
| 132 | + return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] |
| 133 | + } |
| 134 | + |
| 135 | + static func readFrame() -> Data? { |
| 136 | + var data = Data(), oversized = false |
| 137 | + while true { |
| 138 | + let c = fgetc(stdin) |
| 139 | + if c == EOF { return data.isEmpty && !oversized ? nil : Data() } |
| 140 | + if c == 10 { return oversized ? Data() : data } |
| 141 | + if data.count + 1 >= maxFrame { oversized = true } |
| 142 | + if !oversized { data.append(UInt8(c)) } |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + static func exchange(socket endpoint: String, _ request: [String: Any]) -> [String: Any]? { |
| 147 | + guard let pin, endpoint == "i.sock" || endpoint == "d.sock" else { return nil } |
| 148 | + var st = stat() |
| 149 | + let path = directory + "/" + endpoint |
| 150 | + guard lstat(directory, &st) == 0, st.st_uid == getuid(), st.st_mode & S_IFMT == S_IFDIR, st.st_mode & 0o777 == 0o700, |
| 151 | + lstat(path, &st) == 0, st.st_uid == getuid(), st.st_mode & S_IFMT == S_IFSOCK, st.st_mode & 0o777 == 0o600, |
| 152 | + var data = try? JSONSerialization.data(withJSONObject: request, options: [.withoutEscapingSlashes]), |
| 153 | + data.count < maxFrame else { return nil } |
| 154 | + data.append(10) |
| 155 | + var addr = sockaddr_un() |
| 156 | + let wire = Array(path.utf8CString) |
| 157 | + guard wire.count <= MemoryLayout.size(ofValue: addr.sun_path) else { return nil } |
| 158 | + addr.sun_family = sa_family_t(AF_UNIX) |
| 159 | + addr.sun_len = UInt8(MemoryLayout<sockaddr_un>.size) |
| 160 | + withUnsafeMutableBytes(of: &addr.sun_path) { dst in wire.withUnsafeBytes { dst.copyBytes(from: $0) } } |
| 161 | + let fd = Darwin.socket(AF_UNIX, SOCK_STREAM, 0) |
| 162 | + guard fd >= 0 else { return nil } |
| 163 | + defer { close(fd) } |
| 164 | + var yes: Int32 = 1, timeout = timeval(tv_sec: 2, tv_usec: 0) |
| 165 | + guard setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &yes, socklen_t(MemoryLayout<Int32>.size)) == 0, |
| 166 | + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size)) == 0, |
| 167 | + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size)) == 0 else { return nil } |
| 168 | + let connection = withUnsafePointer(to: &addr) { |
| 169 | + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) } |
| 170 | + } |
| 171 | + guard connection == 0, AgentPeerSigning.matches(socket: fd, identifier: AgentPeerSigning.appID, leaf: pin) else { return nil } |
| 172 | + let sent = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> Bool in |
| 173 | + guard let base = bytes.baseAddress else { return false } |
| 174 | + var done = 0 |
| 175 | + while done < bytes.count { |
| 176 | + let n = send(fd, base.advanced(by: done), bytes.count - done, 0) |
| 177 | + if n <= 0 { return false } |
| 178 | + done += n |
| 179 | + } |
| 180 | + return true |
| 181 | + } |
| 182 | + guard sent, shutdown(fd, SHUT_WR) == 0 else { return nil } |
| 183 | + let maximum = endpoint == "i.sock" ? 52 * 1024 : 128 |
| 184 | + var output = Data(), chunk = [UInt8](repeating: 0, count: 4096) |
| 185 | + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) |
| 186 | + var terminated = false |
| 187 | + while ContinuousClock.now < deadline { |
| 188 | + let count = chunk.withUnsafeMutableBytes { recv(fd, $0.baseAddress, $0.count, 0) } |
| 189 | + if count == 0 { return terminated ? decode(output) : nil } |
| 190 | + guard count > 0, !terminated, output.count + count <= maximum else { return nil } |
| 191 | + output.append(contentsOf: chunk.prefix(count)) |
| 192 | + if let newline = output.firstIndex(of: 10) { |
| 193 | + guard newline == output.endIndex - 1 else { return nil } |
| 194 | + terminated = true |
| 195 | + } |
| 196 | + } |
| 197 | + return nil |
| 198 | + } |
| 199 | + |
| 200 | + static func emit(_ envelope: [String: Any]) { |
| 201 | + if var data = try? JSONSerialization.data(withJSONObject: envelope, options: [.withoutEscapingSlashes]) { |
| 202 | + data.append(10); FileHandle.standardOutput.write(data) |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + static func error(_ id: Any?, _ code: Int, _ message: String) -> [String: Any] { |
| 207 | + ["jsonrpc":"2.0","id":id ?? NSNull(),"error":["code":code,"message":message]] |
| 208 | + } |
| 209 | + |
| 210 | + static func result(_ id: Any, _ payload: [String: Any]) { |
| 211 | + emit(["jsonrpc":"2.0","id":id,"result":payload]) |
| 212 | + } |
| 213 | + |
| 214 | + static func tool(_ id: Any, _ message: String, failed: Bool = false, extra: [String: Any]? = nil) { |
| 215 | + var value: [String: Any] = ["content":[["type":"text","text":message]],"isError":failed] |
| 216 | + if let extra { value["structuredContent"] = extra } |
| 217 | + result(id, value) |
| 218 | + } |
| 219 | +} |
0 commit comments