Story Mode Engine

Story Mode Engine MCP Reference

Commit 7c7046d

Unified Model Context Protocol guide for inspecting, validating, and authoring .sme narrative RPG projects across desktop, web preview, and headless CLI workflows.

Raw Markdown (mcp.md)llms.txtJSON Schemas (11)Agent Skill (Pending Sync)Site /llms.txtSynced 2026-11-24

Quick Connect

Native stdio via StoryModeEngine.Mcp or local Streamable HTTP at http://127.0.0.1:47831/mcp

MCP 2025-03-26
%APPDATA%\Claude\claude_desktop_config.json

Connect Claude Desktop to the zero-Node StoryModeEngine.Mcp binary (or copy exact install path from the MCP status pill inside Story Mode Engine).

{
  "mcpServers": {
    "storymodeengine": {
      "command": "StoryModeEngine.Mcp",
      "args": []
    }
  }
}
Table of Contents (42 sections)

Story Mode Engine exposes a unified Model Context Protocol (MCP) surface across its native desktop workbench (.NET 10 + Avalonia 11 + SkiaSharp), its Vite web preview, and standalone stdio CLI hosts.

Any MCP-capable client or LLM can connect to inspect .sme projects, author scripts and game entities with strict cross-file validation, stage 16:9 Artist Stage Previews, capture PNG screenshots for visual verification, launch Godot 4.7 debug states, and drive 4-panel interactive Spotlight coach marks and multi-step guided tours across UI controls and canvas nodes.

This document is also served directly inside the protocol as resource sme://docs/guide.


1. Quick Orientation and Connection Modes

ModeExecutable or EndpointNode.js NeededBest Used ForLive GUI Support
1. Native Companion Binary (stdio)StoryModeEngine.Mcp (packaged next to StoryModeEngine)NoClaude Desktop, Cursor, Antigravity, standalone scripts on Windows, macOS, and LinuxAuto-bridges to open Story Mode Engine desktop app via mcp-session.json; runs headless .sme disk edits when closed
2. Desktop App Embedded HTTPhttp://127.0.0.1:47831/mcp (default port, fallback if occupied)NoHTTP Streamable MCP clients, direct curl / SDK calls while Story Mode Engine is openDirect in-process access to live Avalonia window on Dispatcher.UIThread
3. Vite Web Preview HTTPhttp://127.0.0.1:5173/api/studio/mcpYesBrowser preview workflows started with npm run dev or vite previewProxies live GUI commands over SSE to open /studio.html tabs
4. TypeScript Standalone CLI (stdio)npm run mcp (tsx src/mcp/cli.ts)YesRepo contributors testing Zod v4 tools in CI or bridging Desktop/Web sessions from terminalAuto-bridges to open Story Mode Engine desktop app or web preview via mcp-session.json

Decision Rule: Which Mode Should I Use?

  • If you installed Story Mode Engine (Windows, macOS, or Linux): Configure your MCP client to spawn StoryModeEngine.Mcp (StoryModeEngine.Mcp.exe on Windows). It requires zero runtime dependencies, reads/writes .sme files headlessly when the app is closed, and automatically upgrades to live GUI + Spotlight + visual capture whenever Story Mode Engine is running.
  • If you are working inside the StoryModeEngine repository: Use npm run mcp for stdio clients or http://127.0.0.1:5173/api/studio/mcp during npm run dev.
  • When connected inside Story Mode Engine: Click the MCP pill in the status strip (topbar.mcp_status) to view the active port, copy-ready client JSON snippets, enable/disable toggle, and recent tool activity log.

2. Client Setup Recipes

Claude Desktop

Add storymodeengine to your claude_desktop_config.json:

  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json

Installed Story Mode Engine Desktop App (Recommended, Zero Node.js)

{
  "mcpServers": {
    "storymodeengine": {
      "command": "C:\\Users\\YOU\\AppData\\Local\\StoryModeEngine\\current\\StoryModeEngine.Mcp.exe",
      "args": []
    }
  }
}

On macOS/Linux, point "command" to the packaged StoryModeEngine.Mcp binary inside your app directory (or open the MCP Server and Artist Spotlight dialog from the MCP status pill inside Story Mode Engine and click Copy Config JSON to copy the exact installed path).

Optional Pre-Bound Project or Explicit URL Flags

{
  "mcpServers": {
    "storymodeengine": {
      "command": "StoryModeEngine.Mcp",
      "args": ["--project", "D:\\Games\\MyStory", "--url", "http://127.0.0.1:47831/mcp"]
    }
  }
}

Repository Source Setup (npm run mcp)

{
  "mcpServers": {
    "storymodeengine": {
      "command": "npx",
      "args": ["tsx", "D:\\StoryModeEngine\\src\\mcp\\cli.ts", "--project", "D:\\Games\\MyStory"]
    }
  }
}

Cursor (.cursor/mcp.json)

{
  "mcpServers": {
    "storymodeengine-stdio": {
      "command": "C:\\Users\\YOU\\AppData\\Local\\StoryModeEngine\\current\\StoryModeEngine.Mcp.exe",
      "args": []
    },
    "storymodeengine-http": {
      "type": "http",
      "url": "http://127.0.0.1:47831/mcp"
    }
  }
}

Antigravity / Generic mcpServers JSON

{
  "mcpServers": {
    "storymodeengine": {
      "command": "StoryModeEngine.Mcp",
      "args": ["--project", "/path/to/your-project"]
    }
  }
}

Claude Code CLI

claude mcp add-json storymodeengine '{"command":"StoryModeEngine.Mcp","args":["--project","/path/to/your-project"]}'

CLI Flags and Environment Variables

