mcp

v0.35.0
@statelyai/mcp Checked 19 hours ago Published 8 hours ago

Reusable Stately MCP server for XState machine tooling.

Validate, execute, explore, compare, convert, and visualize state machines from an MCP-compatible agent. Hosted and local servers advertise the Stately display name, description, website, and light/dark PNG icons through standard MCP initialization metadata. Icons are embedded data URIs, so local branding also works offline. Hosts choose which metadata they display; clients that omit icon support retain the server name. The Claude Apply channel uses the same branding with the title Stately Apply.

Summary extracted from the README.

Stately MCP

Validate, execute, explore, compare, convert, and visualize state machines from an MCP-compatible agent.

Hosted and local servers advertise the Stately display name, description, website, and light/dark PNG icons through standard MCP initialization metadata. Icons are embedded data URIs, so local branding also works offline. Hosts choose which metadata they display; clients that omit icon support retain the server name. The Claude Apply channel uses the same branding with the title Stately Apply.

Full editor extension

The authenticated editor HTTP route adds open_stately_editor, get_stately_flow_guidance, save_stately_models, create_stately_model, save_stately_check_result, get_stately_check_result, save_stately_proposal, get_stately_proposal, and check_stately_proposal_source, plus read-only get_stately_spec for the feature spec and get_stately_behavior_record for archived snapshots. create_stately_model is deprecated: call save_stately_models with one model instead. It is removed in the next minor release. See retirement and migration. The extension includes server instructions, a map_flows prompt and an explain_repo prompt (optional focus, default whole repository). The latter uses get_stately_flow_guidance with scope: "repository" to inventory source, save a cited architecture overview and meaningful flows, and explain failures, retries, scope and unknowns without requiring XState adoption. explain_repo is available when both get_stately_flow_guidance and save_stately_models are enabled.

New models saved with save_stately_models or deprecated create_stately_model receive semantic colors by default. Pass autoColor: false on the call to opt out. Existing colors and explicit neutral choices are preserved; labels without a clear semantic role stay neutral. Regenerating an existing model does not automatically recolor it. This MCP option is independent of browser editor settings.

save_stately_check_result saves a real /stately checker report with its native view in the connected account and project. Reuse machineId with its last-read revision after rechecking; a concurrent model edit rejects the save. Reports retain rule outcomes, bounds, counterexamples and variable snapshots; explicit report.documents appear in Checks and Documents. An artifact documentPath must resolve to a shared document with the exact bound SHA-256. Local file paths are references only: this tool does not read them, run a checker, or upload their contents. Project Documents applies presentation budgets with explicit omission notices; complete shared documents remain in each model's Checks panel. The combined graph and report must fit 200000 characters; oversized records fail before saving, with guidance to retain full external artifacts and supply an explicitly bounded view. The supplied view digest must still match.

get_stately_check_result reads that report and compares the model digest. Source freshness stays unknown until the coding host supplies current hashes for all declared source artifacts; the server compares those hashes without reading the workspace. Checks displays application test results separately from model checking. Recheck preserves intended graph edits as an immutable proposal, then requests the coding host through MCP Apps ui/message to reconcile the specification and rerun its real checker. Hosts without messaging show a copyable request. Results remain historical until a completed report is saved. Paths, labels and document contents remain untrusted data; the host must resolve the recorded inputs within its authorized workspace.

Saved formal models offer Recheck with agent, carrying a saved revision or immutable proposal and artifact provenance through the existing chat-message or Copy prompt flow. Sending a request does not run the checker. The agent reports bounded model checks and application replay separately. See formal rechecks.

explain_repo requests Documents with Repository overview.md selected. To request that presentation explicitly, pass presentation: { kind: "document", path: "Repository overview.md" } to save_stately_models, or to open_stately_editor with saved model IDs. Ordinary calls without presentation retain the normal graph-opening behavior. The full result and compact result carry the request; local and hosted links preserve it with document. Repeating a request reopens and reselects the document without discarding model drafts or resetting the same Diagram. Missing documents show an unavailable message and keep the document picker available.

