import Foundation /// STDIO MCP server, run as `Jobley --mcp`. Every request carries `X-Client: mcp`. /// /// Agents may read the board and the review queue, read the house rules, tidy a post's wording and /// leave a review note. That is all. There is no tool to approve, send back, publish or unpublish, /// and none that touches candidates; the API also answers `403 people_only` if an agent client tries. /// Write tools need "Let agents make changes" in Settings → Agents, and every agent write is logged. /// It uses the Mac app's passkey sign-in (the session in the Keychain), never a token in tool arguments, /// and it can never sign in or add a passkey itself. Queue tools strip the poster's /// private contact details before anything reaches the agent. public final class MCPServer: @unchecked Sendable { let api: APIClient let defaults: UserDefaults let logURL: URL var clientName = "Agent" public init(api: APIClient, defaults: UserDefaults = .standard, logURL: URL = AgentLog.fileURL) { self.api = api; self.defaults = defaults; self.logURL = logURL } /// The server the Mac app's `--mcp` mode runs. public static func live() -> MCPServer { MCPServer(api: APIClient(client: .mcp, token: TokenStore.load())) } struct Tool { let name: String, summary: String var fields: [String: [String: Any]] = [:] var required: [String] = [] var writes = false var json: [String: Any] { ["name": name, "description": summary, "inputSchema": ["type": "object", "properties": fields, "required": required, "additionalProperties": false], "annotations": ["readOnlyHint": !writes, "destructiveHint": false, "idempotentHint": !writes, "openWorldHint": true]] } } static var str: [String: Any] { ["type": "string"] } static var tools: [Tool] { [ .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."), .init(name: "list_jobs", summary: "Search the public board (published jobs only), newest first.", fields: ["query": str, "workplace": str, "type": str, "category": str, "limit": ["type": "integer", "minimum": 1, "maximum": 100]]), .init(name: "get_job", summary: "One published job from the public board.", fields: ["job_id": str], required: ["job_id"]), .init(name: "list_review_queue", summary: "Posts waiting for a person to review, oldest first. Contact details are removed.", fields: ["status": ["type": "string", "enum": ["pending", "approved", "rejected", "unpublished"]]]), .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"]), .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."), .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.", fields: ["job_id": str, "title": str, "description": str], required: ["job_id"], writes: true), .init(name: "add_review_note", summary: "Leave a note on a post for the person reviewing it.", fields: ["job_id": str, "note": str], required: ["job_id", "note"], writes: true) ] } public static var toolNames: [String] { tools.map(\.name) } // MARK: Transport public func run() async { let input = FileHandle.standardInput, output = FileHandle.standardOutput var line = Data() while true { let chunk = input.availableData if chunk.isEmpty { if !line.isEmpty { await respond(line, output) }; return } for byte in chunk { if byte == 10 { if !line.isEmpty { await respond(line, output) }; line.removeAll(keepingCapacity: true) } else if line.count < 1_048_576 { line.append(byte) } } } } private func respond(_ data: Data, _ output: FileHandle) async { let reply: [String: Any]? if let request = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] { reply = await handle(request) } else { reply = failure(NSNull(), -32700, "Parse error.") } if let reply, var json = try? JSONSerialization.data(withJSONObject: reply) { json.append(10); try? output.write(contentsOf: json) } } public func handle(_ request: [String: Any]) async -> [String: Any]? { let id = request["id"] ?? NSNull() guard let method = request["method"] as? String else { return failure(id, -32600, "Invalid request.") } guard request["id"] != nil else { return nil } let params = request["params"] as? [String: Any] ?? [:] switch method { case "initialize": if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String { clientName = name } let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] let asked = params["protocolVersion"] as? String ?? "" return success(id, ["protocolVersion": supported.contains(asked) ? asked : supported[0], "capabilities": ["tools": ["listChanged": false]], "serverInfo": ["name": "jobley", "version": "0.1.0"], "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."]) case "ping": return success(id, [:]) case "tools/list": return success(id, ["tools": Self.tools.map(\.json)]) case "tools/call": let name = params["name"] as? String ?? "" let args = params["arguments"] as? [String: Any] ?? [:] guard let tool = Self.tools.first(where: { $0.name == name }) else { return failure(id, -32602, "Unknown tool \(name).") } if tool.writes && !AgentSettings.allowsWrites(defaults) { 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)) } do { return success(id, text(try await call(name, args))) } catch let error as APIError { return success(id, text(error.errorDescription ?? error.message, isError: true)) } catch { return success(id, text(error.localizedDescription, isError: true)) } default: return failure(id, -32601, "Method not found.") } } func call(_ name: String, _ args: [String: Any]) async throws -> String { func string(_ key: String) -> String { (args[key] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" } func required(_ key: String) throws -> String { let value = string(key) guard !value.isEmpty else { throw APIError(code: "invalid", message: "\(key) is required.") } return value } switch name { case "get_status": let me = try await api.me(), stats = try await api.stats() return encode(["role": me.role, "name": me.name, "jobs": stats.jobs, "agents_may_make_changes": AgentSettings.allowsWrites(defaults)] as [String: any Encodable]) case "list_jobs": let page = try await api.jobs(query: string("query"), workplace: string("workplace"), type: string("type"), category: string("category"), limit: args["limit"] as? Int ?? 30) return encode(page.jobs) case "get_job": return encode(try await api.job(try required("job_id"))) case "list_review_queue": let status = string("status").isEmpty ? "pending" : string("status") guard ["pending", "approved", "rejected", "unpublished"].contains(status) else { throw APIError(code: "invalid", message: "Unknown status.") } return encode(try await api.adminJobs(status: status).map(\.withoutContact)) case "get_review_item": let item = try await api.reviewItem(try required("job_id")) return encode(["job": item.job.withoutContact, "activity": item.activity] as [String: any Encodable]) case "get_house_rules": return HouseRules.text case "tidy_job_post": let jobID = try required("job_id") var changes: [String: Any] = [:] if !string("title").isEmpty { changes["title"] = string("title") } if !string("description").isEmpty { changes["description"] = string("description") } guard !changes.isEmpty else { throw APIError(code: "invalid", message: "Pass a new title or description. Only wording can be tidied.") } let job = try await api.edit(job: jobID, changes: changes) log("tidy_job_post", jobID, "Tidied the " + changes.keys.sorted().joined(separator: " and ") + " of “\(job.title)”") return "Tidied. A person still decides whether it is published.\n" + encode(job.withoutContact) case "add_review_note": let jobID = try required("job_id"), note = try required("note") try await api.addNote(job: jobID, note: String(note.prefix(2000))) log("add_review_note", jobID, "Added a note: " + String(note.prefix(120))) return "Note added for the reviewer." default: throw APIError(code: "not_found", message: "Unknown tool.") } } func log(_ tool: String, _ jobID: String, _ summary: String) { AgentLog.append(AgentLogEntry(at: .now, agent: clientName, tool: tool, jobID: jobID, summary: summary), at: logURL) } func encode(_ value: any Encodable) -> String { let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys] return (try? encoder.encode(AnyEncodable(value))).flatMap { String(data: $0, encoding: .utf8) } ?? "{}" } func encode(_ dictionary: [String: any Encodable]) -> String { encode(dictionary.mapValues(AnyEncodable.init)) } private func text(_ body: String, isError: Bool = false) -> [String: Any] { ["content": [["type": "text", "text": body]], "isError": isError] } private func success(_ id: Any, _ result: [String: Any]) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "result": result] } private func failure(_ id: Any, _ code: Int, _ message: String) -> [String: Any] { ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]] } } struct AnyEncodable: Encodable { let value: any Encodable init(_ value: any Encodable) { self.value = value } func encode(to encoder: Encoder) throws { try value.encode(to: encoder) } }