Files
museion/Museion/MCPServer.swift
T
AlexKucera 4d33676a08
CI / ci (push) Canceled after 0s
feat(mentor): apply/skip fix cards (#25)
Fix Cards become actionable. Mechanical cards offer Apply behind a
blocking ask-before sheet showing the exact edit (anchored quote ->
replacement, occurrence + context; empty fix cuts); the sheet is the
only path to a write, one card at a time, no apply-all. The edit
lands through the editing session (pending edits flush first, the
editor re-seeds via adoptText, the card closes applied); Skip and
Done close the card in place, recording nothing; demonstration
cards close Done/Skip only (ADR-0006). Cards arrive ranked
(store-stamped, scan-ordered, open-first palette) and capped at ten
per submit — the app keeps the ranked head and the wire reply
discloses the drop. Stale anchors re-validate at apply: no text
selected or changed, the card flags itself. Includes the
finish-audit round (11 fixes, 2 flip-verified pins); 316 tests
green.

Closes #25
2026-10-20 16:46:43 +02:00

282 lines
9.3 KiB
Swift

//
// 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<String>, 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()))
}
}
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 args = try FixCardStore.decoder.decode(
SubmitArgs.self, from: JSONSerialization.data(withJSONObject: arguments),
)
let written = try FixCardStore.submit(piecePath: args.piecePath, cards: args.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 args.cards.count > written.count {
payload["dropped_over_ceiling"] = args.cards.count - written.count
}
return reply(id: id, result: [
"content": [[
"type": "text",
"text": jsonString(payload) ?? "{}",
]] as [[String: Any]],
])
default:
return failure(FixCardStore.CardError(message: "Unknown tool: \(name)"))
}
} catch {
return failure(error)
}
}
private struct LearningsArgs: Decodable {
var piecePath: String
}
private struct SubmitArgs: Decodable {
var piecePath: String
var cards: [FixCardStore.Input]
}
// MARK: - Tools
/// The two tools (#23). 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 <home>/learnings/<type>s/.",
"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],
],
]
}
// 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}"#
}
}