Files
museion/Museion/MCPServer.swift
T
AlexKucera b02d36bb5d
CI / ci (push) Canceled after 0s
feat(mentor): research & library-light (S8) (#29)
The mentor researches mid-pass and its findings arrive as candidate
source-notes with provenance inside their Session. A third museion-
tools tool, submit_research_notes, is the typed rail (ADR-0006
posture): decode-validate only, reply {"received": N}, write NOTHING
— the session is the holding area, and keeping is the writer's act.

Candidates ride the transcript as first-class rows (researchNote):
parsed from the tool call's rawInput by payload shape — the notes
array routes before the fix-card parse, titles are display text —
one row per note, all-or-nothing per batch, the wire's whitespace
rule mirrored so both boundaries agree. Resume re-materializes them
for free: replays re-run the same parse; dispositions reset honestly
(they were never persisted — engine-owned cargo, ADR-0007).

The writer curates in place (full cards in the shared transcript, no
palette — a handful curates where it lands): Keep opens the
ask-before sheet (G9; PromoteAskSheet posture — inline refusal,
buttons kept) and ONE confirm lands one plain markdown note with
provenance into the piece's research/ via writeResearchNote — the
one folder(of:) id lookup anchors it inside this Home, a symlinked
research/ refuses, collision -2; Reject vanishes, recording nothing.
The pass stub names the rail and forbids the engine writing
candidates itself; kept notes flip hasResearch, so every later pass
sees the research/ path (S8.3 at v1 depth).

Finish-audit (three reviewers) drove the whitespace-parity and
shape-routing fixes, the ResearchNoteContent dedup, and a poll-loop
fix for the debounce rig's sidecar half that the larger suite's load
had pushed past its fixed sleep — full suite green (373 tests).

Closes #29
2026-10-22 14:06:16 +02:00

363 lines
12 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()))
}
}
// 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 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]],
])
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 args = try FixCardStore.decoder.decode(
ResearchNotesArgs.self, from: JSONSerialization.data(withJSONObject: arguments),
)
for note in args.notes {
guard !note.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw FixCardStore.CardError(message: "note title must not be empty")
}
guard !note.url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw FixCardStore.CardError(message: "note url must not be empty")
}
}
return reply(id: id, result: [
"content": [[
"type": "text",
"text": jsonString(["received": args.notes.count]) ?? "{}",
]] 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]
}
/// #29 (S8.1): one candidate source-note — quote/note optional on the
/// wire (they arrive as "" at the keep write when absent).
private struct ResearchNoteArgs: Decodable {
var title: String
var url: String
var quote: String?
var note: String?
}
/// #29 (S8.1): the research rail's wire shape — ONE shape, no legacy
/// fallback; a missing field fails decode = the trust boundary.
private struct ResearchNotesArgs: Decodable {
var piecePath: String
var notes: [ResearchNoteArgs]
}
// 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 <home>/learnings/<type>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}"#
}
}