mtga-companion
2026 · Architect and product owner · in active use
A local tracker for MTG Arena, built as a Rust pipeline: it captures the game's log into SQLite, rebuilds matches from the raw entries with a versioned parser, and serves read-only MCP tools and a live overlay.
- Rust
- SQLite
- SQL
- MCP
- tokio
- egui
- Windows
- tests passed, last recorded count
- 2,291
- read-only MCP tools
- 15
- log entries in a copy of production
- 151,417
- to rebuild all derived data
- 10.6 s
The failure I set out to prevent is a wrong number. Every rate carries its sample size and an interval, and below ten games a cell shows only wins and losses. I worked as architect and product owner; Claude Code agents wrote the code, and how that worked is below.
01 · Runtime processes
One SQLite file, one writer at a time
Two binaries run as separate capture, MCP server and overlay processes around one SQLite file. Writers take one fail-fast lock, one at a time; the overlay and the tools open the file read-only. The game’s own files are only read, never written, locked or renamed, and no game memory is read.
System, edge by edge
| From, to | What crosses |
|---|---|
| Game log → Capture | shared read: Polled every 300 ms by default; the file is never written, locked or renamed. |
| Capture → Raw entries | insert: Committed as a row before the parser reads it. |
| Raw entries → Parser | raw rows: Read in sequence order, inside the capture process. |
| Parser → Derived data | replace: A match's derived rows are replaced together. |
| Raw entries → Overlay | read-only: A separate process polls for new rows every 250 ms. Not drawn: its record panel and end-of-match summary also read derived data, read-only. |
| Derived data → MCP server | read-only: The 15 tools share one handle opened with SQLite's read-only flag. |
| MCP server → Ingest lock | at start: Never waited for: up to two attempts, one to apply view definitions and one to catch up on the log; each is skipped if another writer holds the lock. |
| MCP server ↔ Claude Code | stdio: JSON-RPC over stdio; logs go to stderr. |
| Ingest lock | One writer at a time, never waited for. Capture holds it for its whole run; one-shot commands (ingest, rebuild, card load) also take it. |
System, edge by edge
- Game log → Capture
- shared read: Polled every 300 ms by default; the file is never written, locked or renamed.
- Capture → Raw entries
- insert: Committed as a row before the parser reads it.
- Raw entries → Parser
- raw rows: Read in sequence order, inside the capture process.
- Parser → Derived data
- replace: A match's derived rows are replaced together.
- Raw entries → Overlay
- read-only: A separate process polls for new rows every 250 ms. Not drawn: its record panel and end-of-match summary also read derived data, read-only.
- Derived data → MCP server
- read-only: The 15 tools share one handle opened with SQLite's read-only flag.
- MCP server → Ingest lock
- at start: Never waited for: up to two attempts, one to apply view definitions and one to catch up on the log; each is skipped if another writer holds the lock.
- MCP server ↔ Claude Code
- stdio: JSON-RPC over stdio; logs go to stderr.
- Ingest lock
- One writer at a time, never waited for. Capture holds it for its whole run; one-shot commands (ingest, rebuild, card load) also take it.
Stack
| Technology and version | Role and reason |
|---|---|
| Foundation | |
| Rust edition 2024 | One Cargo workspace of three crates, about 25,000 lines outside tests: a core library and two binaries that depend on it. Why: A small always-on process with no runtime, in a hot loop over a growing log. |
| Capture | |
| Rust standard library file I/O | Follows the game log through a shared read handle, polled every 300 ms by default; no file-watcher package. Why: The game's buffered writes make file-system events unreliable, and polling one file is free. |
| fs4 0.13.1 | A single-instance ingest lock on a file beside the database, acquired fail-fast and never waited for: a second ingest or rebuild is refused, not queued. |
| Store | |
| SQLite via rusqlite 0.37.0, SQLite bundled | One file in WAL mode holds the whole store; PRAGMA user_version tracks six embedded migrations, and an upgrade runs in one transaction after a full backup. Why: One file, queryable from anything, trivially backed up; the MCP server and the overlay read the same file. |
| Statistics | |
| SQL views, SQLite dialect | 14 views built with window functions, materialized common table expressions and json_each; a test fails if any of them names the raw table. |
| Interval math | Wilson 95% score intervals and Newcombe differences, written as pure functions in the core library. Why: Not the Wald interval: Wilson stays usable at zero wins and at zero losses. |
| MCP server | |
| rmcp, schemars =3.8.0, =1.2.3 | MCP over stdio through an explicit server handler, without tool macros: 15 read-only tools, each schema generated from the query type that also validates its arguments. Why: Pinned exactly after a spike, schemars to the version rmcp uses. Claude Code connects over stdio, so there is no HTTP surface. |
| tokio =1.54.1 | A multi-thread runtime built only inside the MCP subcommand; the capture loop is synchronous. |
| Overlay | |
| eframe (egui), on glow (OpenGL) =0.37.0, glow 0.17.0 | The always-on-top overlay window; the renderer is selected in code and no wgpu package is in the lock file. Why: In a spike, wgpu lost window transparency after one toggle and used 154 MB against 72.5 MB. |
| windows-sys (Win32) =0.61.2 | Global hotkey, raw mouse and keyboard input, and the game window's client rectangle and its monitor's DPI. Why: Selection rule for the overlay's crates: the latest release at least two weeks old. The hotkey crate candidate was younger. |
| Operations | |
| Windows Task Scheduler | Registered to start capture at logon with no window, from generated task XML. Why: A task created from XML registers from a non-elevated shell. |
| Quality | |
| rustfmt, clippy, cargo test | One local pre-push script: format check, clippy on all targets with warnings as errors, then cargo test across the workspace. No hosted CI. |
Crate versions are those resolved in the lock file; an equals sign marks an exact pin, and a reason appears only where the project recorded one.
Supporting libraries and tools (9)
| Technology and version | Role and reason |
|---|---|
| Foundation | |
| serde, serde_json 1.0.229, 1.0.154 | Query and response types, MCP payloads and the overlay layout file. Why: float_roundtrip is set explicitly so every build agrees in the last digit of a float. |
| Capture | |
| sha2 0.10.9 | SHA-256 of each captured entry's decoded text. |
| Statistics | |
| jiff 0.2.38 | Local-day and ISO-week buckets, with the time-zone database bundled. Why: Windows has no IANA time-zone database on disk. |
| Operations | |
| tracing, tracing-subscriber 0.1.44, 0.3.23 | Logs to stderr, or to a file in always-on mode, which keeps stdout free for JSON-RPC. |
| tray-icon =0.26.1 | Notification-area icon on its own thread. Why: Selection rule recorded for this crate: the latest release at least two weeks old, pinned exactly. |
| tauri-winrt-notification =0.8.1 | A toast when always-on capture breaks or exits on an error; a standalone crate, not the Tauri framework. Why: Selection rule recorded for this crate: the latest release at least two weeks old. It never activates a window. |
| Quality | |
| zstd 0.13.3 | Recorded-session test fixtures at level 19; not used inside the database. |
| jsonschema =0.60.2 | Validates golden test files against a committed JSON Schema. Why: Default features off: local references only, so no HTTP resolver and no TLS. |
| egui_kittest =0.37.0 | Overlay UI tests that assert against the accessibility tree. |
02 · Data flow and failure paths
Commit first, parse after
Capture commits each entry before the parser reads it, so a parser failure is recorded and capture carries on. Progress lives in the database, not the process, so a restart resumes from the stored offset.
Capture path, edge by edge
| From, to | What crosses |
|---|---|
| Game log → Log reader | shared read: New bytes from the stored offset, at most 8 MiB a step. |
| Log reader → Entry grouper | byte chunks: Chunks may split anywhere; a half-written line waits. |
| Entry grouper → Raw insert | whole entries: While the log is live, only complete entries are emitted; the pending one is flushed when the log rotates. |
| Raw insert → Raw entries | idempotent: Insert-or-ignore on session and sequence number: the same bytes twice change nothing. |
| Raw insert → Session row | same commit: Offset and entry count move in the same transaction. |
| Session row → Log reader | resume offset: On start, reading resumes from the stored offset. |
| Raw insert → Guarded parse | after commit: Runs when capture attaches to a log, after a match ends and after the log rotates. An error or panic is recorded as a failed run; capture continues. |
| Log reader → Log reader | retry, max 20: A transient file error re-attaches and retries, up to 20 times in a row. |
Capture path, edge by edge
- Game log → Log reader
- shared read: New bytes from the stored offset, at most 8 MiB a step.
- Log reader → Entry grouper
- byte chunks: Chunks may split anywhere; a half-written line waits.
- Entry grouper → Raw insert
- whole entries: While the log is live, only complete entries are emitted; the pending one is flushed when the log rotates.
- Raw insert → Raw entries
- idempotent: Insert-or-ignore on session and sequence number: the same bytes twice change nothing.
- Raw insert → Session row
- same commit: Offset and entry count move in the same transaction.
- Session row → Log reader
- resume offset: On start, reading resumes from the stored offset.
- Raw insert → Guarded parse
- after commit: Runs when capture attaches to a log, after a match ends and after the log rotates. An error or panic is recorded as a failed run; capture continues.
- Log reader → Log reader
- retry, max 20: A transient file error re-attaches and retries, up to 20 times in a row.
03 · Storage layers
Derived data rebuilds from the raw entries
The derived tables hold matches, games and game state. A parser fix is a version bump: the next parse empties the derived tables and replays every session in one transaction, and incremental parsing must leave exactly what that rebuild would.
Storage layers, edge by edge
| From, to | What crosses |
|---|---|
| Raw entries | Stored byte-exact and hashed. Marked in amber: the source every derived table is rebuilt from; a rebuild reads it and never changes it. |
| Raw entries → Parser | in seq order: A rebuild starts every session from its first row. |
| Parser → Run history | stamps version: Each recorded run, failed ones included, carries the parser version. |
| Run history → Parser | older: rebuild: No successful run yet, or one from an older parser version, makes the next parse a full rebuild. |
| Parser → Derived tables | per match: Fifteen of the 18 tables are replaced match by match; a rebuild empties all 18 first and rolls back if it fails. |
| Derived tables | The 18 tables hold the parser's facts: matches, games, game state, decks and rank. |
| Derived tables → Statistics views | read: A test fails if any view's SQL names the raw table. |
| Card reference → Statistics views | card facts: Card names, colours and costs, loaded by command from the game's card database, opened read-only. |
| Statistics views | Not drawn: the views also read run history and the session table. |
Storage layers, edge by edge
- Raw entries
- Stored byte-exact and hashed. Marked in amber: the source every derived table is rebuilt from; a rebuild reads it and never changes it.
- Raw entries → Parser
- in seq order: A rebuild starts every session from its first row.
- Parser → Run history
- stamps version: Each recorded run, failed ones included, carries the parser version.
- Run history → Parser
- older: rebuild: No successful run yet, or one from an older parser version, makes the next parse a full rebuild.
- Parser → Derived tables
- per match: Fifteen of the 18 tables are replaced match by match; a rebuild empties all 18 first and rolls back if it fails.
- Derived tables
- The 18 tables hold the parser's facts: matches, games, game state, decks and rank.
- Derived tables → Statistics views
- read: A test fails if any view's SQL names the raw table.
- Card reference → Statistics views
- card facts: Card names, colours and costs, loaded by command from the game's card database, opened read-only.
- Statistics views
- Not drawn: the views also read run history and the session table.
04 · One request, end to end
No rate without its sample size
On a tool call the daemon binary only adapts the protocol and appends its run-time warnings. The query type, the SQL and the interval all live in the core library, and every successful response carries the literal SQL of its main statement.
Tool call, step by step
| From, to | What crosses |
|---|---|
| Claude Code → Server handler | tools/call: Standard output carries only protocol frames. |
| Server handler → Tool dispatch | blocking thread: The call moves to a blocking thread. |
| Tool dispatch → Stats reader | typed query: Arguments become the Rust type that publishes the tool's schema; an unknown key is refused. |
| Stats reader → Statistics views | literal SQL: One read transaction; the same SQL text returns in the response header. |
| Stats reader → Stats envelope | Marked in amber: the code that computes a rate or withholds it. Under 10 games counts only; 10 to 29 a flagged rate; 30 or more ok; Wilson 95% interval. |
| Stats reader → Tool dispatch | header + body: A typed response whose header has eleven fields, among them the SQL and the exclusions. |
| Tool dispatch → Server handler | serialized: Run-time warnings are appended, then the response is serialized. |
| Server handler → Claude Code | one text block: Returned as a single text block. |
Tool call, step by step
- Claude Code → Server handler
- tools/call: Standard output carries only protocol frames.
- Server handler → Tool dispatch
- blocking thread: The call moves to a blocking thread.
- Tool dispatch → Stats reader
- typed query: Arguments become the Rust type that publishes the tool's schema; an unknown key is refused.
- Stats reader → Statistics views
- literal SQL: One read transaction; the same SQL text returns in the response header.
- Stats reader → Stats envelope
- Marked in amber: the code that computes a rate or withholds it. Under 10 games counts only; 10 to 29 a flagged rate; 30 or more ok; Wilson 95% interval.
- Stats reader → Tool dispatch
- header + body: A typed response whose header has eleven fields, among them the SQL and the exclusions.
- Tool dispatch → Server handler
- serialized: Run-time warnings are appended, then the response is serialized.
- Server handler → Claude Code
- one text block: Returned as a single text block.
Real win_rates output from a recorded session, reformatted and abridged. Six games in one event are too few, so that rate is null.
{
"body": {
"cells": [
{
"wins": 9, "losses": 14, "n": 23,
"n_flag": "low_n",
"rate": 0.391304347826087,
"ci_low": 0.22157622687390552,
"ci_high": 0.5921447775576323
}
],
"per_event": [
{
"dims": { "event": "Alchemy_Ladder" },
"wins": 3, "losses": 3, "n": 6,
"n_flag": "insufficient",
"rate": null, "ci_low": null, "ci_high": null
}
]
},
"header": {
"tool": "win_rates",
"policy": {
"interval": "wilson_95",
"insufficient_below": 10,
"ok_from": 30
},
"exclusions": {
"n_incomplete": 1,
"n_out_of_population": 1
},
"reproduce_sql": "SELECT sum(result = 'win') AS wins, sum(result = 'loss') AS losses, sum(gap_bursts > 0) AS n_in_gap_games FROM gold_match WHERE excl_reason IS NULL AND event_name IN ('Ladder', 'Alchemy_Ladder') HAVING count(*) > 0"
}
}
05 · Threads in one process
The overlay reads the store and never writes it
The poll thread owns a read-only connection and replays the open match in memory with the parser’s own code. The render thread draws without reading the store, and the snapshot it receives is built to carry only what a player could see at the table.
Overlay path, edge by edge
| From, to | What crosses |
|---|---|
| SQLite file → Read model | new raw rows: One statement every 250 ms (SQLite's data_version) asks whether anything committed; while a match is followed, the raw rows after the last one pushed are then read. |
| Read model → Live tracker | The read model pushes those rows into an in-memory replay that runs the parser's own code. |
| Live tracker → Live snapshot | hidden ids cut: Unrevealed card ids in the opponent's hand and library are removed first; the keys are an allow-list of 37 paths. Marked in amber: a test fails if snapshot keys differ from it. |
| Live snapshot → View state | Joined with card facts and the record: the deck's past results against the opponent's colours, read from the file by statistics functions that MCP tools also call; sent only when it differs. |
| View state → Renderer | channel: This path's only thread crossing: a channel send and a repaint request. |
| Renderer → Four boxes | The renderer draws Library, Opponent, Record and Status, from display rules in the core library. |
Overlay path, edge by edge
- SQLite file → Read model
- new raw rows: One statement every 250 ms (SQLite's data_version) asks whether anything committed; while a match is followed, the raw rows after the last one pushed are then read.
- Read model → Live tracker
- The read model pushes those rows into an in-memory replay that runs the parser's own code.
- Live tracker → Live snapshot
- hidden ids cut: Unrevealed card ids in the opponent's hand and library are removed first; the keys are an allow-list of 37 paths. Marked in amber: a test fails if snapshot keys differ from it.
- Live snapshot → View state
- Joined with card facts and the record: the deck's past results against the opponent's colours, read from the file by statistics functions that MCP tools also call; sent only when it differs.
- View state → Renderer
- channel: This path's only thread crossing: a channel send and a repaint request.
- Renderer → Four boxes
- The renderer draws Library, Opponent, Record and Status, from display rules in the core library.
06 · Dependency direction
Both binaries depend on core, never on each other
Core declares no GUI, async, MCP or Windows-API dependency. Inside core there is no crate boundary: one source-scan test keeps the store from importing the parser, and the store’s SQLite connection is private to the crate.
Dependencies, edge by edge
| From, to | What crosses |
|---|---|
| Daemon → Core library | path dep: The capture and MCP server binary depends on core by path. |
| Overlay binary → Core library | path dep: The overlay depends on core by path. |
| Daemon, Overlay binary | Neither binary's manifest lists the other, and core's manifest lists neither. |
| Live projection → Parser | reuses replay: The live tracker runs the parser's pure pieces as they are. |
| Live projection → Statistics | same readers: The overlay's record line comes from the functions the tools call. |
| Live projection → Store | read-only: The live module opens the store only with SQLite's read-only flag, and nothing in the module writes. |
| Parser → Store | Only the parser's runner module touches the store. |
| Store, Parser | by test: A unit test fails if the store's source imports the parser. |
| Statistics → Store | Of gold and stats, only gold reads the store, through a connection that is private to core. |
Dependencies, edge by edge
- Daemon → Core library
- path dep: The capture and MCP server binary depends on core by path.
- Overlay binary → Core library
- path dep: The overlay depends on core by path.
- Daemon, Overlay binary
- Neither binary's manifest lists the other, and core's manifest lists neither.
- Live projection → Parser
- reuses replay: The live tracker runs the parser's pure pieces as they are.
- Live projection → Statistics
- same readers: The overlay's record line comes from the functions the tools call.
- Live projection → Store
- read-only: The live module opens the store only with SQLite's read-only flag, and nothing in the module writes.
- Parser → Store
- Only the parser's runner module touches the store.
- Store, Parser
- by test: A unit test fails if the store's source imports the parser.
- Statistics → Store
- Of gold and stats, only gold reads the store, through a connection that is private to core.
Decisions and their limits
A correct view change once made three card tools about three times slower with every test green; a manual timing run and a bisect found it. Record 03 is what came of it.
Show how query work is counted (Rust)
pub fn count_vm_work<T>(&self, f: impl FnOnce() -> T) -> (T, u64) {
let ticks = Arc::new(AtomicU64::new(0));
let seen = Arc::clone(&ticks);
self.conn.progress_handler(
1,
Some(move || {
seen.fetch_add(1, Ordering::Relaxed);
false
}),
);
let out = f();
self.conn.progress_handler(1, None::<fn() -> bool>);
(out, ticks.load(Ordering::Relaxed))
}01 The log is the source of truth
- Enforced by
- A test ingests a recorded session of 19,378 entries (62 MB of log text), exports it and requires the same SHA-256.
- Known limit
- One recorded session. Exact reproduction dates from schema version 3; earlier rows were backfilled.
- Rejected
- Reading the game's memory or network traffic. Notes taken while playing as ground truth.
02 Incremental parsing must equal a full rebuild
- Enforced by
- Two tests parse one recorded session (its first 6 matches, then all 25) in 64 KiB steps, with restarts partway, and compare a fingerprint of all 18 derived tables with a from-scratch rebuild.
- Known limit
- The restarts are simulated inside the test process, not real process restarts.
03 Query cost is counted by a test and timed by hand
- Enforced by
- A test counts SQLite's virtual-machine work for the card tools on seeded stores and fails at 25% over a committed baseline; five query-plan tests; a timed comparison of parent against candidate before merge.
- Known limit
- The budget catches the data shapes it seeds: it later passed a second slowdown, of 1.5 to 2.3 times, until a second seed with a large card table was added. The timed comparison is manual.
- Rejected
- A wall-clock threshold in the automated test run. Exempting follow-up fixes from re-timing.
04 The overlay holds the opponent's hidden cards only as counts
- Enforced by
- An allow-list of 37 snapshot key paths: a new field fails a test until the list file is edited. A second test strips the action list from every game-state message of a recorded 25-match session and requires identical derived tables.
- Known limit
- Exact for the opponent's hand, library and face-down cards, which exist only as counts. The revealed-cards list does carry card ids: a tested filter keeps it clean, and admits a card first seen with no zone.
- Rejected
- Using the opponent's available actions. Reading game memory.
05 The overlay is a separate process, read-only on the store
- Enforced by
- SQLite's read-only open flag, plus a test that scans the overlay's source for any writer, lock or log-file name.
- Known limit
- No test checks that capture survives an overlay crash; that follows from the design. The resource budget is measured by hand: 121.0 MiB and 1.78% of one core with capture, against 150 MiB and 2%.
How it was built
I set the goals and anti-goals, accepted sprints against machine-checkable criteria, with misses recorded as failures, and authorised the production migrations. The rule from the first sprint was that each task’s test cases and mutations were designed and reviewed before implementation. Claude Code agents wrote the code under an AI controller, and second agents reviewed the tasks, re-running the mutations in most sprints. Three phases and seven sprints landed as 349 commits on ten days between and .
What’s next
The loop this was built for is not closed yet. Deck versions are identified and listed; recording a card swap as an experiment and reporting its effect, with uncertainty, against two baselines is still to build.
Read my resume or get in touch.
Numbers as of . This page is unofficial Fan Content permitted under the Fan Content Policy. Not approved/endorsed by Wizards. Portions of the materials used are property of Wizards of the Coast. ©Wizards of the Coast LLC.