Branchwell

Jobley / app · jobley.ai / Sources / JobleyKit / MCPServer.swift

Raw 10.8 KB on 31b31c099e453aea6c2ecdc8181ae49a445ca531
1import Foundation
2
3/// STDIO MCP server, run as `Jobley --mcp`. Every request carries `X-Client: mcp`.
4///
5/// Agents may read the board and the review queue, read the house rules, tidy a post's wording and
6/// leave a review note. That is all. There is no tool to approve, send back, publish or unpublish,
7/// and none that touches candidates; the API also answers `403 people_only` if an agent client tries.
8/// Write tools need "Let agents make changes" in Settings → Agents, and every agent write is logged.
9/// It uses the Mac app's passkey sign-in (the session in the Keychain), never a token in tool arguments,
10/// and it can never sign in or add a passkey itself. Queue tools strip the poster's
11/// private contact details before anything reaches the agent.
12public final class MCPServer: @unchecked Sendable {
13 let api: APIClient
14 let defaults: UserDefaults
15 let logURL: URL
16 var clientName = "Agent"
17
18 public init(api: APIClient, defaults: UserDefaults = .standard, logURL: URL = AgentLog.fileURL) {
19 self.api = api; self.defaults = defaults; self.logURL = logURL
20 }
21
22 /// The server the Mac app's `--mcp` mode runs.
23 public static func live() -> MCPServer {
24 MCPServer(api: APIClient(client: .mcp, token: TokenStore.load()))
25 }
26
27 struct Tool {
28 let name: String, summary: String
29 var fields: [String: [String: Any]] = [:]
30 var required: [String] = []
31 var writes = false
32 var json: [String: Any] {
33 ["name": name, "description": summary,
34 "inputSchema": ["type": "object", "properties": fields, "required": required, "additionalProperties": false],
35 "annotations": ["readOnlyHint": !writes, "destructiveHint": false, "idempotentHint": !writes, "openWorldHint": true]]
36 }
37 }
38
39 static var str: [String: Any] { ["type": "string"] }
40
41 static var tools: [Tool] { [
42 .init(name: "get_status", summary: "Who the Mac app is signed in as, how many posts are in each state, and whether agents may make changes. Call this first."),
43 .init(name: "list_jobs", summary: "Search the public board (published jobs only), newest first.",
44 fields: ["query": str, "workplace": str, "type": str, "category": str, "limit": ["type": "integer", "minimum": 1, "maximum": 100]]),
45 .init(name: "get_job", summary: "One published job from the public board.", fields: ["job_id": str], required: ["job_id"]),
46 .init(name: "list_review_queue", summary: "Posts waiting for a person to review, oldest first. Contact details are removed.",
47 fields: ["status": ["type": "string", "enum": ["pending", "approved", "rejected", "unpublished"]]]),
48 .init(name: "get_review_item", summary: "One post in the queue with its review history. Contact details are removed.", fields: ["job_id": str], required: ["job_id"]),
49 .init(name: "get_house_rules", summary: "The rules for what counts as a good job, so you can point at the one a post may miss. A person decides."),
50 .init(name: "tidy_job_post", summary: "Fix the wording of a post's title or description: typos, spacing, formatting. Never change pay, company, location or meaning.",
51 fields: ["job_id": str, "title": str, "description": str], required: ["job_id"], writes: true),
52 .init(name: "add_review_note", summary: "Leave a note on a post for the person reviewing it.",
53 fields: ["job_id": str, "note": str], required: ["job_id", "note"], writes: true)
54 ] }
55
56 public static var toolNames: [String] { tools.map(\.name) }
57
58 // MARK: Transport
59
60 public func run() async {
61 let input = FileHandle.standardInput, output = FileHandle.standardOutput
62 var line = Data()
63 while true {
64 let chunk = input.availableData
65 if chunk.isEmpty { if !line.isEmpty { await respond(line, output) }; return }
66 for byte in chunk {
67 if byte == 10 { if !line.isEmpty { await respond(line, output) }; line.removeAll(keepingCapacity: true) }
68 else if line.count < 1_048_576 { line.append(byte) }
69 }
70 }
71 }
72
73 private func respond(_ data: Data, _ output: FileHandle) async {
74 let reply: [String: Any]?
75 if let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] { reply = await handle(request) }
76 else { reply = failure(NSNull(), -32700, "Parse error.") }
77 if let reply, var json = try? JSONSerialization.data(withJSONObject: reply) { json.append(10); try? output.write(contentsOf: json) }
78 }
79
80 public func handle(_ request: [String: Any]) async -> [String: Any]? {
81 let id = request["id"] ?? NSNull()
82 guard let method = request["method"] as? String else { return failure(id, -32600, "Invalid request.") }
83 guard request["id"] != nil else { return nil }
84 let params = request["params"] as? [String: Any] ?? [:]
85 switch method {
86 case "initialize":
87 if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String { clientName = name }
88 let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]
89 let asked = params["protocolVersion"] as? String ?? ""
90 return success(id, ["protocolVersion": supported.contains(asked) ? asked : supported[0],
91 "capabilities": ["tools": ["listChanged": false]],
92 "serverInfo": ["name": "jobley", "version": "0.1.0"],
93 "instructions": "Jobley is a job board where people decide. You can read the board and the review queue, tidy a post's wording and leave notes. You cannot approve, send back, publish or unpublish a post, and you never see candidates. Never rank, score or filter jobs or people."])
94 case "ping": return success(id, [:])
95 case "tools/list": return success(id, ["tools": Self.tools.map(\.json)])
96 case "tools/call":
97 let name = params["name"] as? String ?? ""
98 let args = params["arguments"] as? [String: Any] ?? [:]
99 guard let tool = Self.tools.first(where: { $0.name == name }) else { return failure(id, -32602, "Unknown tool \(name).") }
100 if tool.writes && !AgentSettings.allowsWrites(defaults) {
101 return success(id, text("Changes by agents are off. Ask the person to turn on “Let agents make changes” in Jobley Settings → Agents.", isError: true))
102 }
103 do { return success(id, text(try await call(name, args))) }
104 catch let error as APIError { return success(id, text(error.errorDescription ?? error.message, isError: true)) }
105 catch { return success(id, text(error.localizedDescription, isError: true)) }
106 default: return failure(id, -32601, "Method not found.")
107 }
108 }
109
110 func call(_ name: String, _ args: [String: Any]) async throws -> String {
111 func string(_ key: String) -> String { (args[key] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" }
112 func required(_ key: String) throws -> String {
113 let value = string(key)
114 guard !value.isEmpty else { throw APIError(code: "invalid", message: "\(key) is required.") }
115 return value
116 }
117 switch name {
118 case "get_status":
119 let me = try await api.me(), stats = try await api.stats()
120 return encode(["role": me.role, "name": me.name, "jobs": stats.jobs, "agents_may_make_changes": AgentSettings.allowsWrites(defaults)] as [String: any Encodable])
121 case "list_jobs":
122 let page = try await api.jobs(query: string("query"), workplace: string("workplace"), type: string("type"),
123 category: string("category"), limit: args["limit"] as? Int ?? 30)
124 return encode(page.jobs)
125 case "get_job":
126 return encode(try await api.job(try required("job_id")))
127 case "list_review_queue":
128 let status = string("status").isEmpty ? "pending" : string("status")
129 guard ["pending", "approved", "rejected", "unpublished"].contains(status) else { throw APIError(code: "invalid", message: "Unknown status.") }
130 return encode(try await api.adminJobs(status: status).map(\.withoutContact))
131 case "get_review_item":
132 let item = try await api.reviewItem(try required("job_id"))
133 return encode(["job": item.job.withoutContact, "activity": item.activity] as [String: any Encodable])
134 case "get_house_rules":
135 return HouseRules.text
136 case "tidy_job_post":
137 let jobID = try required("job_id")
138 var changes: [String: Any] = [:]
139 if !string("title").isEmpty { changes["title"] = string("title") }
140 if !string("description").isEmpty { changes["description"] = string("description") }
141 guard !changes.isEmpty else { throw APIError(code: "invalid", message: "Pass a new title or description. Only wording can be tidied.") }
142 let job = try await api.edit(job: jobID, changes: changes)
143 log("tidy_job_post", jobID, "Tidied the " + changes.keys.sorted().joined(separator: " and ") + " of “\(job.title)”")
144 return "Tidied. A person still decides whether it is published.\n" + encode(job.withoutContact)
145 case "add_review_note":
146 let jobID = try required("job_id"), note = try required("note")
147 try await api.addNote(job: jobID, note: String(note.prefix(2000)))
148 log("add_review_note", jobID, "Added a note: " + String(note.prefix(120)))
149 return "Note added for the reviewer."
150 default:
151 throw APIError(code: "not_found", message: "Unknown tool.")
152 }
153 }
154
155 func log(_ tool: String, _ jobID: String, _ summary: String) {
156 AgentLog.append(AgentLogEntry(at: .now, agent: clientName, tool: tool, jobID: jobID, summary: summary), at: logURL)
157 }
158
159 func encode(_ value: any Encodable) -> String {
160 let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
161 return (try? encoder.encode(AnyEncodable(value))).flatMap { String(data: $0, encoding: .utf8) } ?? "{}"
162 }
163
164 func encode(_ dictionary: [String: any Encodable]) -> String {
165 encode(dictionary.mapValues(AnyEncodable.init))
166 }
167
168 private func text(_ body: String, isError: Bool = false) -> [String: Any] {
169 ["content": [["type": "text", "text": body]], "isError": isError]
170 }
171 private func success(_ id: Any, _ result: [String: Any]) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "result": result] }
172 private func failure(_ id: Any, _ code: Int, _ message: String) -> [String: Any] {
173 ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]]
174 }
175}
176
177struct AnyEncodable: Encodable {
178 let value: any Encodable
179 init(_ value: any Encodable) { self.value = value }
180 func encode(to encoder: Encoder) throws { try value.encode(to: encoder) }
181}