Shipping a Zero-Dependency Story-State Kernel Across PyPI, JSR, Hugging Face Spaces, and the Model Context Protocol (MCP)
In November 2026 we benchmarked ten consumer AI story apps with one deliberately boring test: plant a concrete fact at turn two, ask for it at turn fifteen.
A major product stayed perfectly fluent and on-persona for thirteen turns and then lost the fact. Four more never reached turn fifteen at all - signup walls and credit caps ended the session before the probe could be administered.
The preprint is State Drift in Consumer LLM Interactive Fiction (DOI 10.5281/zenodo.24549412); the data is CC-BY-4.0 on Harvard Dataverse. This post is about the fix we shipped, and what it takes to ship the same deterministic kernel to PyPI, JSR, a Hugging Face Space, and a Model Context Protocol server without the four builds drifting apart.
The constraint that shaped everything
A story engine for agents has one job an LLM cannot do for itself: be the authority on state. Everything else - prose, pacing, character voice - can be generated.
"Does the reader still have the amber ledger, and how much trust have they earned?" cannot, because a language model will answer fluently and wrongly.
So the design constraints were:
- Zero runtime dependencies. One module. Stdlib only. Python 3.10+, Node 18+. If an agent has to resolve a dependency tree to get deterministic state, it will vendor a stale copy instead.
- One write path. All state mutation goes through a single reducer. No
engine.state["trust"] += 1from the outside. - Hash-verifiable memory. Every step returns a
trace_hashover the canonical JSON of its payload. If a client mutates state locally, the next hash will not match - the drift is detectable, not silent. - Bit-identical cross-language behaviour. The Python and JavaScript builds must produce the same hash for the same inputs. Not "equivalent" - identical bytes.
That last constraint is where most of the engineering time went, and it is the part worth reading about if you maintain parallel implementations of anything.
The kernel
A story is a JSON graph: scenes, choices, effects, and guards.
{
"id": "the-midnight-bookshop",
"start": "start",
"initialState": { "spark": 1, "trust": 1, "item": "none" },
"scenes": {
"start": {
"title": "Rain on Bellweather Lane",
"body": "Your {{item}} waits on the counter.",
"choices": [
{ "label": "Take the mug", "next": "warm", "effects": { "spark": 2, "item": "Cardamom Tea" } },
{ "label": "Compare notes", "next": "warm", "effects": { "trust": 2 } }
]
},
"warm": {
"title": "Between the Stacks",
"body": "Trust={{trust}} Spark={{spark}}",
"ending": true
}
}
}
Two rules carry almost all of the semantics:
- Scalars add, everything else assigns.
{"trust": 2}increments the meter;{"item": "amber ledger"}replaces it. Numeric meters are cumulative because relationship state is cumulative in every interactive-romance system worth reading. Explicit operators ({"op": "append", "value": "..."},{"op": "delete"}) exist for the cases where you need them. - Guards filter, they do not grey out. A choice with
"requires": {"trust": 3}is removed fromavailable_choicesentirely when the threshold is unmet. Rendering it disabled leaks the existence of a state variable the author did not want to reveal, and it teaches players to grind.
remember() appends turn-stamped facts to a memory log - {"turn": n, "fact": "..."} - which is what the benchmark's planted-fact probe actually tests. export_save() / import_save() round-trip cursor, state, history and memory, so a session is a portable string.
Cross-language SHA-256 parity
The trace_hash is sha256(canonical_json(payload)), where canonical means sorted keys, no whitespace, and integral floats written as integers. That last clause is not decoration:
- Python:
3.0 == 3,json.dumpswrites3.0 - JavaScript:
3.0 === 3,JSON.stringifywrites3
Same number, different bytes, different hash. The canonicalizer therefore normalises 3.0 โ 3 on both sides before hashing.
The parity test in CI runs a fixed corpus of graphs and choice sequences through both builds and asserts equality of:
trace_hashfor every stephistory[](scene ids and effects applied)memory[](turn numbers and fact strings)
If anyone "fixes" the canonicaliser in one language, the corpus fails within one CI run. A mismatch is not a style issue - it is proof that a state transition diverged.
{
"verification": {
"algorithm": "sha256",
"canonicalization": "JSON with sorted keys, no whitespace, integral floats as integers",
"hash": "2eeba186fb99โฆ",
"note": "Recompute sha256 over the canonical JSON of payload; a mismatch means the story state was mutated outside this reducer."
}
}
Wrapping it in MCP
The Model Context Protocol server (branching-story-mcp) exposes the kernel as four tools and two resources over JSON-RPC 2.0 on stdio, newline-delimited, and nothing else ever touches stdout:
validate_story_graph- Static validation of a graph before an agent writes prosestep_story_state- Run the reducer for one or more choicesquery_ai_story_benchmark- Query the CC-BY-4.0 benchmark matrix by platform/statusdetect_state_drift- Classify a transcript against a planted fact
Plus two resources: the benchmark matrix and the schema. Every tool is annotated readOnlyHint: true, destructiveHint: false - the server is read-only by construction.
Install is a one-liner in any MCP client:
{
"mcpServers": {
"branching-story-mcp": {
"command": "uvx",
"args": ["branching-story-mcp"]
}
}
}
Or, if you would rather not have Python in the loop:
{
"mcpServers": {
"branching-story-mcp": {
"command": "npx",
"args": ["-y", "@ouba-studio/branching-story-mcp"]
}
}
}
A full session is three messages:
printf '%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"smoke","version":"0"}}}' \
'{"jsonrpc":"2.0","method":"notifications/initialized"}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \
| uvx branching-story-mcp
And the interesting call - stepping state with a prior memory log:
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "step_story_state",
"arguments": {
"story": {
"id": "midnight-bookshop",
"startScene": "arrival",
"initialState": { "spark": 1, "trust": 1 },
"scenes": { "...": "..." }
},
"choices": [0, "Open the folio"],
"state": { "trust": 2 },
"remember": ["My cat's name is Marmalade."]
}
}
}
Note what choices accepts: integer indexes, case-insensitive labels, or {index} / {label} objects. That is deliberate - agents rarely know the ordinal of the option they meant, but they almost always know the label.
The response carries final_scene, final_state, turns, per-step guards_evaluated / fired_guards / unmet_guards / effects_applied, available_choices[] for the landing scene, stopped_reason, and the trace_hash + verification block. A step that requests a guarded choice it has not earned is recorded with status: "guard_blocked" and leaves state untouched - the agent gets a structured explanation instead of a silently skipped transition.
detect_state_drift, or the taxonomy we actually needed
Classifying "the model forgot" turns out to have five distinct failure modes, and conflating them is why most AI-memory benchmarks are unusable. The tool returns a verdict per session:
passed- PASS - F0 true - recalled at or after the probe, no contradictionF4_TRANSIENT_DEGRADATION- F4 true - stalled then recoveredF1_CONTRADICTION- F1 false - a later turn asserts a different valueF1_OMISSION- F1 false - probe reached, fact never recalledF2_SESSION_NON_PERSISTENCE- F2 false - empty assistant turns after plantingF3_GATING_CENSORING- F3 null - transcript stops before the probe - unknown, not failedF5_PLATFORM_DELISTING- F5 null - delisting prevented the session
The null verdicts matter as much as the booleans. A session that never got to run is not evidence of anything, and scoring it as a failure inflates the apparent severity of the problem while hiding the more interesting one: four of ten products could not be tested at all.
Shipping the demo: Hugging Face Space + a static mirror
Two artefacts consume the same dataset, and both had to stay serverless:
- Hugging Face Space - the benchmark explorer runs entirely client-side against the published JSON. No backend, no keys, no build step beyond a static bundle. Spaces is the right home because it is the one host where a reviewer can open the demo and the model card side by side.
- Benchmark explorer on ouba.art - identical bundle, our domain. If Spaces is down or blocked in a reviewer's country, the evidence is still reachable.
The write-up itself is mirrored in four formats because different audiences genuinely read in different places: Internet Archive for the permanent copy, Scribd for readers, Gamma for a narrated walkthrough, and SpeakerDeck for classrooms.
What actually broke
Four bugs worth recording, in the order they happened:
- Guard coercion.
requiresvalues arrive as JSON numbers or strings depending on which language authored the file. Both builds now coerce JavaScript-style, so"4"counts and garbage is0. Deciding this once, in writing, prevented a class of "works in my runtime" bugs. - Integral floats. Covered above. The fix is a canonicaliser, not a
==comparison, because the hash has to be stable across processes and languages. - Framing. JSON-RPC on stdio is newline-delimited, and a client that pretty-prints its request across three lines will hang forever. The server reads a line at a time and rejects partial frames with
-32600; agents that log to stdout get an immediate, legible failure instead of a deadlock. - Clients that mutate locally. Some agent frameworks "helpfully" merge tool results into their own world model and then pass the merged object back. The hash mismatch surfaces it immediately - which is the whole point of making the memory verifiable rather than merely persistent.
Reproduce it
pip install branching-story-kit branching-story-mcp
uvx branching-story-mcp --help
Kernel: GitHub ยท PyPI ยท JSR ยท live docs and validator. MCP server: GitHub ยท PyPI ยท awesome-mcp-servers listing. Data: Dataverse DOI 10.7910/DVN/YEBHQR ยท Zenodo software DOI 10.5281/zenodo.24514910 ยท preprint DOI 10.5281/zenodo.24549412.
Code is MIT. Datasets are CC-BY-4.0. The kernel is 207 lines with no dependencies, and the hash is the contract.
Published by Ouba Studio - the team behind Ouba and the 2026 AI Story Apps Benchmark. Questions: t***@ouba.art.
Comments
No comments yet. Start the discussion.