// // MCPServer.swift // Museion // // #23 (M2, slice 1): the museion-tools MCP server over stdio — NDJSON // JSON-RPC 2.0 (one message per line, stdout is the wire, stderr logs), // launched headless via --serve-mcp before any AppKit machinery. Wire // facts baked in from a live verified session against the real hermes // MCP client. // import Foundation import SwiftUI /// The launch branch (#23): `--serve-mcp` runs the headless tool server, /// anything else is the normal app. Lives here — MuseionApp stays the /// pure SwiftUI scene. @main enum MuseionLauncher { static func main() { if CommandLine.arguments.contains("--serve-mcp") { MCPServer.serve() } else { MuseionApp.main() } } } /// #23: the stdio MCP server. nonisolated — this mode runs before any app /// machinery and never touches NSApplication/AppKit. nonisolated enum MCPServer { /// Production entry: blocking loop over stdin lines, replies on /// stdout. EOF on stdin → clean exit 0. static func serve() { run( lines: AnyIterator { readLine() }, write: { line in fputs(line + "\n", stdout) fflush(stdout) // piped stdout is block-buffered; unflushed lines never reach the client }, ) } /// The dispatch loop, in-process testable: feed lines, collect /// replies. static func run(lines: AnyIterator, write: (String) -> Void) { while let line = lines.next() { dispatch(line, write: write) } } // MARK: - Dispatch private static func dispatch(_ line: String, write: (String) -> Void) { // 1 MB frame cap — mirrors ACPEngineClient's reader cap so a // hostile or buggy client can't push an unbounded line into // JSONSerialization. ponytail: readLine() still buffers the line // itself in memory; byte-chunked stdin reader if a same-user OOM // ever matters. guard line.utf8.count <= 1_048_576 else { write(reply(error: ["code": -32600, "message": "Line too long"], id: NSNull())) return } guard let data = line.data(using: .utf8), let message = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], let method = message["method"] as? String else { write(reply(error: ["code": -32700, "message": "Parse error"], id: NSNull())) return } let id = message["id"] let params = message["params"] as? [String: Any] ?? [:] // Notifications (notifications/initialized & friends) never reply. if method.hasPrefix("notifications/") { return } switch method { case "initialize": // Echo the client's protocolVersion; never invent one. let version = params["protocolVersion"] as? String ?? "2025-11-25" write(reply(id: id, result: [ "protocolVersion": version, "capabilities": ["tools": [:]] as [String: Any], "serverInfo": ["name": "museion-tools", "version": "1.0"], ])) case "ping": write(reply(id: id, result: [:])) case "tools/list": write(reply(id: id, result: ["tools": tools])) case "tools/call": write(toolCall(id: id, params: params)) default: write(reply(error: ["code": -32601, "message": "Method not found"], id: id ?? NSNull())) } } // The dispatcher's body IS the tool catalog — it grows one case per // tool. ponytail: split per-tool handlers out only when a second // dimension (not more tools) forces it. // swiftlint:disable:next function_body_length private static func toolCall(id: Any?, params: [String: Any]) -> String { let name = params["name"] as? String ?? "" let arguments = params["arguments"] as? [String: Any] ?? [:] func failure(_ error: Error) -> String { // CardError carries the human message; other errors (decode) // read better verbatim. Tool failures are results with // isError inside — never JSON-RPC errors. let text = error is FixCardStore.CardError ? error.localizedDescription : "\(error)" return reply(id: id, result: [ "content": [["type": "text", "text": text]] as [[String: Any]], "isError": true, ]) } do { switch name { case "query_learnings": let args = try FixCardStore.decoder.decode( LearningsArgs.self, from: JSONSerialization.data(withJSONObject: arguments), ) let learned = try FixCardStore.learnings(piecePath: args.piecePath) return reply(id: id, result: [ "content": [[ "type": "text", "text": jsonString([ "learnings": learned.map { ["file": $0.file, "markdown": $0.markdown] } as [[String: Any]], ]) ?? "{}", ]] as [[String: Any]], ]) case "submit_fix_cards": let (piecePath, cards) = try ToolPayloads.submitFixCards(from: JSONValue(arguments)) let written = try FixCardStore.submit(piecePath: piecePath, cards: cards) var payload: [String: Any] = [ "cards": written.map { ["file": $0.file, "anchor_status": $0.card.anchorStatus.rawValue] } as [[String: Any]], ] // The ceiling backstop tells the truth on the wire (#25 S3.2): // cards beyond the kept ranked head were dropped — say how many. if cards.count > written.count { payload["dropped_over_ceiling"] = cards.count - written.count } return reply(id: id, result: [ "content": [[ "type": "text", "text": jsonString(payload) ?? "{}", ]] as [[String: Any]], ]) case "submit_research_notes": // #29 (S8.1): the candidates rail — DECODE-VALIDATE ONLY. // Findings are engine-owned cargo in their session; the reply // is a received count, never storage. The ONLY path to disk is // the writer's keep (PostStore.writeResearchNote). let received = try ToolPayloads.submitResearchNotes(from: JSONValue(arguments)) return reply(id: id, result: [ "content": [[ "type": "text", "text": jsonString(["received": received]) ?? "{}", ]] as [[String: Any]], ]) default: return failure(FixCardStore.CardError(message: "Unknown tool: \(name)")) } } catch { return failure(error) } } private struct LearningsArgs: Decodable { var piecePath: String } // MARK: - Tools /// The tools (#23 cards + learnings; #29 the research rail). The submit /// schema IS the fix-card schema (ADR-0006): it serves the card UI, the /// apply-write, and learning promotion. private static var tools: [[String: Any]] { [ [ "name": "query_learnings", "description": "The piece's visible learnings — raw markdown per file, from /learnings/s/. " + "Dismissed learnings are hidden until their decay interval (base 10 passes, doubling per " + "re-dismiss; a per-Learning resurface_after frontmatter key overrides) elapses.", "inputSchema": [ "type": "object", "properties": [ "piece_path": [ "type": "string", "description": "Path to the piece folder or its post.md.", ] as [String: Any], ] as [String: Any], "required": ["piece_path"], ] as [String: Any], ], [ "name": "submit_fix_cards", "description": "Persist fix cards for a piece. Anchor-validated against post.md; " + "stale anchors land flagged. At most 10 cards per call — " + "the app keeps the ranked head and drops the rest.", "inputSchema": [ "type": "object", "properties": [ "piece_path": [ "type": "string", "description": "Path to the piece folder or its post.md.", ], "cards": [ "type": "array", "description": "Ranked most-important-first; at most 10 per call — " + "the app keeps the ranked head and drops the rest.", "items": [ "type": "object", "properties": [ "pattern": ["type": "string"], "problem": ["type": "string"], "diagnostic_question": ["type": "string"], "fix": [ "type": "string", "description": "Mechanical cards: the exact replacement for the anchored span " + "(empty string = cut). Demonstration cards: the demonstration.", ] as [String: Any], "anchor": [ "type": "object", "properties": [ "quote": [ "type": "string", "description": "Exact substring quoted from the piece.", ], "occurrence": [ "type": "integer", "default": 1, "description": "1-based occurrence of the quote in the piece.", ], "context": ["type": "string"], ] as [String: Any], "required": ["quote"], ], "lane": ["type": "string", "enum": ["mechanical", "demonstration"]], "emitter": ["type": "string", "enum": ["lint", "engine"]], "provenance": [ "type": "object", "properties": [ "piece": ["type": "string"], "date": ["type": "string"], "engine": ["type": "string"], "pass": [ "type": "integer", "description": "Pass number that found the card (1 = structural, 2 = line-level).", ] as [String: Any], ] as [String: Any], ], ] as [String: Any], "required": ["pattern", "problem", "anchor", "lane", "emitter"], ] as [String: Any], ] as [String: Any], ] as [String: Any], "required": ["piece_path", "cards"], ] as [String: Any], ], [ "name": "submit_research_notes", "description": "Deliver research findings as candidate source-notes for a piece — " + "candidates only: the notes arrive in the session, nothing is written to disk. " + "The writer keeps or rejects each note in Museion; keeping writes the plain " + "markdown note (with provenance) into the piece's research/ folder.", "inputSchema": [ "type": "object", "properties": [ "piece_path": [ "type": "string", "description": "Path to the piece folder or its post.md.", ], "notes": [ "type": "array", "description": "Candidate source-notes with provenance.", "items": [ "type": "object", "properties": [ "title": ["type": "string"], "url": ["type": "string"], "quote": [ "type": "string", "description": "Verbatim quotation from the source, when there is one.", ], "note": [ "type": "string", "description": "The finding — why this source matters to the piece.", ], ] as [String: Any], "required": ["title", "url"], ] as [String: Any], ] as [String: Any], ] as [String: Any], "required": ["piece_path", "notes"], ] as [String: Any], ], ] } // MARK: - Wire plumbing /// One JSON serializer for every wire path (review: textJSON/serialize /// were the same body twice). private static func jsonString(_ object: [String: Any]) -> String? { (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes])) .flatMap { String(data: $0, encoding: .utf8) } } private static func reply(id: Any?, result: [String: Any]) -> String { serialize(["jsonrpc": "2.0", "id": id ?? NSNull(), "result": result] as [String: Any]) } private static func reply(error: [String: Any], id: Any) -> String { serialize(["jsonrpc": "2.0", "error": error, "id": id] as [String: Any]) } private static func serialize(_ object: [String: Any]) -> String { if let string = jsonString(object) { return string } // The wire must always answer, but stay debuggable: stderr is logs. fputs("museion-tools: reply serialization failed\n", stderr) return #"{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error"},"id":null}"# } }