The same saved models supply a readable repository overview in Documents, including the default project Diagram. Each flow explains states, transition events and guards, descriptions, evidence statuses, and citation explanations. Repository paths link to the recorded commit when supported. Feature paths link only when all mapped flows resolve within one project and agree on repository and revision. Explicit citation URLs retain their supplied targets. Sandboxed Documents opens source links through the host. Captured file hashes describe supplied bytes; source freshness remains unknown without a current-file comparison. Details stop at 40 states and 80 transitions per flow with omission counts; the source model and Model evidence.txt retain the supplied evidence. Both Documents are scoped to the active project. Without an active project, Model evidence.txt shows a select-project notice. On reopen, shared feature names use the newest valid inventory save time within their project. Regenerating a flow without a feature inventory preserves that inventory time. Legacy inventories without save times retain deterministic first-model precedence when recency is unavailable. Both prompts use the existing map, edit, apply, and regenerate loop. Comment tools add list_stately_comments, submit_stately_comment, reply_stately_comment, resolve_stately_comment, and tag_stately_comment. Machine readers can view configured comments; comments:write enables create, reply, resolution and tagging separately from editing. tag_stately_comment replaces a thread's entity tags (node:<id>, edge:<id>, annotation:<id>, block:<blockId>) and rejects keys that do not exist in the saved machine graph. Comment writes validate saved targets/revisions and capture server-derived context. The complete shared editor supports OpenAI global/thread entrypoints and fullscreen display. Tool discovery advertises the current content-hashed editor resource. Previously advertised editor hashes and ui://stately/editor.html serve the current editor, so cached host metadata survives deployments. Agents can map arbitrary application behavior into an XGraph with source evidence, save it in a linked project or personal Drafts, and open existing Stately models. The guidance tool directs the host agent to inspect its own accessible source, attach exact citations and uncertainty labels, and save an estimated flow. It performs no source reading or AI analysis itself. These estimates do not validate application behavior. Optional source snapshots record SHA-256 hashes of inspected working-tree files. Before implementation, the host reports current hashes to check_stately_proposal_source; changed files require a focused re-estimate and conflict review, while missing snapshots or unreported files leave freshness unknown. Unrelated commits do not invalidate matching files. The server compares host-reported hashes and cannot inspect or enforce source freshness itself.

Every project has a Diagram derived from its models' known invoke, spawn, and event-send relationships. Saving multiple flows opens that project Diagram and persists only the requested models. Diagram edits are limited to moving components and edge labels, and renaming components. These presentation changes are stored in this browser; they do not rename source machines or change topology. Click Open on a linked component to open its model. Each model retains its draft and viewport. Architecture is a built-in profile, not a separate package.

overview optionally saves an authored architecture document. It accepts an architecture-profile XGraph, a name, evidence, optional existing machineId, and links entries with nodeId and machine. Each machine identifies a flow in the same call by unique name or zero-based index. The server resolves references to saved model IDs. Authored architecture documents remain separate from the project Diagram. They change only through an explicit overview save; supply overview.machineId to replace one.

Explicit open_stately_editor.selectedMachineId takes precedence. Multi-model workspaces within one project otherwise open its Diagram. Workspace results publish selectedProjectDiagramId; links preserve it with projectDiagram. selected preserves an explicit model selection. The agent context identifies a project Diagram without inventing a machine ID and includes its displayed graph.

The server validates graphs and references before saving. Multi-model saves are sequential. Persistence failures report IDs already saved. Retry with those IDs to avoid duplicates. The full editor transport retains the feature inventory.

Source-derived named actions may omit parameter objects; the editor fills those with empty objects before rendering.

Stored Digraphs without a graph ID load using their root state ID. Existing graph IDs and stored definitions are preserved; loading does not write a migration.

Free authenticated accounts can save generated models and view them read-only. Single-machine results open directly on the canvas. The native Workspace panel appears for multi-machine results or explicit library browsing. Its close control hides it; the canvas More panels menu reopens it. Evidence lives in the Documents panel. A successful open_stately_editor({}) clears earlier operation errors. Single-machine views keep project navigation on the canvas through View diagram and Back to machine, preserving draft edits without opening a sidebar. Choose View diagram in the project's … or right-click menu. The project row is highlighted with a diagram icon while its Diagram is active. Project names expand or collapse their machines. Session models remain in their owning projects. The Diagram is always available, including for empty projects, and its components open their actual models. A small Stately mark follows the editor theme in the top-right canvas rail; there is no extra MCP header, title row, command bar, or standing temporary-storage notice. Panel controls and capture/review actions live on the canvas and reserve no rows above it. The chat host owns expansion. It collapses in narrow hosts and retains each model's draft when switching models. Proposal saving and chat handoff stay in the top-right canvas action chip. The Simulation panel is available; validation panels are disabled in this shell. Project navigation does not require an editing entitlement.

