Skip to content
29 changes: 28 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ let package = Package(
type: .dynamic,
targets: ["CApi"]
),
// The tools an AI uses to drive the machine, served over the Model
// Context Protocol. The library has no transport of its own: the
// executable below speaks stdio, the macOS app HTTP.
.library(
name: "Bubilator88Automation",
targets: ["Bubilator88Automation"]
),
.executable(
name: "bubilator88-mcp",
targets: ["MCPServer"]
),
],
dependencies: [
.package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"),
Expand Down Expand Up @@ -76,10 +87,26 @@ let package = Package(
],
swiftSettings: alwaysOptimize
),
.target(
name: "Bubilator88Automation",
dependencies: [
"Bubilator88Core",
],
swiftSettings: alwaysOptimize
),
.executableTarget(
name: "MCPServer",
dependencies: [
"Bubilator88Automation",
"Bubilator88Core",
.product(name: "Logging", package: "swift-log"),
]
),
.target(
name: "CApi",
dependencies: [
"Bubilator88Core",
"Bubilator88Automation",
],
// The @_cdecl functions are public, and Swift exports public
// symbols from a Windows DLL by itself; no .def file is needed.
Expand All @@ -92,7 +119,7 @@ let package = Package(
),
.testTarget(
name: "Bubilator88CoreTests",
dependencies: ["Bubilator88Core", "Z80", "FMSynthesis", "Peripherals", "PC88Types", "CApi"]
dependencies: ["Bubilator88Core", "Z80", "FMSynthesis", "Peripherals", "PC88Types", "CApi", "Bubilator88Automation"]
),
]
)
26 changes: 26 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,32 @@ Product > Build Documentation で開けます。
- **不安定**: `@_spi(Debug) import Bubilator88Core` で見えるもの (デバッガ、CPU レジスタ、
音源の内部状態など)。Bubilator88 のデバッガ用で、予告なく変わります。
- **C ABI** (`Bubilator88C`, `b88_*`): 関数の追加のみ行い、既存の関数は変えません。
- **不安定**: `Bubilator88Automation` の Swift API。MCP のツール名と引数は使う側
(AI) に見えるので、変えるときは互換に気を付けます。

## AI から操作する (MCP)

`Bubilator88Automation` は、AI がエミュレータを操作するためのツールを
[Model Context Protocol](https://modelcontextprotocol.io) で提供します。
フレーム実行、キー・文字列入力、画面 (PNG とテキスト)、ディスク、ステート、
レジスタ・メモリの参照と書き換え、逆アセンブル、ブレークポイント、命令トレース、
書き込み元の追跡とウォッチ、シンボル付きのサイクル計測、
メモリマップ、機械語ファイルの直接ロード、メモリダンプ、テープ、入力の記録・再生を扱えます。
通信手段は持たず、JSON-RPC のメッセージを 1 件ずつ処理します。

`bubilator88-mcp` は、これを stdio で動かす headless のサーバーです。
コマンドを起動できる MCP クライアントなら、どれからでも使えます。
時間は AI がフレームを実行したときだけ進むので、同じ操作は同じ結果になります。
BIOS ROM は既定でアプリと同じ `~/Library/Application Support/Bubilator88` から読みます。

```
# Claude Code の例。ほかのクライアントでは、このコマンドを stdio のサーバーとして登録する
claude mcp add bubilator88-headless -- \
swift run --package-path /path/to/Bubilator88Core bubilator88-mcp
swift run bubilator88-mcp --help # ROM の場所、モード、起動ディスクの指定
```

C ABI からは `b88_mcp_handle` / `b88_mcp_reply` で同じツールを使えます。

## Windows (C ABI)

Expand Down
93 changes: 93 additions & 0 deletions Sources/Bubilator88Automation/AutomationHost.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import Foundation
@_spi(Debug) import Bubilator88Core

/// Where the automation tools run: a machine plus the few operations whose
/// right behaviour depends on who owns it.
///
/// The tools themselves (`ToolCatalog`) are written once against this
/// protocol. `PC88AutomationHost` is the plain implementation used by the
/// headless server and the C ABI; the macOS app supplies its own so that
/// resets, disks and save states also update its windows and settings.
///
/// Every method is called from one thread at a time (the server's), never
/// concurrently.
public protocol AutomationHost: AnyObject {
/// Run `body` on the thread that owns the machine, between frames.
func withMachine<T>(_ body: (PC88) throws -> T) throws -> T

/// Run up to `count` frames as fast as possible, calling `beforeEach`
/// before each one; it returns false to stop early. Stops early, too, when
/// a breakpoint pauses `debugger`. Returns the frames run, counting the one
/// a breakpoint cut short.
///
/// A host that also runs the machine in real time stops doing so first and
/// leaves it stopped, so what the caller sees next is what it ran.
func runFrames(_ count: Int, beforeEach: (PC88) -> Bool) throws -> Int

/// The debugger breakpoints are kept in. It need not be attached to the
/// machine; `setDebuggerAttached` attaches it.
@_spi(Debug) var debugger: Debugger { get }

/// Attach the debugger while breakpoints exist, so breakpoints fire; the
/// host may keep it attached for its own reasons as well.
func setDebuggerAttached(_ attached: Bool) throws

/// Whether the machine runs in real time on its own. Always false for a
/// headless host, whose time moves only through `runFrames`.
var isRunningInRealTime: Bool { get }

/// Start or stop real-time running. Throws `AutomationError` on a host
/// that has no real time.
func setRunningInRealTime(_ running: Bool) throws

/// Reset the machine. `mode` and `clock8MHz`, when given, change the
/// machine before a cold reset.
func reset(cold: Bool, mode: BootMode?, clock8MHz: Bool?) throws

/// Mount image `imageIndex` of the disk file at `url` in `drive` (0 or 1).
/// Returns the image's name.
func mountDisk(drive: Int, url: URL, imageIndex: Int, writeProtected: Bool) throws -> String

func ejectDisk(drive: Int) throws

/// Write a `.b88s` save state to `url`.
func saveState(to url: URL) throws

/// Restore the `.b88s` save state at `url`.
func loadState(from url: URL) throws

/// Load the cassette image at `url`. Returns the format found.
func mountTape(url: URL) throws -> TapeFormat

func rewindTape() throws

func ejectTape() throws
}

/// The plain cassette operations, for a host with no cassette display to
/// keep up to date.
public extension AutomationHost {
func mountTape(url: URL) throws -> TapeFormat {
let data: Data
do {
data = try Data(contentsOf: url)
} catch {
throw AutomationError("Cannot read \(url.path): \(error.localizedDescription)")
}
return try withMachine { $0.mountTape(data: data) }
}

func rewindTape() throws {
try withMachine { $0.rewindTape() }
}

func ejectTape() throws {
try withMachine { $0.ejectTape() }
}
}

/// A failure reported back to the AI as a tool error, in words it can act on.
public struct AutomationError: Error, Equatable, CustomStringConvertible {
public let description: String
public init(_ description: String) { self.description = description }
}
Loading
Loading