feat(mentor): museion-tools MCP server (#23)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Headless --serve-mcp role in the app binary: NDJSON JSON-RPC on stdio exposing query_learnings and submit_fix_cards (ADR-0006 cards, anchor-validated; stale lands flagged, never rejected), registered into the museion profile at provisioning. Cards persist per piece under <piece>/cards/ and surface in a floating Fix Cards palette with pass-stamped provenance. Live dogfood drove the shape: session/prompt waits pass length (the 15 s request default abandoned working turns), a liveness row and a persisted Debug checkbox (off) split writing sessions from debug chatter, the verdict references findings by title only while the cards carry the detail (persona v1.3 — tools work in silence), and the #24 pass rails (pass bar, TurnOutcome seam, snapshots) ride in. Three-reviewer audit round: piece-path shape guard closes the JSON-drop and substring-oracle holes, nested submit rawInput parsing (the flat parser never matched the live rail), missing stopReason never advances a pass, 1 MB stdin cap, card scan off MainActor. 296 tests green; every behavioral fix flip-verified. Closes #23
This commit is contained in:
1 parent
c2e94fd825
commit
683ddf8426
29 files changed
+2626
-169
No files matched your search
@@ -0,0 +1,267 @@
|
||||
//
|
||||
// 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)
|
||||
return reply(id: id, result: [
|
||||
"content": [[
|
||||
"type": "text",
|
||||
"text": jsonString([
|
||||
"cards": written.map {
|
||||
["file": $0.file, "anchor_status": $0.card.anchorStatus.rawValue]
|
||||
} as [[String: Any]],
|
||||
]) ?? "{}",
|
||||
]] 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.",
|
||||
"inputSchema": [
|
||||
"type": "object",
|
||||
"properties": [
|
||||
"piece_path": [
|
||||
"type": "string",
|
||||
"description": "Path to the piece folder or its post.md.",
|
||||
],
|
||||
"cards": [
|
||||
"type": "array",
|
||||
"items": [
|
||||
"type": "object",
|
||||
"properties": [
|
||||
"pattern": ["type": "string"],
|
||||
"problem": ["type": "string"],
|
||||
"diagnostic_question": ["type": "string"],
|
||||
"fix": ["type": "string"],
|
||||
"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}"#
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user