Editing, immutable proposal saves, and chat handoff require editing access plus project edit permission. The hosted adapter requires the verified Pro+ editor_sync:write entitlement. With teams:write, the unlinked-save hint also suggests linking a team project to share models with the team. Save creates a machine version with its baseline; source implementation is delegated to the active chat after a user clicks Apply. Stale models are rejected.

The editor can ask the connected coding agent to capture a live application's screens using the saved flow. The agent owns browser access, actions, and screen assertions. Stately records its reported results, transition coverage, and private screenshot references. Recrawl requires a click by default. The capture request checks the chat's exposed tools before browser work and reports missing capture tools with a connection/catalog refresh instruction. MCP editor states with screenshots default to Asset appearance. Details can override a state's appearance or set the root default inherited by descendants. Automatic recrawl is an explicit per-model setting. Review changes opens the graph comparison without adding an approval step before Apply. See live application captures. The runnable Playwright example binds transitions to actual browser actions and assertions, saves capture results through MCP, and verifies that a broken Retry control produces a mismatch and replay trace while preserving intended behavior.

Successful saves publish the immutable proposal version ID in the host's model context, so the agent can read the proposal or check source freshness without initiating implementation. Further edits clear the proposal from host context and mark the draft unsaved. Context updates preserve order, including edits during a pending save update.

Comments use the native panel, persist before explicit host-chat delivery, and require comments:write plus machine access. Agent replies return to the same thread with correlation; loads and synchronized replies do not request chat responses. Unsupported message hosts can still save comments.

Programmatic hosts opt in with a request-bound editorClient adapter; local stdio omits these tools. No credentials reach the iframe. See the editor workflow for routing, limits, and host validation requirements.

Two ways to run it

Local (stdio). npx @statelyai/mcp runs the server on your machine. Use it when you want the server in-process, or when you need to point the tools at your own Stately deployment.

Hosted (HTTP). https://mcp.stately.ai/mcp needs no local install and adds the hosted resource tools that read your Stately projects.

Both use Stately credentials by default. Testing guidance, report analysis and opted-in local execution run without a Stately credential or HTTP API call. list_machines and get_machine also run locally; other machine operations call the configured HTTP API. Stately's hosted API rejects unauthenticated calls with Missing authentication. A self-hosted API can define its own auth policy.

Protocol support

Stately MCP supports both the MCP 2026-07-28 protocol and legacy 2025 clients. Modern clients use stateless discovery instead of initialization sessions, receive the MCP Apps extension capability, and may cache the static tool and resource catalogs for five minutes. The hosted endpoint accepts the modern Mcp-Method and Mcp-Name routing headers. The stdio server negotiates the same modern protocol and falls back for legacy clients automatically.

Tool calls also preserve MCP trace context. Subscription streams are disabled because Stately's tool and resource catalogs do not change during a request. Tasks and multi-round-trip input remain available in the SDK for future tools that need long-running execution or additional client input; current tools are single-response operations and do not advertise unsupported workflows.

Local (stdio)

Add this to your MCP client configuration:

{
  "mcpServers": {
    "stately": {
      "command": "npx",
      "args": ["-y", "@statelyai/mcp"],
      "env": { "STATELY_ACCESS_TOKEN": "..." }
    }
  }
}

Or install it and run the stately-mcp binary directly:

npm install -g @statelyai/mcp
stately-mcp

Credentials are read from STATELY_ACCESS_TOKEN, STATELY_API_KEY, or the config written by statelyai login.

The API defaults to https://editor.stately.ai/api. Point it at a self-hosted deployment with STATELY_API_BASE_URL:

{
  "mcpServers": {
    "stately": {
      "command": "npx",
      "args": ["-y", "@statelyai/mcp"],
      "env": { "STATELY_API_BASE_URL": "https://stately.internal/api" }
    }
  }
}

