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,183 @@
|
||||
//
|
||||
// MCPServerWireTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #23 (M2, slice 1): the museion-tools wire contract, in-process through
|
||||
// MCPServer.run(lines:write:) over real JSON-RPC lines — echoed
|
||||
// protocolVersion, silent notifications, typed tools/list, the full
|
||||
// submit round-trip with the card on disk, isError tool failures,
|
||||
// -32601 unknown method, -32700 garbage. Wire facts verified live
|
||||
// against the real hermes MCP client.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
/// Run lines through the server loop, parsing every reply as JSON objects.
|
||||
private func runWire(_ lines: [String]) throws -> [[String: Any]] {
|
||||
var replies: [String] = []
|
||||
MCPServer.run(lines: AnyIterator(lines.makeIterator())) { replies.append($0) }
|
||||
return try replies.compactMap {
|
||||
try JSONSerialization.jsonObject(with: Data($0.utf8)) as? [String: Any]
|
||||
}
|
||||
}
|
||||
|
||||
/// Review pin (DoS): a line over the 1 MB frame cap answers -32600 —
|
||||
/// never reaches JSONSerialization.
|
||||
@Test func `oversized line answers line too long`() throws {
|
||||
let big = String(repeating: "a", count: 1_048_577)
|
||||
let replies = try runWire([big])
|
||||
let error = replies[0]["error"] as? [String: Any]
|
||||
#expect((error?["code"] as? Int) == -32600)
|
||||
}
|
||||
|
||||
private let initializeLine = #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#
|
||||
private let initializedLine = #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#
|
||||
private let toolsListLine = #"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#
|
||||
|
||||
/// The text payload of a tools/call result.
|
||||
private func toolText(_ result: [String: Any]) throws -> String {
|
||||
let content = try #require(result["content"] as? [[String: Any]])
|
||||
return try #require(content.first?["text"] as? String)
|
||||
}
|
||||
|
||||
struct MCPServerWireTests {
|
||||
@Test func `initialize echoes client protocol version`() throws {
|
||||
let replies = try runWire([initializeLine])
|
||||
#expect(replies.count == 1)
|
||||
#expect(replies[0]["id"] as? Int == 1)
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result["protocolVersion"] as? String == "2025-06-18")
|
||||
let info = try #require(result["serverInfo"] as? [String: Any])
|
||||
#expect(info["name"] as? String == "museion-tools")
|
||||
#expect(result["capabilities"] is [String: Any])
|
||||
}
|
||||
|
||||
@Test func `initialize falls back to pinned protocol version`() throws {
|
||||
let replies = try runWire([#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result["protocolVersion"] as? String == "2025-11-25")
|
||||
}
|
||||
|
||||
@Test func `notifications never reply`() throws {
|
||||
#expect(try runWire([initializedLine]).isEmpty)
|
||||
}
|
||||
|
||||
@Test func `ping answers empty result`() throws {
|
||||
let replies = try runWire([#"{"jsonrpc":"2.0","id":9,"method":"ping"}"#])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result.isEmpty)
|
||||
}
|
||||
|
||||
@Test func `tools list exposes both tools with schemas`() throws {
|
||||
let replies = try runWire([toolsListLine])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
let tools = try #require(result["tools"] as? [[String: Any]])
|
||||
#expect(Set(tools.compactMap { $0["name"] as? String }) == ["query_learnings", "submit_fix_cards"])
|
||||
|
||||
let submit = try #require(tools.first { $0["name"] as? String == "submit_fix_cards" })
|
||||
let schema = try #require(submit["inputSchema"] as? [String: Any])
|
||||
let required = try #require(schema["required"] as? [String])
|
||||
#expect(required.contains("piece_path"))
|
||||
#expect(required.contains("cards"))
|
||||
let properties = try #require(schema["properties"] as? [String: Any])
|
||||
let cardsProp = try #require(properties["cards"] as? [String: Any])
|
||||
let cardItems = try #require(cardsProp["items"] as? [String: Any])
|
||||
let cardRequired = try #require(cardItems["required"] as? [String])
|
||||
#expect(cardRequired.contains("pattern"))
|
||||
#expect(cardRequired.contains("problem"))
|
||||
#expect(cardRequired.contains("anchor"))
|
||||
#expect(cardRequired.contains("lane"))
|
||||
#expect(cardRequired.contains("emitter"))
|
||||
let cardProps = try #require(cardItems["properties"] as? [String: Any])
|
||||
let anchor = try #require(cardProps["anchor"] as? [String: Any])
|
||||
let anchorProps = try #require(anchor["properties"] as? [String: Any])
|
||||
let occurrence = try #require(anchorProps["occurrence"] as? [String: Any])
|
||||
#expect(occurrence["type"] as? String == "integer")
|
||||
#expect(occurrence["default"] as? Int == 1)
|
||||
|
||||
let query = try #require(tools.first { $0["name"] as? String == "query_learnings" })
|
||||
let querySchema = try #require(query["inputSchema"] as? [String: Any])
|
||||
#expect(try #require(querySchema["required"] as? [String]) == ["piece_path"])
|
||||
}
|
||||
|
||||
@Test func `submit and query round trip through the wire`() throws {
|
||||
let home = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("mcp-wire-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
||||
let piece = home.appendingPathComponent("projects/posts/test-piece", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: piece, withIntermediateDirectories: true)
|
||||
try "---\ntype: post\n---\nThe repeated anchor line.\n"
|
||||
.write(to: piece.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
let learnings = home.appendingPathComponent("learnings/posts", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: learnings, withIntermediateDirectories: true)
|
||||
try "wire learning".write(to: learnings.appendingPathComponent("l.md"), atomically: true, encoding: .utf8)
|
||||
|
||||
// swiftlint:disable line_length
|
||||
let submit = """
|
||||
{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"submit_fix_cards","arguments":{"piece_path":"\(piece.path)","cards":[{"pattern":"Hedging","problem":"The hedge weakens the claim.","anchor":{"quote":"repeated anchor line"},"lane":"mechanical","emitter":"lint"}]}}}
|
||||
"""
|
||||
// swiftlint:enable line_length
|
||||
let query = """
|
||||
{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"query_learnings","arguments":{"piece_path":"\(piece.path)"}}}
|
||||
"""
|
||||
let replies = try runWire([initializeLine, initializedLine, submit, query])
|
||||
// initialize + two tool results; the notification stayed silent.
|
||||
#expect(replies.count == 3)
|
||||
|
||||
let submitResult = try #require(replies[1]["result"] as? [String: Any])
|
||||
#expect(submitResult["isError"] == nil)
|
||||
let payload = try #require(
|
||||
try JSONSerialization.jsonObject(with: Data(toolText(submitResult).utf8)) as? [String: Any],
|
||||
)
|
||||
let cards = try #require(payload["cards"] as? [[String: Any]])
|
||||
#expect(cards.first?["anchor_status"] as? String == "valid")
|
||||
let file = try #require(cards.first?["file"] as? String)
|
||||
#expect(file.hasSuffix("-hedging.json"))
|
||||
#expect(
|
||||
FileManager.default.fileExists(atPath: piece.appendingPathComponent("cards/\(file)").path),
|
||||
)
|
||||
|
||||
let queryResult = try #require(replies[2]["result"] as? [String: Any])
|
||||
let learned = try #require(
|
||||
try JSONSerialization.jsonObject(with: Data(toolText(queryResult).utf8)) as? [String: Any],
|
||||
)
|
||||
let learningsPayload = try #require(learned["learnings"] as? [[String: Any]])
|
||||
#expect(learningsPayload.first?["markdown"] as? String == "wire learning")
|
||||
}
|
||||
|
||||
@Test func `tool failures set is error`() throws {
|
||||
let lines = [
|
||||
// Missing piece.
|
||||
// swiftlint:disable:next line_length
|
||||
#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"submit_fix_cards","arguments":{"piece_path":"/nonexistent/piece","cards":[{"pattern":"p","problem":"q","anchor":{"quote":"x"},"lane":"mechanical","emitter":"lint"}]}}}"#,
|
||||
// Unknown tool name.
|
||||
#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"wat","arguments":{}}}"#,
|
||||
// Malformed arguments (piece_path missing).
|
||||
#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"query_learnings","arguments":{}}}"#,
|
||||
]
|
||||
for line in lines {
|
||||
let replies = try runWire([line])
|
||||
let result = try #require(replies[0]["result"] as? [String: Any])
|
||||
#expect(result["isError"] as? Bool == true, "expected isError for: \(line)")
|
||||
#expect(replies[0]["error"] == nil)
|
||||
let text = try toolText(result)
|
||||
#expect(!text.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func `unknown method errors 32601`() throws {
|
||||
let replies = try runWire([#"{"jsonrpc":"2.0","id":6,"method":"wat/thing"}"#])
|
||||
let error = try #require(replies[0]["error"] as? [String: Any])
|
||||
#expect(error["code"] as? Int == -32601)
|
||||
#expect(replies[0]["result"] == nil)
|
||||
}
|
||||
|
||||
@Test func `garbage line errors 32700 with null id`() throws {
|
||||
let replies = try runWire(["not json at all"])
|
||||
let error = try #require(replies[0]["error"] as? [String: Any])
|
||||
#expect(error["code"] as? Int == -32700)
|
||||
#expect(replies[0]["id"] is NSNull)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user