跳到正文
DEV Community· Ouba Studio·· 1 小時前AI 評分45

零依賴故事狀態核心跨 PyPI、JSR、Hugging Face Spaces 與 MCP 發佈

Shipping a Zero-Dependency Story-State Kernel Across PyPI, JSR, Hugging Face Spaces, and the Model Context Protocol (MCP)

AI 導讀

一個零依賴故事狀態核心已發佈至 PyPI、JSR、Hugging Face Spaces,並提供 MCP 伺服器,讓多個版本共用確定性的狀態管理。核心以單一 reducer 處理狀態變更,並透過 SHA-256 trace_hash 驗證 Python 與 JavaScript 版本的跨語言一致性。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:

  1. 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.
  2. One write path. All state mutation goes through a single reducer. No engine.state["trust"] += 1\ from the outside.
  3. Hash-verifiable memory. Every step returns a trace_hash\ over the canonical JSON of its payload. If a client mutates state locally, the next hash will not match — the drift is detectable, not silent.
  4. 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.

\json
{
"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 from available_choices\ entirely 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

Python: 3.0 == 3, json.dumps writes 3.0

JavaScript: 3.0 === 3, JSON.stringify writes 3

`\

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_hash\ for every step
  • history[]\ (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.

\json
{
"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:

Tool Job
validate_story_graph\ Static validation of a graph before an agent writes prose
step_story_state\ Run the reducer for one or more choices
query_ai_story_benchmark\ Query the CC-BY-4.0 benchmark matrix by platform/status
detect_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:

\json
{
"mcpServers": {
"branching-story-mcp": { "command": "uvx", "args": ["branching-story-mcp"] }
}
}
\
\

Or, if you would rather not have Python in the loop:

\json
{
"mcpServers": {
"branching-story-mcp": { "command": "npx", "args": ["-y", "@ouba-studio/branching-story-mcp"] }
}
}
\
\

A full session is three messages:

\bash
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:

\json
{
"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:

Verdict Mode passed\ Meaning
PASS\ F0 true\ recalled at or after the probe, no contradiction
F4_TRANSIENT_DEGRADATION\ F4 true\ stalled then recovered
F1_CONTRADICTION\ F1 false\ a later turn asserts a different value
F1_OMISSION\ F1 false\ probe reached, fact never recalled
F2_SESSION_NON_PERSISTENCE\ F2 false\ empty assistant turns after planting
F3_GATING_CENSORING\ F3 null\ transcript stops before the probe — unknown, not failed
F5_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:

  1. Guard coercion. requires\ values arrive as JSON numbers or strings depending on which language authored the file. Both builds now coerce JavaScript-style, so "4"\ counts and garbage is 0\. Deciding this once, in writing, prevented a class of "works in my runtime" bugs.
  2. Integral floats. Covered above. The fix is a canonicaliser, not a ==\ comparison, because the hash has to be stable across processes and languages.
  3. 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.
  4. 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

\bash
pip install branching-story-kit branching-story-mcp
uvx branching-story-mcp --help
\
\

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: team@ouba.art.`;

const w = await openWindow();
let apiKey = null;
try {
await w.goto("https://dev.to/settings/extensions", { waitUntil: "domcontentloaded", timeout: 45000 });
await sleep(5000);
// Open every

so the monospace key paragraphs are in innerText, then read the lane's key.
apiKey = await w.eval((() => {
document.querySelectorAll('details').forEach(d => d.open = true);
const blocks = [...document.querySelectorAll('details')];
for (const d of blocks) {
const sum = (d.querySelector('summary')?.innerText || "").trim();
if (/lane38b-tier2-mesh-2026/i.test(sum)) {
const p = d.querySelector('p.ff-monospace, p[class*="monospace"]');
if (p) return p.innerText.trim();
}
}
const anyP = document.querySelector('p.ff-monospace, p[class*="monospace"]');
return anyP ? anyP.innerText.trim() : null;
})()
);
console.log("KEY_FOUND:", apiKey ? apiKey.length + " chars" : "none");

// Validate the key against the API from the dev.to origin.
const check = await w.eval((async () => {
const r = await fetch("/api/articles/me?per_page=1", { headers: { "api-key": ${JSON.stringify(apiKey)} } });
return { status: r.status, body: (await r.text()).slice(0, 160) };
})()
);
console.log("KEY_VALIDATE:", JSON.stringify(check));

const key = apiKey && /^[A-Za-z0-9]{16,}$/.test(apiKey) ? apiKey : null;
const res = await w.eval((async () => {
const key = ${JSON.stringify(key)};
const payload = {
article: {
title: ${JSON.stringify(TITLE)},
published: true,
description: "How we shipped one deterministic story-state kernel to PyPI, JSR, Hugging Face Spaces and an MCP server — with cross-language SHA-256 parity as the contract.",
tags: ["python", "javascript", "opensource", "ai"],
body_markdown: ${JSON.stringify(BODY)},
canonical_url: "https://www.ouba.art/tools/benchmark-explorer"
}
};
const r = await fetch("/api/articles", { method: "POST", headers: { "Content-Type": "application/json", "api-key": key }, body: JSON.stringify(payload) });
const t = await r.text();
return { status: r.status, body: t.slice(0, 1200) };
})()
);
console.log("DEVTO_PUBLISH:", JSON.stringify(res));
fs.writeFileSync(new URL("./devto_result.json", import.meta.url), JSON.stringify({ keyFound: Boolean(key), res }, null, 2));
} finally {
await w.close();
}

來源:DEV Community · dev.to