Visualization results include a bare View in Stately: <url> line in their text and the same link as structuredContent.viewUrl, because some hosts (Claude Code among them) hand the model only structuredContent when a result carries one. Links use the API origin (https://editor.stately.ai by default); set STATELY_EDITOR_BASE_URL when the editor is served elsewhere.

Connect to the hosted endpoint

Choose your client and add Stately MCP using one of these methods. Each ends in a Stately sign-in; to run the server locally instead, see Local (stdio) above.

Codex

codex mcp add stately --url https://mcp.stately.ai/mcp
codex mcp login stately

Claude Code

claude mcp add --transport http stately https://mcp.stately.ai/mcp

Then open Claude Code, run /mcp, and complete Stately sign-in.

Cursor

Open Cursor Settings → MCP → Add new global MCP server, then add:

{
  "mcpServers": {
    "stately": {
      "url": "https://mcp.stately.ai/mcp"
    }
  }
}

Save the configuration and complete Stately sign-in when Cursor connects. To share the server with a project, put the same configuration in .cursor/mcp.json at the project root.

VS Code with GitHub Copilot

Create .vscode/mcp.json in your project:

{
  "servers": {
    "stately": {
      "type": "http",
      "url": "https://mcp.stately.ai/mcp"
    }
  }
}

Open the Command Palette and run MCP: List Servers, start stately, then complete Stately sign-in. For a personal configuration available in every workspace, run MCP: Open User Configuration instead.

Other MCP clients

Add a remote server using the Streamable HTTP transport and this URL:

https://mcp.stately.ai/mcp

Complete Stately sign-in when the client connects.

Machine input

Most tools accept a machine config object or a source document. Conversion accepts XState, SCXML, XGraph, legacy Stately DigraphDef, Mermaid, and D2 sources; target formats exclude DigraphDef and Mermaid. Validation also supports JSON and YAML.

validate_machine

Checks machine syntax and graph structure deterministically. It does not typecheck or execute XState source; use simulate_machine and generate_graph_paths to verify runtime behavior. A successful response contains ok and an issues array.

Use Stately to validate this machine:

createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { PAUSE: 'paused', STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});

convert_machine

Converts XState, SCXML, XGraph, legacy Stately DigraphDef, Mermaid, or D2 input to XState, SCXML, XGraph, or D2. The response contains the target format, converted content, and any warnings.

Use Stately to convert this machine to SCXML:

createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});
Use Stately to convert this SCXML machine to XState:

<scxml xmlns="http://www.w3.org/2005/07/scxml" name="player" initial="paused">
  <state id="paused">
    <transition event="PLAY" target="playing" />
  </state>
  <state id="playing">
    <transition event="STOP" target="stopped" />
  </state>
  <final id="stopped" />
</scxml>
Use Stately to convert this machine to D2:

createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});
Use Stately to convert this machine to XGraph:

createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});

diff_machines

Compares two machine documents structurally instead of comparing their source text. It returns a summary, the compatible normalized diff, and versioned semanticChanges; set includePatches to request applicable patches. Corresponding transitions remain paired when their source or target changes, and changed fields identify source, target, label, event, guard, actions, and other semantic data without layout or viewer details. hasChanges also covers supported non-structural changes; the node and edge counts remain structural. Generated patches preserve ordered actions/invokes and guarded transition priority, including explicit null/default resets and action parameter clearing.

Use Stately to compare these two versions of a machine and suggest patches:

Before:
createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: {}
  }
});

After:
createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});

apply_machine_patches

Applies semantic patches in memory and returns a non-mutating behavioral proposal: the updated document, the structured patches, and a concise behavioralSummary. It never writes the source file or invokes Git. Use to to choose the returned format; the coding agent remains responsible for its actual source edit.

Patches use semantic graph operations. For example:

{
  "op": "createTransition",
  "sourceId": "player.playing",
  "targetId": "player.paused",
  "eventType": "STOP"
}

Use graph entity IDs; top-level states commonly use <machine-id>.<state-key>. Use camelCase operation names such as createTransition, not snake_case names. State patches preserve initial input, output, timeout, and route; transition patches preserve input and matches; invoke patches preserve metadata, input, and output; implementation patches preserve code; schema patches preserve context, event, input, and output schemas. Use null to clear these optional fields, schemas, or machine context. Schema-valid sparse XGraphs may omit effect/tag arrays; create patches initialize those collections when needed.

Use Stately to rename the playing state to active and return the updated XState machine:

createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: {}
  }
});

review_machine_implementation

Reviews an agent-edited machine against the original source and proposed semantic patches. It validates the edited machine, derives the behavior the edit actually introduced, and reports missing, extra, or divergent changes. The returned stately-behavior-review.md artifact contains the semantic summary plus before/after Mermaid graphs, ready for the agent to save or paste into its pull request.

The workflow keeps ownership explicit:

  1. Inspect the existing machine.
  2. Call apply_machine_patches for structured behavioral guidance.
  3. Edit the source with the coding agent's normal tools.
  4. Call review_machine_implementation with the original source, edited source, and proposed patches.
  5. Let the coding agent create its branch, commit, and pull request normally.

Neither tool writes files, creates branches, commits, pushes, or contacts a Git provider. The surgical writer remains an optional primitive for an agent that wants minimal source edits; it does not own the surrounding workflow.

Ask Stately for patches that add a verifyingFraud state between processing and
completed. Edit the machine source yourself, then ask Stately to review the
edited machine against the original source and those patches. Save the returned
Markdown behavior review and include it in the pull request you create.

generate_graph_paths

Generates shortest or simple paths through a machine. The response includes the event steps, state and transition coverage, total path count, truncation, and execution metadata. max sets the page size, defaults to five, and accepts integers from 1 to 1000. Explicit values above five are honored within the server generation budget. XState source uses native traversal in an isolated sandbox; other formats are converted to structural XGraph first.

To retrieve another page, repeat the same machine or graph and kind, passing pagination.nextCursor as cursor. Cursors are bound to the normalized input, strategy, server budget and exact ordered generated result. A changed model or result rejects the cursor; restart collection without it. Page size may change between calls. Retrieval is stateless and reruns the existing API traversal; it does not resume its CPU work. The API accepts an optional resultWindow with offset and max; native execution projects that page before crossing the sandbox output boundary, while coverage and the fingerprint still describe the bounded generation. Existing native limits remain: 10 seconds, 64 MiB of QuickJS memory and 8 MiB of serialized output. An individual oversized page fails explicitly; a cursor does not bypass generation or resource limits. Native fingerprints use a pure SHA-256 bridge with at most 8 MiB per chunk, 64 MiB of cumulative input and 4096 calls per execution. These limits fail explicitly rather than labelling partial results complete.

pagination reports the applied page limit, generation budget, available path count, offset, model revision and generation fingerprint. more-pages means another page is available. complete means the entire bounded generated set has been retrieved. budget-exhausted means retrieval reached the end of the server budget while generation still reports omitted paths. The default budget is 1000 paths. An explicitly configured anonymousGraphPathLimit remains a hard budget for every caller, capped at 1000. Authentication and API execution policy still apply.

generationComplete describes the bounded generator result; retrievalComplete describes reaching the last available page. Neither flag proves all application behavior, event payloads or requirements are covered. totalPaths retains the generator's reported total, and legacy truncated remains true whenever this individual page contains fewer than that total, even on the last page of a complete collection. Use contiguous pages sharing one generationId, starting at offset zero, to establish collection completion. coverageScope: "generation-budget" makes coverage refer to all available paths in the generated batch, rather than only the current page. Execution metadata retains the distinction between native and structural traversal. The hashes detect mismatches; they are not signatures or server attestations.

Use Stately to find up to five shortest paths through this machine:

import { createMachine } from 'xstate';

createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { PAUSE: 'paused', STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});

simulate_machine

Runs up to 100 events through a machine and returns a step-by-step trace of states, context, selected action names, and execution metadata. XState source runs native transition logic in an isolated sandbox. Structural inputs report normalization explicitly. For SCXML, executionMode: "native" opts into sandboxed XState v6 execution. advanceTimeMs advances virtual timers after the event list, which may be empty. Completion output is returned when defined. SCXML results report exact: false; invocation and full SCXML conformance remain unsupported. Timed traces omit action names and include a warning.

Use Stately to simulate PLAY followed by STOP on this machine:

import { createMachine } from 'xstate';

createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});

Temporary visualization workspaces