Both StoryModeEngine.Mcp and src/mcp/cli.ts support:

  • --project <dir-or-sme> (or -p <path> in TS CLI): Sets default projectRoot when tools omit projectRoot.
  • --url <http://127.0.0.1:PORT/mcp> (or -u <url> in TS CLI): Forces a specific running Studio HTTP endpoint.
  • SME_DEFAULT_PROJECT: Environment variable fallback for default project directory or .sme manifest file.
  • SME_MCP_URL: Explicit loopback HTTP endpoint override for stdio bridging.

Wire Protocol Examples (JSON-RPC 2.0)

Supported MCP protocol versions: 2025-03-26 (default) and 2024-11-05. Server identifier: serverInfo.name = "storymodeengine".

HTTP Streamable (POST http://127.0.0.1:47831/mcp)

curl -s -X POST http://127.0.0.1:47831/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26"}}'
curl -s -X POST http://127.0.0.1:47831/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sme_validate_and_lint","arguments":{}}}'

NDJSON (stdio over stdin/stdout)

{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26"}}
{"jsonrpc":"2.0","method":"notifications/initialized"}
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
{"jsonrpc":"2.0","id":3,"method":"resources/read","params":{"uri":"sme://docs/guide"}}
{"jsonrpc":"2.0","id":4,"method":"prompts/get","params":{"name":"audit_project_health","arguments":{"chapter":"1"}}}

Health check endpoint (GET without running a tool):

  • Story Mode Engine Desktop App: GET http://127.0.0.1:47831/mcp/health
  • Story Mode Engine Web Preview: GET http://127.0.0.1:5173/api/studio/mcp/health

3. Session Discovery (mcp-session.json) and Security Guardrails

Session Auto-Discovery Paths and Priority Order

When StoryModeEngine.Mcp or npm run mcp starts, stdio requests resolve live Story Mode Engine endpoints in this priority order:

  1. --url CLI argument
  2. SME_MCP_URL environment variable
  3. Desktop app session file (mcp-session.json inside SettingsStore.SettingsDirectory):
    • Windows: %APPDATA%\StoryModeEngine\mcp-session.json
    • macOS: ~/Library/Application Support/StoryModeEngine/mcp-session.json
    • Linux: $XDG_CONFIG_HOME/StoryModeEngine/mcp-session.json or ~/.config/StoryModeEngine/mcp-session.json
  4. Workspace Vite session file (walking upward from current working directory): <repo>/artifacts/.mcp-session.json

Session JSON fields:

{
  "url": "http://127.0.0.1:47831/mcp",
  "healthUrl": "http://127.0.0.1:47831/mcp/health",
  "port": 47831,
  "pid": 12345,
  "runtime": "avalonia-desktop",
  "mode": "http",
  "projectRoot": "D:/Games/MyStory",
  "version": "0.2.8"
}

Offline vs. Live Proxying Behavior

  • sme_* project tools run locally on disk even when no Studio window is open. Whenever a live Studio session IS detected and matches the edited projectRoot, project/asset mutations automatically ask Studio to refresh safely.
  • studio_* GUI tools (studio_navigate, studio_spotlight, studio_stage_artist_preview, studio_capture_visual_preview, etc.) require a running Studio GUI. If no live Studio window is reachable, they return a clear actionable error telling the user to launch Studio.

Built-In Security and Safety Guardrails

  1. Strict Loopback Binding (127.0.0.1): Embedded HTTP servers never bind to 0.0.0.0 or LAN interfaces.
  2. DNS Rebinding and CSRF Protection (HTTP 403): Requests with non-loopback Host headers (anything other than 127.0.0.1, localhost, or [::1]) or non-loopback Origin headers are rejected immediately with 403 Forbidden.
  3. Pre-Write Cross-File Validation: Every sme_* edit validates the complete ProjectBundle (validateProjectBundle in TS, SmeProjectValidator.Validate in C#) BEFORE writing to disk. Invalid changes leave files untouched and return structured errors.
  4. Explicit Confirmation for Destructive / Remote Operations: sme_delete_script, sme_delete_dialogue_node, sme_delete_character_pose, sme_delete_hub_entity, sme_delete_topdown_building, sme_delete_item, sme_delete_knowledge, sme_delete_minigame, sme_delete_entity, sme_delete_snapshot, and sme_git_push fail unless confirm: true is passed.
  5. Dirty-State Protection: studio_open_project and studio_reload_project refuse to overwrite unsaved edits in the Studio UI unless force: true is supplied, and automatic background reloads preserve dirty user edits cleanly.
  6. Synchronous UI Re-entrancy Lock (AsyncActionGate): UI mutations block overlapping clicks, modal saves, and Spotlight dismissals while an async action is running.
  7. Windows Piped Stdio UTF-8 BOM Tolerance: Both McpStdioHost.cs and src/mcp/cli.ts strip leading \uFEFF characters on incoming stdin lines.

4. .sme Project Mental Model for LLMs

Directory Anatomy

my-story/
  my-story.sme            # Root ProjectManifest (or <slug>.storymodeengine / project.json)
  characters.json         # Cast, startingStats, bossConfig, per-character poses, and outfit pose slots
  assets.json             # ONLY place mapping semantic descriptor keys -> relative asset files
  art-manifest.json       # Auto-distilled inventory of fulfilled vs. missing asset slots
  scripts/*.json          # DialogueScript files (10 node types)
  hubs/*.json             # 2.5D JRPG / 2D exploration HubDefinition scenes
  minigames/*.json        # Registered MinigameManifest configurations
  items.json              # Optional trinkets, boss relics, consumables, key items
  knowledge.json          # Optional per-learner Truths & Insights
  campaign.json           # Optional multi-chapter structure + POV rotation rules
  saves/*.json            # Save snapshots and _godot_launch.json
  assets/...              # Concrete PNG, SVG, WebP, OGG, MP3, WAV, MP4, WebM, OGV files

Critical Domain Invariants

  • Semantic Asset Addressing Only: Scripts, hubs, and minigames NEVER reference file paths directly. They reference semantic descriptors (or upload via sme_upload_asset with a descriptor key like environment:town_square:default or character:companion:default:vn_portrait:neutral).
  • Node Types (All 10 Supported by sme_upsert_dialogue_node):
    1. line: { type: "line", speaker?: { characterId, expression, position }, listener?: { characterId, expression, position }, text, presentation?, background?, bgmCue?, sfxCue?, combatMode?, next? }
    2. choice: { type: "choice", prompt?, speaker?, choices: [{ id, label, condition?, next }], background? }
    3. branch: { type: "branch", branches: [{ condition, next }], defaultNext? }
    4. mutate: { type: "mutate", mutations: [...], next }
    5. transition: { type: "transition", background?, bgmCue?, effect?, durationMs?, next }
    6. cinematic: { type: "cinematic", mode: "video" | "timeline", title?, skippable?, skipLabel?, durationSec?, initialColor?, persistBackground?, video?, poster?, volume?, muted?, events?: [{ id, atSec, durationSec?, easing?, action, ... }], mutations?, next } (supports 10 timed actions: set_image, fade, focus, camera, caption, play_bgm, stop_bgm, play_sfx, effect, mutate, auto-advancing to next on completion)
    7. tiered_stat_check: { type: "tiered_stat_check", prompt?, speaker?, approaches: [{ id, label, stat, cleanThreshold, costlyThreshold, nextClean, nextCostly, nextFail, ... }] }
    8. launch_exploration: { type: "launch_exploration", hubId, objectiveHint?, onReturn }
    9. launch_minigame: { type: "launch_minigame", minigameId, params?, onWin?, onLose?, onDraw?, onQuit?, onComplete? }
    10. end: { type: "end", nextScriptId?, returnToHub?: boolean }
  • Outgoing Edge Ports (sme_rewire_dialogue_edge, sme_draw_connected_node):
    • Scalar ports: next, defaultNext, onReturn, onWin, onLose, onDraw, onQuit, onComplete
    • Choice option ports: choice:<choiceId>, or choice:new (appends a new choice option, optionally named via choiceLabel)
    • Branch arm ports: branch:<zeroBasedIndex>, or branch:new (appends a new condition branch arm)
    • Stat-check outcome ports: approach:<approachId>:clean, approach:<approachId>:costly, approach:<approachId>:fail
  • Sticky Scene Background Precedence (Visual Key & Node Canvas):
    1. explicit node background or cinematic initial frame (override)
    2. upstream transition background or cinematic (persistBackground: true) final background along incoming edges (transition)
    3. script defaultBackground (script_default)
    4. exploration hub backdrop on launch_exploration nodes (hub)

5. Complete Tool Reference (74 Tools)

Omit projectRoot whenever a project is already open in Studio or set via --project / SME_DEFAULT_PROJECT.

Project Discovery, Configuration, and Health (6 Tools)

Tool NamePurposeKey Arguments (* = required)Returns / Notes
sme_list_projectsList known .sme projects (recent Studio folders / workspace projects).(none){ activeProjectRoot, projects }
sme_create_projectCreate a starter .sme project directly via <dir>/<slug>.sme OR slug + parentDir.filePath OR slug + parentDir; optional name, description, companionNameCreates starter script, companion, hub, minigame, and manifest
sme_get_project_summaryInspect project metadata, entity counts, asset totals, and balance error/warning counts.projectRoot?Concise overview before full reads
sme_get_project_bundleRead a filtered section or full project bundle.projectRoot?, section (project|characters|scripts|hubs|minigames|items|knowledge|campaign|assetCatalog|all), id?Filter with section + id to keep payloads small
sme_update_project_configUpdate project metadata, initial entry mode/script/hub, or RPG config (affinityMode, deathMode, onPlayerDefeat, weakenedStatPenalty, stats, synergies, theme, titleMenu).projectRoot?, name?, description?, initialMode? (dialogue|hub), initialScriptId?, initialHubId?, config?Validated before save
sme_validate_and_lintRun strict cross-file schema validation, reachability / Balance Linter (stat checks, data-driven perimeter posts, dynamic POV/boss reachability, meeting coverage, boss knowledge/exploit audits), and optional chapter POV matrix.projectRoot?, matrixChapter?Check this before declaring any project edit done

Export and Issue Tracking (2 Tools)

Tool NamePurposeKey Arguments (* = required)Returns / Notes
sme_export_manifestExport standalone .sme root manifest JSON (matching Studio Export .sme).projectRoot?, destinationPath?Writes .sme/.storymodeengine/.json file when destinationPath given, always returns manifestJson
sme_submit_feature_requestSubmit a feature request or bug report (routes to Linear if LINEAR_API_KEY is set, else local draft).title*, details*, requestType?, targetArea?, projectRoot?Automatically attaches live Studio tab/node context when connected

Dialogue Scripts, Nodes, Edges, and Social Scenes (9 Tools)

Tool NamePurposeKey Arguments (* = required)Returns / Notes
sme_list_scriptsList all dialogue scripts with title, entry node, node count, and default background status.projectRoot?Quick index of scripts/*.json
sme_get_scriptRead full script JSON PLUS computed flow layout, unreachable node IDs, and sticky resolved backgrounds.scriptId*, projectRoot?Shows exact graph topology and inherited backgrounds
sme_upsert_scriptCreate or replace a full DialogueScript JSON object.scriptId*, script*, setAsInitial?, projectRoot?Cross-file validated before disk write
sme_delete_scriptDelete a dialogue script (confirm: true required).scriptId*, confirm* (true), projectRoot?Refuses if referenced by initialScriptId or campaign/other scripts
sme_upsert_dialogue_nodeAdd or update any of the 10 node types inside an existing script.scriptId*, nodeId*, node*, setAsEntry?, projectRoot?Cross-file validated before disk write
sme_delete_dialogue_nodeDelete a dialogue node from a script (confirm: true required).scriptId*, nodeId*, confirm* (true), projectRoot?Fails on entry node or dangling references
sme_draw_connected_nodeCreate a new default dialogue node of any of the 10 types and wire an outgoing port from fromNodeId to it atomically (splicing any replaced target to preserve flow).scriptId*, fromNodeId*, nodeType*, nodeId?, port?, choiceLabel?, node?, projectRoot?Mirrors Studio drag-to-draw workflow; rejects end source nodes
sme_rewire_dialogue_edgeRewire an outgoing port on fromNodeId to toNodeId.scriptId*, fromNodeId*, toNodeId*, port?, choiceLabel?, projectRoot?Supports next, defaultNext, onReturn, onWin, onLose, onDraw, onQuit, onComplete, choice:<id>, choice:new, branch:<i>, branch:new, approach:<id>:clean|costly|fail
sme_create_social_sceneCreate a standardized chapter POV x NPC conversation script (<povId>_talks_to_<npcId>_ch<N> or _m<M>).chapter*, povId*, npcId*, meeting? (1..10), title?, openingLine?, defaultBackground?, projectRoot?Preserves existing script safely if already created
sme_scaffold_social_meetingsScaffold Meeting 1, 2, and 3 branching social scripts with choices and affinity mutations for a POV x NPC pair.chapter*, povId*, npcId*, meetings? ([1,2,3]), defaultBackground?, overwrite?, projectRoot?Skips existing meeting scripts unless overwrite: true

Characters, Hubs, Minigames, Items, Knowledge, and Campaign (30 Tools)

Tool NamePurposeKey Arguments (* = required)Returns / Notes
sme_list_charactersList cast members, playable/role flags (playable, initiallyPlayable, inSocialRoster, canBeBoss), starting stats, bossConfig, effective poses, and variant IDs.projectRoot?Read before authoring dialogue speakers
sme_upsert_characterCreate or update a CharacterDefinition in characters.json (auto-syncs poses across outfits if supplied).characterId*, character*, projectRoot?Cross-file validated
sme_upsert_character_variantCreate or update an outfit variant, synced pose slots, hub animations, or minigame actors.characterId*, variantId*, variant*, setAsDefault?, projectRoot?Auto-updates distilled manifest slots
sme_upsert_character_poseCreate or update a full character POSE definition (displayName, mood, framing, facing, artBrief, mediaType, rigSpec, tags, stageTransform) and sync all outfits on that character.characterId*, poseId*, pose*, projectRoot?Ensures every outfit gets a slot for this pose
sme_delete_character_poseDelete a character POSE definition and remove its synced slot across all outfits (confirm: true required).characterId*, poseId*, confirm* (true), projectRoot?Refuses deleting the last remaining pose
sme_list_hubsList exploration hubs (2_5d_jrpg, top_down_2d, hotspot_nodes), pitch, ground color, hasTopDownMap, building counts, movement style, and entities.projectRoot?Hub index
sme_upsert_hubCreate or update a HubDefinition (hubs/<id>.json), including scene3d and topDown2d grids/buildings.hubId*, hub*, projectRoot?Supports 2.5D camera/ground and Top-Down 2D grids
sme_upsert_hub_entityCreate or update an interactive NPC, door (triggerMode: "walk_in", exitOffset), kiosk, portal, or inspectable entity inside a hub.hubId*, entityId*, entity*, projectRoot?Cross-file validated
sme_delete_hub_entityDelete an entity from a hub (confirm: true required).hubId*, entityId*, confirm* (true), projectRoot?Validates hub integrity before saving
sme_paint_topdown_tilesPaint NES/GameBoy top_down_2d map tiles and/or fill the grid with a base tile type.hubId*, fillTile?, tiles? ([{ col, row, tile }]), projectRoot?Auto-initializes 20x14 grid and syncs bounds
sme_upsert_topdown_buildingCreate or update a solid building footprint and optional linked walk_in doorway HubEntity on a top_down_2d hub.hubId*, buildingId*, building*, ensureDoorEntity?, dialogueScriptId?, projectRoot?Keeps building footprint and door alignment in sync
sme_delete_topdown_buildingDelete a building from a top_down_2d hub (confirm: true required) and optionally remove its linked doorway entity.hubId*, buildingId*, confirm* (true), deleteLinkedDoorEntity?, projectRoot?Cleanly updates buildings and entities
sme_list_miniscene_templatesList all 14 built-in exploration, RPG combat, and tabletop/arcade mini-scene templates.(none)Use returned id in sme_add_miniscene_from_template
sme_add_miniscene_from_templateInstantiate any of the 14 mini-scene templates and optionally wire it into a script.templateId*, id*, name?, wireMode? (append_node|wire_after_selected|attach_to_choice|standalone_only), scriptId?, selectedNodeId?, returnNodeId?, participantCharacters?, projectRoot?Creates hub/minigame/stat-check + wiring node
sme_list_minigamesList registered MinigameManifest files (minigames/*.json).projectRoot?Returns IDs, minigameType, templateType, godotScenePath, participants
sme_upsert_minigameCreate or update a MinigameManifest JSON object (supports posts[] defense configs, dieSides, startingComposure, exposeDamage, allyAssistThreshold, maxCardsPerTurn, and handSize).minigameId*, minigame*, projectRoot?Validates participants, statIds, & asset descriptors
sme_delete_minigameDelete a minigame manifest and clean up minigames/<id>.json (confirm: true required).minigameId*, confirm* (true), projectRoot?Fails if any dialogue node or campaign chapter still references it
sme_init_campaignInitialize a composable starter campaign.json on a project without one (or overwrite with overwrite: true).title?, prologueScriptId?, epilogueScriptId?, firstChapterTitle?, conversationBudget?, overwrite?, projectRoot?Sets files.campaign and writes Chapter 1 steps
sme_upsert_campaign_chapterCreate or update a CampaignChapter entry in campaign.json (supports legacy slots and composable steps[], completionCriteria, nextChapterRules, posts[], secrets_deck, and duel/deck tuning).chapter*, projectRoot?Auto-initializes campaign.json if absent
sme_get_campaign_flowInspect normalized chapter step sequences, completion criteria, conditional transitions, and social/POV rules.projectRoot?Normalizes legacy chapters into ordered steps[]
sme_upsert_chapter_stepCreate, update, or reorder a CampaignChapterStep inside a chapter (normalizing legacy chapters if needed).chapterId*, step*, insertAtIndex?, projectRoot?Supports all 8 step types and completion criteria
sme_update_campaign_rulesUpdate campaign-level rules or chapter completionCriteria, nextChapterRules, socialMode, socialHubId, and povSwitch guardrails.title?, prologueScriptId?, epilogueScriptId?, gameOverScriptId?, socialRules?, chapterId?, completionCriteria?, nextChapterRules?, socialMode?, socialHubId?, chapterGameOverScriptId?, povSwitch?, projectRoot?Also syncs povSwitch patch to pov_switch steps
sme_delete_campaign_chapterDelete a chapter from campaign.json (confirm: true required).chapterId*, confirm* (true), projectRoot?Refuses deleting the last remaining chapter
sme_delete_chapter_stepDelete a composable step from a chapter (confirm: true required).chapterId*, stepId*, confirm* (true), projectRoot?Refuses deleting the last remaining step
sme_upsert_itemCreate or update a trinket, boss relic, key item, or consumable in items.json (supports statBonuses, combatEffects, and synergyTag).itemId*, item*, projectRoot?Auto-initializes items.json if absent
sme_delete_itemDelete an item or boss relic from items.json (confirm: true required).itemId*, confirm* (true), projectRoot?Refuses deleting items still referenced by boss relicId
sme_upsert_knowledgeCreate or update a Truth or Insight in knowledge.json (relatedCharacterId, onLearnScriptId, confrontationScriptId, confrontationCondition).knowledgeId*, entry*, projectRoot?Auto-initializes knowledge.json if absent
sme_delete_knowledgeDelete a Truth or Insight entry from knowledge.json (confirm: true required).knowledgeId*, confirm* (true), projectRoot?Refuses deleting entries still referenced by truthId / truthAutoCleanWin
sme_update_initial_statePatch project.initialState (activeCharacterId, currentChapter, currentPhase, flags, relationships, characterVariants, location, inventory).initialState*, projectRoot?Merges fields & validates
sme_delete_entityDelete a character, character_variant, hub, hub_entity, item, knowledge, or campaign_chapter (confirm: true required).entityType*, id*, parentId? (required for character_variant & hub_entity), confirm* (true), projectRoot?Refuses deleting dangling references, last variant, or active defaultVariant

Distilled Art Manifest and Asset Files (3 Tools)

Tool NamePurposeKey Arguments (* = required)Returns / Notes
sme_get_art_manifestFilter art-manifest.json slots by fulfillment status, category, character, or substring search.projectRoot?, status? (all|missing|fulfilled), category? (all|character|environment|minigame|ui_audio), characterId?, search?Inspect before uploading art/audio
sme_upload_assetWrite PNG/SVG/JPG/WebP/OGG/MP3/WAV/MP4/WebM/OGV asset into assets/, register descriptor key in assets.json, and re-distill.descriptorKey*, mediaType*, category*, filename? (required with base64Data), base64Data? OR sourceFilePath?, projectRoot?Provide either sourceFilePath or base64Data
sme_preview_asset_imageReturn an MCP image content block (png/jpg/webp/svg) for a fulfilled visual asset so vision LLMs can inspect it.assetKey*, projectRoot?Accepts semantic descriptor key or relative path

Save Snapshots, Git, and Godot 4.7 (11 Tools)

Tool NamePurposeKey Arguments (* = required)Returns / Notes
sme_list_savesList all saved snapshots under saves/.projectRoot?Includes metadata, chapter, phase, POV
sme_save_snapshotWrite a save snapshot JSON into saves/ from a full saveFile or launch parameters + playtest boosts.name*, saveFile?, chapter?, phase?, povId?, scriptId?, nodeId?, hubId?, minigameId?, statBonus?, affinityBonus?, learnAllKnowledge?, label?, projectRoot?Great for repeatable mid-game regression fixtures
sme_delete_snapshotDelete a snapshot file under saves/ (confirm: true required).filename*, confirm* (true), projectRoot?Requires confirm: true
sme_git_statusInspect Git repo initialization, branch, remote, ahead/behind counts, and changed files.projectRoot?Maps directly to Tab 7 status strip
sme_git_initInitialize a Git repository in the project directory.projectRoot?Safe no-op/init
sme_git_pullPull latest commits from remote inside the project Git repository.projectRoot?Auto-refreshes open Studio UI on change
sme_git_commitStage all project changes and create a commit.message*, projectRoot?Follows repo commit hygiene
sme_git_pushPush local commits to configured remote (confirm: true required).confirm* (true), projectRoot?Requires confirm: true
sme_godot_statusInspect saved/detected Godot 4.7 executable and bundled/workspace godot/ runtime dir.projectRoot?Run before launching Godot
sme_configure_godotSave or clear the local Godot 4.7 executable path (binaryPath: "" resets to auto-detect).binaryPath*Returns refreshed godot status object
sme_launch_godotWrite saves/_godot_launch.json (from snapshotFilename, custom saveFile, or chapter/phase/POV/boost args) and optionally launch Godot 4.7.projectRoot?, writeOnly?, ignoreLaunchSave?, binaryPath?, snapshotFilename?, saveFile?, targetMode?, chapter?, phase?, povId?, scriptId?, nodeId?, hubId?, minigameId?, statBonus?, affinityBonus?, learnAllKnowledge?, label?Use writeOnly: true in automated headless workflows

Live Studio GUI, 16:9 Artist Stage, Capture, and Spotlight (12 Tools)

Tool NamePurposeKey Arguments (* = required)Returns / Notes
studio_get_ui_stateRead active tab, selections, isDirty, isBusy, openModal, Spotlight status, manifest summary, lint counts, Git status.(none)Always inspect isDirty / isBusy before destructive Studio UI calls
studio_open_projectOpen a folder or .sme manifest in the live Studio window.projectPath*, force?Refuses while isDirty unless force: true
studio_reload_projectReload the open project from disk into the live Studio UI.force?Refuses while isDirty unless force: true
studio_save_projectTrigger Save Project in the live Studio window.(none)Validates and persists unsaved Studio UI edits
studio_navigateSwitch workspace tab/sub-tab, select script/node/character/hub/asset, zoom/pan canvas, toggle Visual Key or Reference card, and set Artist filters.tab? (story|characters|artist|exploration|campaign|saves|git), castSubTab? (characters|items|knowledge), scriptId?, nodeId?, characterId?, hubId?, assetKey?, canvasZoom? (0.4..2.0), resetCanvasView?, centerOnNodeId?, showVisualKey?, showInspectorReference?, assetFilter? (all|missing|character|environment|minigame|ui_audio|audio), assetCharacterFilter?, assetSearch?Clean programmatic navigation
studio_stage_artist_previewSwitch to Asset Preview and compose a 16:9 live VN scene composition (applying pose stageTransform if set), or reset override.assetKey?, backgroundAssetKey?, characterId?, variant?, expression?, pose?, listenerCharacterId?, speakerLabel?, dialogueText?, audioAssetKey?, clearOverride?Non-destructive visual composition check
studio_list_ui_targetsReturn all 61 static Spotlight targets + 8 dynamic target patterns with live currentlyVisible flags.(none)Inspect before running studio_spotlight
studio_spotlightShow a 4-panel dimmed cutout and explainer callout over any static target or dynamic entity/canvas node.target*, title*, message*, interactive?, placement? (auto|right|left|bottom|top), padding?, badge?Automatically switches tab and centers node if needed
studio_spotlight_tourLaunch a multi-step guided walkthrough (Back / Next / Done + auto-navigation + optional stagePreview per step).steps* ([{ target, title, message, interactive?, placement?, padding?, stagePreview? }]), startIndex?Ideal for onboarding artists & writers
studio_clear_spotlightDismiss active Spotlight or Guided Tour cleanly.(none)Fails if Studio is currently busy
studio_show_noticeShow a concise non-blocking message on the Studio status bar.message*, isError?Useful feedback after background tasks
studio_capture_visual_previewRender and return an MCP image/png block of stage_preview, node_canvas, or window for visual inspection.target? (stage_preview|node_canvas|window)Check alignment, typography, and stage composition directly

6. sme:// Resources and Prompts Reference

Static sme:// Resources (10)

URIMIME TypeContents
sme://docs/guidetext/markdownComplete docs/MCP.md manual (this guide).
sme://schemas/indexapplication/jsonIndex of all bundled Draft 2020-12 JSON Schema URIs.
sme://project/summaryapplication/jsonSame summary payload as sme_get_project_summary.
sme://project/art-manifestapplication/jsonDistilled art-manifest.json slots and fulfillment counts.
sme://project/missing-assetsapplication/jsonFiltered list of missing art/audio slots.
sme://project/balance-reportapplication/jsonFull sme_validate_and_lint validation + Balance Linter report.
sme://project/campaign-flowapplication/jsonNormalized chapter steps, completion criteria, conditional transitions, and social/POV rules from sme_get_campaign_flow.
sme://templates/minigamesapplication/jsonFull 14-template catalog (id, name, category, modeKind, godotScenePath, defaultParams).
sme://studio/ui-stateapplication/jsonLive StudioUiStateSnapshot (or { connected: false, runtime: "headless-stdio" } offline).
sme://studio/ui-targetsapplication/jsonCanonical catalog of all 61 static targets and 8 dynamic target patterns (currentlyVisible reflects live window if connected).

Resource URI Templates (2)

URI TemplateMIME TypeContents
sme://schemas/{filename}application/schema+jsonExact Draft 2020-12 JSON Schema for any .schema.json file (e.g. sme://schemas/project.schema.json, sme://schemas/dialogue.schema.json).
sme://project/scripts/{scriptId}application/jsonFull script + graph layout + sticky backgrounds for scriptId.

Built-In MCP Prompts (4)

Prompt NameOptional ArgumentsGuided Workflow
guide_artist_missing_artprojectRootInspect missing art/audio slots, focus Asset Preview, stage 16:9 compositions, and launch an artist Spotlight tour.
draft_branching_scenescriptId, premiseRead characters & layout, author/expand a branching VN scene, validate/lint cross-file refs, and spotlight the key decision node.
audit_project_healthprojectRoot, chapterValidate schemas, inspect chapter POV social coverage + Balance Linter, and highlight issues in Studio.
review_character_assetscharacterIdInspect character outfit/portrait fulfillment, preview images, stage 16:9 composition, and capture a PNG visual check.

7. Studio UI Spotlight Target Catalog (61 Static + 8 Dynamic)

Interactive vs. Non-Interactive Mode

  • interactive: false (default): All background controls and the cutout region are shielded; the artist reads the explainer card and clicks Next, Back, or Got it (or presses Escape when idle).
  • interactive: true: Pointer clicks pass directly through the cutout to the highlighted control (such as typing a pitch angle or picking a floor color) while surrounding panels remain dimmed and blocked.

Top Bar, Status Strip, and Tool Rail Targets (tab: "global")

Target IDControl
topbar.open_folderOpen Folder button
topbar.new_project+ New .sme project button
topbar.export_smeExport .sme manifest button
topbar.import_smeImport .sme manifest button
topbar.feature_requestFeature request / bug report button
topbar.saveSave project button
topbar.playtestGodot... (Playtest Anywhere) button
topbar.godot_settingsGodot 4.7 Engine Settings tool rail button
topbar.run_godotRun Game (F5) launch button
topbar.mcp_statusMCP status pill and settings dialog launcher

Workspace Tab Targets

Target IDTab
tab.storyNode Canvas tab
tab.charactersCast tab
tab.artistAsset Preview tab
tab.exploration2.5D Hub tab
tab.campaignMatrix tab
tab.savesSnapshots tab
tab.gitGit tab

Per-Tab Static Control Targets

TabTarget IDControl
storystory.outlinerScripts and nodes outliner dock
storystory.node_canvasInteractive Skia / SVG dialogue flow canvas
storystory.draw_mode_btnDraw Mode toggle button (D) for dragging outgoing transitions from cards or output nubs
storystory.visual_keyDocked Visual Key / Index legend (auto-expands on spotlight)
storystory.inspectorSelected node inspector dock
storystory.inspector_bg_cardSticky Scene Background preview & assignment card
storystory.inspect_bg_art_btnInspect BG Art quick-jump button
storystory.inspector_cinematicCinematic Sequencer card (16:9 preview, playback scrubber, video/timeline event editor)
storystory.inspector_branchVisual Conditional Branching builder card (branches, conditions, default fallback)
storystory.inspector_mutateVisual World State Mutations builder card (ordered mutations and next node)
storystory.inspector_transitionVisual Transition and Audio node editor (type, duration, color, direction, BGM/SFX)
storystory.inspector_referenceCollapsible Read-Only Reference card (auto-expands on spotlight)
storystory.add_miniscene_btn+ Mini Scene template wizard button
characterscharacters.listCast roster list and add-character box
characterscharacters.inspectorCharacter stats, boss config, character poses, and outfit pose slots
characterscharacters.role_flagsPlayable, roster, boss eligibility flags, name color, profile icon, and side portrait
characterscharacters.boss_profileToggleable Boss Profile config (weakStat, resistedStat, resolveMax, attackPower, relicId, battleScriptId)
characterscharacters.poses_sectionPer-character defined Poses list with + Add Pose dialog launcher
characterscharacters.add_pose_btn+ Add Pose button opening the Pose Definition modal
characterscharacters.outfits_sectionOutfit variants with synced upload and stage preview slots for every pose
characterscharacters.items_editorItems and Relics (items.json) CRUD editor (stat bonuses, combat effects, synergy tag)
characterscharacters.knowledge_editorKnowledge and Truths (knowledge.json) CRUD editor (expose damage/line, hooks, confrontation condition)
artistartist.stage_preview16:9 Live Artist Stage composition viewport
artistartist.filtersAsset category chips, character dropdown, and search box
artistartist.gridDistilled asset cards and Upload / Replace actions
artistartist.reset_stage_btnReset Stage Override button (visible during studio_stage_artist_preview)
explorationexploration.hub_listDefined 2.5D/2D exploration hubs list
explorationexploration.traversal_modeTraversal mode selector (2_5d_jrpg, top_down_2d, hotspot_nodes)
explorationexploration.camera_pitch2.5D Camera Pitch numeric control (5 to 85 deg)
explorationexploration.ground_color2.5D Ground Color swatch & hex input
explorationexploration.topdown_settingsTop-Down 2D grid size, tile size, movement style (tile_grid/smooth), render mode, and custom asset overrides
explorationexploration.topdown_painterInteractive NES/GBC tile palette, building stamper, spawn tool, and grid canvas
explorationexploration.topdown_buildingsBuilding footprints, roof styles, and linked walk-in doorway VN triggers
explorationexploration.hub_entitiesInteractive Hub Entities CRUD editor (NPCs, walk-in door triggers, visuals, conditions, 5-kind interaction)
explorationexploration.hub_obstaclesHub collision obstacle rectangles CRUD editor
explorationexploration.minigamesMini Scenes list & Godot launch actions
campaigncampaign.settingsCampaign rules (affinityMode, deathMode, onPlayerDefeat, stats, synergies, theme, chapters)
campaigncampaign.flow_mapVisual Macro Chapter Flow Map canvas showing prologue, chapters, steps, routes, and endings
campaigncampaign.chapter_inspectorSelected chapter Step Stack, completion criteria, conditional transitions, and POV switch rules
campaigncampaign.pov_matrixMulti-POV x NPC social coverage grid with 3-meeting scaffolding
campaigncampaign.balance_linterReachability and Balance Linter report
savessaves.listSaved snapshots grid (saves/)
gitgit.status_barGit branch, remote, ahead/behind, and dirty badges
gitgit.commit_boxGit commit message input, pull, commit, and push controls

Dynamic Prefix Targets (8)

PatternAuto-Navigation Behavior
node:<nodeId>Switches to story tab, selects owner script + node, centers graph canvas, cuts out exact node card
node:<scriptId>/<nodeId>Same as above targeting an explicit scriptId
script:<scriptId>Switches to story tab, selects script, highlights story.outliner
character:<charId>Switches to characters tab, selects character, highlights characters.inspector
asset:<assetKey>Switches to artist tab, clears filters, focuses assetKey card or artist.grid
hub:<hubId>Switches to exploration tab, selects hub, highlights exploration.hub_list
minigame:<minigameId>Switches to exploration tab and highlights exploration.minigames
snapshot:<filename>Switches to saves tab and highlights saves.list

8. Four Copy-Paste LLM Workflow Playbooks

Playbook 1: Bootstrap and Validate a Brand-New Game Project

[
  {"tool": "sme_create_project", "args": {"filePath": "D:/Games/LanternHarbor/lantern-harbor.sme", "name": "Lantern Harbor", "companionName": "Rowan"}},
  {"tool": "sme_upsert_character", "args": {"characterId": "harbor_keeper", "character": {"id": "harbor_keeper", "name": "Morgan", "role": "Harbor Master", "playable": false, "defaultVariant": "coat", "variants": {"coat": {"id": "coat", "displayName": "Storm Coat", "representations": {"vn_portrait": {"mediaType": "2d_static", "expressions": ["neutral", "stern"]}}}}}}},
  {"tool": "sme_upsert_dialogue_node", "args": {"scriptId": "opening_scene", "nodeId": "harbor_greeting", "node": {"type": "line", "speaker": {"characterId": "harbor_keeper", "expression": "neutral", "position": "right"}, "listener": {"characterId": "companion", "expression": "neutral", "position": "left"}, "text": "The tide brings strange cargo tonight.", "next": "start_town"}}},
  {"tool": "sme_rewire_dialogue_edge", "args": {"scriptId": "opening_scene", "fromNodeId": "after_game", "toNodeId": "harbor_greeting", "port": "next"}},
  {"tool": "sme_validate_and_lint", "args": {"matrixChapter": 1}}
]

Playbook 2: Artist Co-Pilot Visual Check and Interactive Spotlight Tour

  1. Call sme_get_art_manifest with { "status": "missing" } to find missing backgrounds, portraits, or audio cues.
  2. Call sme_upload_asset with a local file (sourceFilePath) or SVG/PNG base64Data.
  3. Call studio_stage_artist_preview to compose speaker + dimmed listener + backdrop + dialogue copy at 16:9 without touching story scripts.
  4. Call studio_capture_visual_preview with { "target": "stage_preview" } and inspect the returned PNG image for portrait cropping, contrast, or spacing.
  5. Call studio_spotlight_tour to walk the artist interactively through fixing pitch/color settings or inspecting background inheritance:
{
  "name": "studio_spotlight_tour",
  "arguments": {
    "steps": [
      {
        "target": "exploration.camera_pitch",
        "title": "Adjust 2.5D Isometric Pitch",
        "message": "Edit the camera tilt angle between 5 and 85 degrees directly through this cutout.",
        "interactive": true,
        "placement": "right"
      },
      {
        "target": "artist.stage_preview",
        "title": "Verify 16:9 Stage Composition",
        "message": "Review character portraits, speaker label, and background art together at 16:9.",
        "stagePreview": {
          "characterId": "companion",
          "expression": "neutral",
          "speakerLabel": "COMPANION CHECK",
          "dialogueText": "Lighting and crop verified at 16:9."
        }
      }
    ]
  }
}

Playbook 3: Create a Social Scene and Test Mid-Game with Boosts in Godot

  1. Call sme_create_social_scene with { "chapter": 1, "povId": "player", "npcId": "companion", "openingLine": "Before the investigation begins, let us compare notes." }.
  2. Call sme_save_snapshot with { "name": "ch1_social_boosted", "chapter": 1, "phase": "social", "povId": "player", "scriptId": "player_talks_to_companion_ch1", "statBonus": 3, "affinityBonus": 5, "learnAllKnowledge": true }.
  3. Call sme_launch_godot with { "snapshotFilename": "ch1_social_boosted.json", "writeOnly": true } (or omit writeOnly to spawn the Godot 4.7 window directly).

Playbook 4: Safe Dirty-State Editing Pattern

  1. Before calling any sme_* disk write while a user is actively editing in Studio, call studio_get_ui_state.
  2. If isDirty === true, call studio_save_project (with the user's consent) OR inform the user before making disk changes. Never call studio_reload_project with force: true unless intentionally discarding unsaved UI edits.

9. Troubleshooting and Automated Parity Policy

Common Errors and Fixes

  • Tool "studio_*" requires a running Story Mode Engine window: Open Story Mode Engine (or run npm run dev with studio.html open in a browser), confirm the MCP status pill is green, then retry.
  • HTTP 403 Forbidden non-loopback Host/Origin: Ensure requests target http://127.0.0.1:<port>/mcp with Host: 127.0.0.1:<port> (or localhost:<port>) and zero cross-origin non-loopback Origin headers.
  • Story Mode Engine has unsaved changes on studio_open_project / studio_reload_project: Call studio_save_project first or pass force: true only when discarding unsaved changes is intended.
  • Spotlight says target is not currently rendered/visible: Dynamic cards like story.inspector_bg_card require selecting a dialogue line/choice/transition node (studio_navigate({ nodeId })), and artist.reset_stage_btn is only visible while studio_stage_artist_preview override is active.
  • Cross-file validation failed before write: Fix missing characterId, environmentId, scriptId, hubId, minigameId, or broken outgoing node references reported in details.errors. On sme_delete_entity or sme_delete_minigame, rewire or delete referring nodes/chapters before removing the target entity.

Contributor MCP-First Parity Enforcement

Every PR in Story Mode Engine is verified by node scripts/check.mjs, whose checkMcpParityAndDocs() audit asserts:

  1. Exact parity across src/mcp/ and studio-avalonia/src/StoryModeEngine.Core/Mcp/ for all tool names (74), sme:// resources (10 static + 2 templates), prompts (4), and static UI target IDs (61).
  2. Complete coverage of every Avalonia [RelayCommand] and every web /api/studio/* endpoint inside src/mcp/capability-manifest.json.
  3. Every tool, resource URI, template URI, prompt, and static UI target ID is documented in docs/MCP.md, and docs/MCP.md + schemas/*.schema.json are bundled in both StoryModeEngine.Studio.csproj and StoryModeEngine.Mcp.csproj.