visualize_machines displays up to 20 models per call in the shared editor. A model is one flow diagram, identified by machineId; its states and transitions belong to that model. Successive calls can accumulate more than 20 models in the same workspace, and updates to an existing identity do not add another model. Visualization and editor tools request fullscreen display when the host invokes them; the host controls whether it opens the app automatically. Pass stable machineId values and reuse the returned workspaceId for additions, updates and retries. Set selectedMachineId to explicitly open a model. Background arrivals keep the current selection. Same-identity updates retain earlier revisions and protect draft edits. Each model retains up to 20 earlier revisions. Workspaces are limited to 5 MB of UTF-8 snapshot data. read_visualization_workspace reopens the collection. Without an explicit workspaceId, an addition that exceeds the snapshot size limit starts a fresh collection. Explicit workspace additions report the size error. Invalid stored data and other validation errors remain errors. Stored collections remain available under their original workspace IDs; result-only collections remain in earlier tool results. These tools never save models to hosted projects. Hosted saving remains an explicit save_stately_models operation. One-model collections show only the canvas. The machine selector appears when a second model arrives; temporary-storage details stay in the tool result rather than banners above the canvas.

visualize_machine also accepts workspaceId, machineId, name and focus. Without machineId, the graph id supplies identity. Use explicit identities for models whose graphs share an id.

Every result carries the complete collection for replay. Standalone MCP additionally stores temporary workspaces under ~/.cache/stately/visualization-workspaces. The app persists selection and draft edits through app-only server tools. Embedded servers must inject a durable, principal-isolated visualizationWorkspaceStore. Without that adapter, results say persistence: "result"; later selection and edits cannot survive reopening. Without a store, successive additions accumulate only while the same server instance remains alive; use one batch when that lifetime is unknown. Local storage is never the restoration authority.

export_machine_image

Export XState, JSON, XGraph, SCXML, Mermaid, D2, or Digraph with export_machine_image({ machine, format?, imageFormat?, root?, layout?, direction? }). imageFormat defaults to png, returned as MCP image content; svg returns SVG markup as text. Use source instead of machine and format when import hints are needed. Unpositioned machines are laid out automatically; set layout: true to recompute an existing layout.

visualize_machine

MCP Apps hosts render an interactive, read-only graph with hierarchy drill-in, breadcrumbs, select/pan/structural-simulation controls, selection utilities, zoom, viewport recovery, keyboard shortcuts, and a host-mediated link to the same graph in Stately. It starts in select mode; AI controls remain hidden. Pass XState source text (the default for strings), a JSON machine config, SCXML, XGraph, legacy Stately DigraphDef, Mermaid, or D2; the server converts it once to canonical XGraph before rendering the app and PNG fallbacks. PNG fallbacks use the editor's Stately graph renderer and image export, including self-transitions, targetless transitions, and readable timer labels. Other image-capable clients receive one PNG fallback per parent node. Structured content uses a required schemaVersion: "2.0" envelope with a canonical XGraph JSON string in interactive.graphJson. Every V2 field has a concrete JSON schema so hosts can persist the result without traversing open XGraph data. interactive and pngFallback independently report ready or unavailable, so PNG rendering may succeed when the persisted interactive graph is unavailable. The graph is capped at 500,000 UTF-8 bytes by default and PNG metadata at 100 entries; image bytes remain native MCP content blocks. Use parentNodeIds to request multiple fallback levels; omit it to render the highest-level editor view.

The App reads only this declared structured output. The stable resource URI is retained: newer bundles decode V2, V1, and the earlier unversioned graph / graphError shape. Saved results created before graph fields were declared cannot be reconstructed and deliberately ask the user to run the tool again.

Each returned image uses the MCP ImageContent shape:

{ type: 'image', data: pngBase64, mimeType: 'image/png' }

Use visualize_stately_machine({ machineId, direction?, parentNodeIds? }) to fetch and render a hosted machine in one call. It prefers the public graph, then an XGraph-shaped stored definition, then legacy DigraphDef compatibility.

Use Stately to visualize this machine from left to right:

createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});

extract_machines_from_code

Statically extracts every XState machine config from JavaScript or TypeScript. The parser infers XState v5 or v6 structurally; pass xstateVersion only to override inference. It does not execute source or require a resource provider.

Computed event maps such as on: Object.fromEntries(...) that static parsing cannot resolve return an actionable unsupported-construct error. Use an explicit object literal for states, on, or after. Visualization does not execute callbacks or establish executable fidelity.

Use Stately to extract the machine from this TypeScript:

import { createMachine } from 'xstate';

export const player = createMachine({
  id: 'player',
  initial: 'paused',
  states: {
    paused: { on: { PLAY: 'playing' } },
    playing: { on: { STOP: 'stopped' } },
    stopped: { type: 'final' }
  }
});

Hosted resource tools

These tools read hosted Stately projects and machines through the server-owned /api/v1 resource contract. They are separate from the workspace tools (list_machines, get_machine), which read local files.

Tool Reads
list_stately_projects The hosted projects the caller can access.
get_stately_project One project, with its current project version id and machine ids.
list_stately_project_machines The machines in a project.
get_stately_machine One machine, with its definition.
visualize_stately_machine Fetch and visualize one hosted machine in one call.

Inputs take a projectId or machineId, never a project version id.

Every call needs a credential: the MCP host supplies it and the bearer token is forwarded to the resource provider. Calls without one fail with unauthenticated, and deployments with no resource provider fail with capability_disabled. Errors use the canonical resource envelope, { error: { code, message, issues?, retryable? } }.

These tools are read-only by policy. Create, update, and delete resource tools are deliberately absent.

Use Stately to list the machines in the project with ID `project-id`.
{ "machines": [{ "machineId": "machine-id", "name": "checkout" }] }

All Stately MCP tools are registered as read-only, non-destructive, and idempotent. Machine tools are closed-world; the hosted resource tools are open-world.

Tool-call observation

Hosts can pass onToolCall to registerStatelyMcpTools or createStatelyMcpServer. It receives a content-free completion event with the tool name, outcome, duration, and stable error code when available. Arguments, machine source, and results are never included. Input and output validation failures are reported as errors. Configure the observer before registering any other tools on the same McpServer.

Error codes

Tool errors carry a code from a closed set. An upstream code is only preserved when it is one of these values; anything else falls back to the default for the HTTP status class, so clients never see an invented code.

Code Meaning
bad_request Malformed request, and the default for unmapped 4xx statuses.
unauthenticated Missing or rejected credentials (HTTP 401).
forbidden Authenticated but not allowed (HTTP 403).
not_found No such project, machine, or route (HTTP 404).
conflict Version or state conflict (HTTP 409).
payload_too_large Upstream rejected the request size (HTTP 413).
rate_limited Too many requests (HTTP 429).
capability_disabled The operation is not enabled on this deployment.
upstream_error Server-side HTTP failure, and the default for 5xx statuses.
internal_error Unhandled failure inside a tool handler.
upstream_timeout The Stately API did not answer within apiTimeoutMs.
invalid_input Local input validation failed before any API call.
input_too_large Input exceeded maxSourceBytes before any API call.

Migration: 4xx responses that previously surfaced an unrecognized upstream code verbatim (or upstream_error from a proxy) now report the status-class default listed above. upstream_error remains reserved for 5xx responses.

On HTTP 429 the upstream Retry-After header is appended to the error message, for example Too many requests. Retry after 30 seconds.

Set clientId to label this server's HTTP analysis calls for channel-level telemetry. It defaults to stately-mcp/embedded; the stdio binary uses stately-mcp/stdio. The label carries no user or machine content.

The observer is absent by default. Its failures do not affect tool results, and its promises are not awaited; serverless hosts should schedule delivery with their platform lifecycle primitive.

For saved OAuth connections, refresh-token testing, and native ChatGPT smoke requirements, see Connection testing.

Self-hosting

Self-host Stately Studio, then replace the hosted URL above with your deployment's /api/mcp endpoint, for example https://studio.example.com/api/mcp.

When the editor runs with AUTH_PROVIDER=none, MCP tool calls do not require a bearer credential. Keep the endpoint behind your own trusted access boundary.

After deployment, run the protocol and MCP App canary with a read-only bearer credential:

STATELY_MCP_CANARY_URL=https://studio.example.com/api/mcp \
STATELY_MCP_CANARY_TOKEN=... pnpm verify:mcp:canary

It verifies tool discovery, fetches and hashes the advertised app template, checks compatibility URLs used by previously created visualizations, enforces the serialized MCP resource response byte budget, and runs a minimal visualization. The scheduled production workflow requires the STATELY_MCP_CANARY_TOKEN repository secret and fails when it is absent.

For enterprise self-hosting options, see pricing and contact us.