stateui-mcp
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
stateui-mcp
A standalone MCP server for building StateUI apps. An agent creates and edits an app with tools, a person watches the same app live in a browser, and a headless Chromium (Playwright) renders it so the agent can take screenshots, click and type in it, and read the events it raises.
The server serves no HTTP. It speaks MCP on stdio, and its tools write each app's live state to a statenet (@punyts/statenet). The view page that shows the apps is static: the Vite dev server of view/ serves it locally, a CDN in production, and it reads the state from that statenet (see Live views).
It is the single-user, local version of the ui-builder bounded context of AI Minion: same tools, arguments, results and error codes, with no workspaces, users or approval policy. The server stores the owner's parts, the instances and the uploaded files as JSON files in its data directory (see Data directory). createServices takes a storage (ServicesStorage) in place of dataDir: @punyts/stateui-pg provides Postgres adapters for those ports, which Magnetic uses.
Install
Node 22 or newer. The @punyts/* packages are not on npm; it is developed in the punyts workspace, where each library is an npm workspace and npm run setup at the workspace root clones, installs and builds them, so it runs from there.
npm run mcp:build # at the workspace root: this server, the libraries it uses and the runtime bundle
npx playwright install chromium # once (setup does it), for ui_preview, ui_screenshot and ui_interactWithout Chromium everything else works. ui_preview still returns the address a person can open (with rendered: false and a note), and ui_screenshot and ui_interact answer browser-unavailable.
The runtime bundle comes from @punyts/stateui-app (dist/runtime-bundle/, built by npm run build:runtime-bundle in that package); the view page's Vite plugin serves it (stateuiView({ runtimeDir }) points at another build). The plugin will not start with a bundle built before a component was added to the library; it names the missing components and asks for a rebuild.
The 3D renderer chunk comes from @punyts/stateui-3d (dist/runtime-chunk/, an optional dependency). When it is installed and built the view page's plugin serves it beside the runtime and names it to the view, so an app with a scene3d loads it on first mount; without it the page names no chunk, and a scene shows its _fallback text.
Related MCP server: Agentic Browser bridge
Run
Three processes: the statenet, the view page's dev server and the MCP server.
# The statenet (ws://127.0.0.1:4200/sync) and the view page (http://127.0.0.1:5180/, the runtime frame on 5181)
npm run dev
# The MCP server, on stdin and stdout; an MCP client starts it (below)
node dist/cli.js --data-dir ./datanpm run dev (scripts/dev.mjs) runs the statenet (its data in ./statenet-data, letting in the pages of http://127.0.0.1:5180 and http://localhost:5180) and Vite (view/vite.config.ts) in one process, so stopping it stops both. npm run statenet and npm run view run each alone. STATENET_PORT moves the statenet, STATEUI_VIEW_PORT the page (and the origin the statenet lets in), STATEUI_VIEW_RUNTIME_PORT the runtime frame.
Option | Environment | Default |
|
|
|
|
|
|
|
|
|
| accepted for older client configurations; stdio is the only transport | |
|
| none: an app that keeps |
|
| none: no tool calls are logged |
|
| on: the component showcase is installed on an empty data directory |
--port, --runtime-port, --host and --runtime-dir are gone with the web server; passing one says what replaced it.
Tool-call log. With --tool-log <file> the server appends one JSON line per tool call: { at, tool, ok, errorCode?, requestChars, responseChars, target?, errorCount?, warningCount? }. requestChars is the length of the JSON arguments, responseChars the length of the result's text (images are not counted), errorCode the error of a failed result, errorCount and warningCount the lengths of its errors and warnings, and target the call's app (with / and screen when it names one), cut to 80 characters. Once per session, when the client has initialized, it also writes { at, instructionsChars }, the length of the served instructions (not their text), so a measurement counts the instructions once per build with the tokens read. Nothing else is written: no arguments, no response bodies. A failed write is reported once on stderr and never fails the call. It is for measuring how agents use the tools: node scripts/summarizeToolLog.mjs <calls.jsonl>... prints per build the tokens read (instructions plus catalog plus guide), the instructions tokens, the catalog tokens (the catalog tools and ui_guide; characters divided by four), the guide tokens apart, the failed writes and the first-write validation errors, and their median and range over several builds (test/measurement/requests.md has the requests and the scripts that run them).
npm start runs node dist/cli.js; stateui-mcp --help lists the options. stateui-mcp convert converts the old apps of a data directory into owner parts once (see Converting the old apps). Every log line goes to stderr, because stdout is the protocol. Ctrl+C, SIGTERM, or the client closing stdin stops the server, closes its statenet connections and closes the headless browser. The server starts without the statenet and keeps trying to reach it: the tools work meanwhile, and the views catch up once it is there.
Component showcase
The server ships an app that shows every component of the library, component-showcase. Every screen places the same two composed components, showcaseHeader (the title and the theme switches) and showcaseMenu (a side menu that folds behind a button on a phone); the menu has a home screen, with the number of components per category and a chart of them, and one screen per catalog category (layout, navigation, forms, data, feedback, overlays, content, conversation, graphics). Each component is a card with its name, its catalog summary and a live example with realistic data: tables, lists, boards, calendars and charts read small sample datasets, the overlays open from buttons, the drawings use every 2D shape and the 3D scenes every 3D node, with a model from a GLB file. The header switches between the four theme presets and between light and dark. A logic module, showcase-tasks, unassigns a task moved back to To do on the board.
See it. When the server starts on a data directory that holds no parts (a new or empty one), it installs the showcase there and logs one line, Installed the component showcase on the new data directory. Open http://127.0.0.1:5180/ and pick component-showcase, or ask the agent to ui_preview it. The showcase is an ordinary app of parts (an app, four themes, models and datasets, a logic module and an uploaded file), so ui_get shows how each example is built and its nodes can be copied into another app. A data directory that already holds parts is never touched, so the showcase is installed once, and an app you change or delete stays that way.
Turn it off. Start the server with --no-showcase, or set STATEUI_MCP_SHOWCASE=off. startServer installs it only when its showcase option is true, which the CLI sets unless it is turned off.
Rebuild it. The parts in showcase/parts/ are generated and committed: npm run showcase:build (scripts/buildShowcase.mjs) builds them from the examples in showcase/examples/ (one file per category, plus datasets.json), the catalog of @punyts/stateui-components and the files in showcase/files/, with fixed ids and dates, so a rebuild with nothing changed writes the same bytes. Run it after adding a component to the library or changing an example; test/showcase.test.ts fails when the committed parts are not up to date, when a catalog component has no card (the exclusion list, EXCLUDED in the script, is empty) or when the app does not validate, and test/showcase.integration.test.ts opens every screen in the headless browser.
Register it in an MCP client
The client starts the server on stdio; start npm run dev first so the views have a statenet and a page.
Claude Code:
claude mcp add stateui -- node /path/to/stateui-mcp/dist/cli.js --data-dir /path/to/dataA .mcp.json (the workspace's own uses relative paths, since Claude Code starts it in the workspace folder):
{
"mcpServers": {
"stateui": {
"command": "node",
"args": ["/path/to/stateui-mcp/dist/cli.js", "--data-dir", "/path/to/data"]
}
}
}The server instructions are short (K1.2 of the guide-tool epic): they hold what every build needs and point to the rest. They are built from the guide's topic table (GUIDE_TOPICS in src/infrastructure/mcp/guide.ts, the one source of the guidance; ui_guide answers one topic of it) by buildServerInstructions: the opening line; a paragraph on ui_guide (GUIDE_INTRO: what it is, that its description lists the topics, and to read a topic before the step it names); the always-on topics in full, in table order; then one line per other topic, as a block at the end: "Before , read ui_guide topic ." (pointerLine). With the library catalog and its four presets they are 5,157 characters, a third of the 15,669 they were with every topic in full; test/toolSet.test.ts fails if they grow past half of that. The always-on topics are the eight build steps (searchWorkflowSection, the topics start and sections): plan (ui_list; a large app, more than three screens or one that writes to an owner dataset other apps use, waits for the user's OK on the plan), theme (ui_theme_create, ui_theme_write, ui_tokens_list), data (ui_model_write, ui_data_write), app (ui_patterns_search, ui_app_create), screens (ui_patterns_search, ui_screen_create), sections (ui_components_search, ui_component_get, ui_nodes_write), logic (ui_logic_write) and check (ui_validate, ui_preview, ui_screenshot full page and at 375 px, ui_interact), the order being guidance and an edit starting at the step it needs, with the library's theme presets (PatternCatalog.presets(); the line is left out while there are none) and a category index generated from the catalog (each category with its count and three typical members); and the rules that cost a failed call (the topic keys: icon names from ui_icons_list, token and overlay names from ui_tokens_list and ui_component_get, no integer-like record keys, no set through a missing parent, move over remove and rewrite, never write a resolved value back). The other topics are read with ui_guide: parts (parts the owner keeps by name, build time and run time tools), paths ($.app, $.screens.<name>, $.route, rendered paths), revisions (a revision per part with its warnings), modules (modules and params), logic, live-view (the live view, the instance state and how to read events), files, safety (ask before ui_delete and ui_rename), and the graphics topics, pointer lines too since K1.2: drawing (graphicsSection): the shape vocabulary, that shapes sit in a drawing, that a shape value is a literal, a token or a link, that a colour from a record comes from the record ("<-fill": "$row.fill"), that draggable needs interactive: true and a drag writes once on release, and that shapes are reached with ui_tree rendered: true and ui_interact; paint-field (paintFieldSection, two lines): paintField is a form field whose value is the reference of the PNG it saves, a form waits for the save, and painting needs a pointer, so a form that must work without one adds a textField for a typed signature; and scene3d, scene3d-models and scene3d-behavior (scene3dSection joins them, G3.11 of graphics epic 3, releases 3A and 3B; a header and one bullet per subject, 11 lines): scene3d and its nodes (camera, light, mesh, model, label3d, group3d, repeat3d); that a scene needs _title and _fallback, and the 16-scene warning (ui_validate); the node values ([x, y, z], a mesh's geometry and material, colours as literals or tokens); the default camera, the environment presets and controls (orbit, pan), which write the active camera's position and target once on release; that model.src is the file reference of an uploaded GLB of at most 10 MiB and which models are refused (SUI-RUN-3D, SUI-RUN-FILE); that material.map is the file reference of an uploaded png, jpeg, gif or webp image tinted by the colour (SUI-STATE-INVALID for another type); that repeat3d draws its mesh row once per record as one instanced mesh, each record with its own position, rotation, scale, visibility and material.color, the rest shared (SUI-RUN-DRAW when records differ there), at most 20,000 records (SUI-RUN-CAP); that interactive: true with a _label raises press and hover and gives the node a path for ui_tree and ui_interact; that label3d draws plain _text in the page font facing the camera (fontSize 0.3 scene units by default, the theme text colour); that transition eases a node's position, rotation, scale, material colour and opacity, a light's intensity and a camera's position and target, animate (spin, bob, pulse) and a model's clip (animation, playing) play without writing state, and reduced motion turns them off; and that ui_screenshot waits for the scene, its models, textures and transitions. A client that does not show the server instructions gets the same text from ui_guide with the topic start. The descriptions of ui_list, ui_theme_create, ui_app_create and ui_components_search end with the start of the working loop and the rules that cost a failed call (START_HERE, which names ui_guide once), and each tool description starts with Build time: or Run time: (ui_guide: Guide:).
Tools
Thirty-eight tools: the guide, then three groups: build time, the owner's data and run time. Build time tools change definitions (parts) and never touch an instance; run time tools act on the default persona's instance of an app part and never change a definition. ui_guide is neither: its description starts with Guide:.
The guide's topics. ui_guide answers one topic by name, and the server instructions name the topic to read before each step ("Before , read ui_guide topic ."); the topics marked always on are in the instructions in full. start (always on): the whole server instructions, for a client that does not show them; sections (always on): the later build steps, the theme presets and the component categories; parts: before planning the parts of an app; paths: before writing a node, screen or route path, or looking at a running app with ui_tree; revisions: before changing a part that exists; keys (always on): before naming an icon or token, giving a record key or setting a value under a path; modules: a logic module or the params of a screen; logic: a machine or rule; tables: a lookup table; effects: a compute unit, an effect, a request token or paged records; live-view: before previewing, testing or watching a running app; files: before reading a file a user uploaded; drawing: a drawing and its shapes; paint-field: a paintField; scene3d: a scene3d, its node values and its camera; scene3d-models: a 3D model file, a texture or a repeat3d; scene3d-behavior: a pressable 3D node, a label3d, 3D motion or the check of a scene; safety: before deleting or renaming a part. A client that drops the server instructions still has them: ui_guide with { topic: 'start' } answers the same text. A failed call whose code has a topic carries guide: '<topic>' in its body, and so does each validation error or warning (see below), so the agent reads the rule the call broke.
Tool | Arguments | Result |
|
|
|
|
|
|
|
| the compact catalog entry (properties with only the keys that apply, slots, events, commands, tokens, example; a composed component's tree and exposed paths); an unknown name is |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| an MCP image (PNG) and |
|
| fill |
|
|
|
|
|
|
|
|
|
|
|
|
The tools of the owner's parts (kind is one of apps, themes, logic, models, data, components, patterns, screens, and screens takes app):
Tool | Arguments | Result |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Read-only tools carry readOnlyHint; ui_delete and ui_rename carry destructiveHint, so the client asks the user. A failed call has isError: true and the body { error, message, ...details, guide? }. guide names the ui_guide topic that explains the code (guideFor over TOOL_CODE_TOPICS in src/infrastructure/mcp/guide.ts; added by fail() in toolKit.ts, the message is unchanged): conflict, duplicate-name and in-use point to revisions, missing-parts to parts, missing-path, invalid-path, unknown-path, not-a-node, invalid-target, unknown-screen and not-rendered to paths, logic-guard and not-waiting to logic, and no-logic, unknown-command and browser-unavailable to live-view; other codes have no guide. Each entry of errors and warnings in a validation answer (ui_validate, the warnings of a write, the errors of a refused write; for the warnings of a part write, the errors of each app it reaches) gains guide the same way from its catalog code, by the longest prefix in VALIDATION_PREFIX_TOPICS: SUI-LOGIC to logic, SUI-MODULE and SUI-USES-NEEDS to modules, SUI-USES to parts, SUI-ROUTE and SUI-NODE-MISSING to paths, SUI-INSTANCE to live-view, SUI-DOC-ORDER, SUI-STATE-TOKEN, SUI-THEME-TOKEN and SUI-RUN-ICON to keys, SUI-STATE-PAINT, SUI-STATE-LABEL and SUI-RUN-DRAW to drawing, SUI-DOC-LIMIT-SCENES to scene3d, and SUI-RUN-3D and SUI-RUN-CAP to scene3d-models; other entries are unchanged. The runtime errors of ui_preview, ui_interact and ui_state_get carry no guide. Codes: invalid-argument (with argument), not-found, unknown-tool, internal-error, browser-unavailable, not-rendered, action-failed, and the codes in the table. Arguments are plain JSON; extra arguments are refused, so a call with the appId of the removed tools fails.
Differences from ui-builder: no workspace-missing or user-missing, no approval marker on ui_delete and ui_rename (the client can ask the user; the tools are annotated destructive), and the run time tools act on the default persona's instance, as the local owner's only user.
path in ui_screenshot and ui_interact is the state path of a node, such as $.app.children.form.children.email (the leading $. is optional). It is mapped to the element the component rendered for that node, through open shadow roots. A hidden or closed node has no element. When no component rendered that path, it is mapped to the element with data-shape-path equal to it (shapeTargets.ts): the SVG element of a shape, or the proxy button of a canvas shape, so a path that names no shape is an error naming the path.
Drawings (graphics epic 1) use the same tools: shape nodes go in a drawing node's children with ui_nodes_write (ui_components_search with category: "graphics" finds them), ui_validate reports the paint, token and label checks, ui_screenshot of the drawing's path waits until it is drawn, ui_tree with rendered: true lists its interactive shapes, and ui_interact presses, hovers, focuses or drags one by its path (drag with value +dx,+dy moves it by page pixels; the offset is read by dragTargetOf in src/infrastructure/preview/dragTarget.ts, and a shape that is not interactive and draggable is refused before the mouse goes down). A drag writes once, on release: the shape's x and y (or the record of a drawRepeat copy), so a following ui_screenshot or ui_state_get shows the new position. A drawImage (G1.9b) takes a data: picture or the reference of a png, jpeg, gif or webp file uploaded to the app (POST /apps/<id>/files); the frame reads the file through the host (fileRead, G1.9), and ui_screenshot waits until the picture is decoded and drawn. The guide topic drawing says what src may be. That topic drawing (graphicsSection, above; a pointer line in the server instructions) says the same to the model. The shape vocabulary, the renderers and the events are documented in the @punyts/stateui-components README ("Graphics").
3D scenes (graphics epic 3, releases 3A and 3B) use the same tools: a scene3d node holds camera, light, mesh, model, label3d (a text that faces the camera), group3d and repeat3d (one mesh row drawn once per record as an instanced mesh) nodes in its children (ui_nodes_write; ui_components_search with category: "graphics" finds them), ui_validate checks them and warns past 16 scenes a page (SUI-DOC-LIMIT-SCENES), and ui_screenshot of the scene's path waits until its first complete frame, models, textures and transitions included (scenes: pending in the result when it times out; a playing animate or model clip does not hold it back). A model's src is the reference of a GLB uploaded to the app (POST /apps/<id>/files, the Security notes say which GLB files are taken), and a mesh's material.map the reference of an uploaded png, jpeg, gif or webp picture; the frame reads both through the host as a drawImage picture is read. With controls a person turns or pans the camera in the live view and the camera node's position and target are written once on release, so ui_state_get shows the view. A 3D node with interactive: true has a proxy button, so ui_tree with rendered: true lists it with its path and ui_interact clicks, hovers, focuses and presses keys on it as on a 2D shape (G3.8); a drag on it turns the camera of a scene with controls and is not a press. The scene and its nodes are documented in the @punyts/stateui-components README (scene3d), the renderer, the chunk and the headless WebGL note in the @punyts/stateui-3d README. The guide topics scene3d, scene3d-models and scene3d-behavior (scene3dSection; pointer lines in the server instructions) say the same to the model.
Live views
The live views of the apps live in a statenet. The server is one of its clients; the view pages are the others. Nothing of the server listens on a port.
The statenet. StatenetViews (src/infrastructure/statenet/) connects to the statenet (--statenet) with StatenetLink, @punyts/state-sync's sync client over a WebSocket, which reconnects with its backoff:
The directory, the namespace
stateui.apps: the server keeps$.apps.<appId>there ({ name, namespace, revision, updatedAt }, one entry per app part, written again on every app change), so the view page lists the apps and finds the namespace of the one it shows. A page asks there for an app with the emitstateui.open { appId }; the server answersreadywhen it (re)joins, so a page asks again after a restart.One bridge per open app (
AppBridge), in the namespace of its instance,instances.<persona>.<ownerId>.<appId>. The instance's authority stays in the server (logic, guards, shared datasets, storage on disk) and is the truth: every change it pushes (logic,ui_state_set, a shared dataset's write) is written to the statenet, and on every (re)connect the statenet's state is made equal to the authority's (diffState, the smallest writes that do it;$.servernever leaves the server). A change a page made comes from the statenet and goes to the authority as a client change, so guards, model checks and logic run on it. When the authority adjusts or refuses it, the statenet gets the authority's value back and the pages arejectedmessage, which the view raises assync.rejected; unlike a page that talks to its own server, the change shows for a moment first. A definition change restarts the authority; the bridge connects to the new one and writes what changed. A deleted app getsdeleted, and its bridge stops.The view relay. Everything that is not state rides the protocol's
emit, which the statenet relays (an emit from the server goes to every page of the namespace, an emit from a page to the server only,@punyts/statenet): the server sendsstateui.server, a page sendsstateui.view. Each message is JSON in one or more envelopes{ v: 1, id, part, parts, text, from?, to? }(src/domain/viewRelay.ts), so a 1 MiB document or a 10 MiB file stays under the protocol's 1,000,000-character message limit. A page sendshello { kind }(browserorheadless; the server attaches it to the hub and answers with the app),report { report }(ready, rendered, errors, astakeViewReporttakes them),event { name, value }(anemitof the app, forui_events_read),request { id, method, path, … }(a file upload, read or release, answered withresponse { id, status, json?, bytes?, headers? }as the file routes answer) andbye. The server sendsview { message }(the document, commands, locale, theme, deletion, a refused change),responseandready. The statenet'sstatenet.left { clientId }detaches a page that closed.
The view page (view/, src/browser/statenetView.ts): / lists the apps of the directory, /?app=<id> shows the live view of one (host.ts with statenetChannel.ts), and ?statenet=ws://… names the statenet (else VITE_STATENET_URL from the build, else ws://<page host>:4200/sync). ui_preview answers <view url>?app=<id>&statenet=<url>, the page the headless browser opens too (?kind=headless or its user agent marks it). The Vite plugin (@punyts/stateui-mcp/vite, stateuiView()) serves the runtime frame on a second port, so the sandboxed frame (allow-scripts allow-same-origin) has an origin of its own and cannot reach the page; it serves the runtime page with the runtime policy (no network, framed by the page's origin only), the bundle and the 3D chunk, and writes data-runtime-url and data-chunk-3d on the page's body.
Production (a CDN). npm run view:build writes the page, page.css and runtime/ (the runtime page, bundle and chunk) to dist/view/; no deployment is made. Set at build time: STATEUI_VIEW_BASE, the base URL or path the files are served from (Vite's base, such as https://cdn.example.com/stateui/); STATEUI_VIEW_RUNTIME_URL, where the pages load the runtime frame from ({host} is the page's host name), on an origin other than the pages', so serve runtime/ from a second origin with the runtime policy as its Content-Security-Policy (runtimeCsp in src/infrastructure/http/security.ts); without it the frame loads ./runtime/runtime.html from the pages' own origin; and VITE_STATENET_URL, the statenet the pages connect to. Run the server with --view-url set to the page's URL, and the statenet with --allow-origin set to the page's origin. The statenet listens on loopback only and has no authentication, so a statenet reached from other machines needs a proxy that adds both in front of it.
How the view works. The page is a shell with one module. It puts the runtime page into a sandboxed iframe served from the runtime origin, speaks the versioned message protocol of @punyts/stateui-app/protocol with a per-load nonce, and checks every message by source, origin and nonce. The app runs in Full mode of @punyts/state-sync: the page's sync client syncs with the app's namespace, and the view messages bring the document (on hello and after every part write, written into the running app as path writes where it can, or as a new load), commands and theme or locale switches. Every change a user makes to $.data or to the articulation of $.app (no _ content, no component, on, layout, placement or theme) is synced, and every change the authority applies (another view's, a ui_state_set) reaches every view. The sync client keeps the confirmed state, the changes not yet acknowledged and the document in localStorage, so the view opens and takes changes while the statenet is away and sends them in order when it is back. body[data-sync] and $.runtime.sync show the status. Query parameters ?mode=dark and ?locale=fr apply a theme overlay or a language to a view. Files. The frame has no network, so files pass through the page: a file message (a fileField upload) goes to the server as a request, a fileRead (a component reading a stored file, such as a paintField background image) is read through the server (src/browser/fileRead.ts) and answered with fileData, the bytes moved in the transfer list, and a fileRelease (a component giving a stored file back) is answered with fileReleased (src/browser/fileRelease.ts). An id that is not a UUID is not_found (a release ok: true) without a request; a 404 is not_found, 401 or 403 unauthorized, any other failure internal, a request that gets no answer offline, and a body over 10 MiB is too_large. A release is ok: true for 204, 404 and 409 (a file the app or its live state still references stays, and the 24-hour sweep removes it once nothing does), and it waits until the sync client has no change waiting for its ack (at most 5 s), so the write that let go of the file reaches the server first.
The embedded endpoint
A server that serves its own view pages, with sign-in and many owners, embeds startHttpServer (src/infrastructure/http/HttpServer.ts) instead: @punyts/magnetic does, since a statenet has no authentication to hand to signed-in browsers. Its pages run the same view with the direct channel (src/browser/viewChannel.ts, /assets/host.js):
Route | What |
| the apps (app parts), with a link to each |
| the live view of an app part, assembled and with the default persona's instance |
| the WebSocket of a view: the state-sync protocol and |
| what a view tells the server: ready, rendered revision and runtime errors |
| an upload from a |
| the bytes, as an attachment, |
| releases an upload: |
| the host script and the stylesheet |
| the live view with the app in the page itself, not in a frame: the page loads the page bundle before the host script, and the host mounts the app on |
| the page bundle of |
Its runtime port is a second origin that serves only the app frame (/runtime/<hash>.html, /runtime/<hash>.js, /runtime/runtime.css and the 3D chunk /runtime/<chunk hash>.js); every other path there answers 404. The host page allows scripts, styles, connections and frames from its own origin only. The page of an app in the page (?surface=page, APP_PAGE_CSP) has no frames and allows what the runtime page allows, since the app runs on the page's origin: 'unsafe-eval', and images and fonts from data: and https:. Its host gives the page an app host, stateuiHost.apps: the live app is attached where an embeddedApp asks for it, and a preview of it follows its store. The test harness (test/helpers.ts, httpHarness) runs the tools with this endpoint, since a view behaves the same over either channel. stateuiHost.mount(element, { document, icons?, keys?, inPage? }) puts a panel in element: a frame from the runtime origin, or with inPage in the page surface the page bundle's runtime on an element of the page, whose embeddedApp nodes reach stateuiHost.apps. A preview from stateuiHost.apps is given once the live app is mounted, and each mount of the live app raises stateui:ready on window, so a page opens its previews again on the new store. stateuiHost.pages({ open, mounted?, disposed? }) gives the app host the site's own pages: an embeddedApp that asks for a name open(name) answers ({ document, icons?, keys?, title? }) gets that page as a panel in the page filling its frame, mounted(name, panel, element) is handed the panel, disposed(name, panel) is called with that panel when it is let go, and its emits reach the embeddedApp and stateui:emit on the element.
Logic. A Full app's authority runs the document's logic (see @punyts/stateui-app): the units without runs or with runs: "server" (logicFor); a unit with runs: "browser" runs in the person's page instead, and its writes come to the authority as the person's changes do. A change a view sends runs the logic after it is applied and acknowledged; a guard rule (a rule whose only command is reject) answers before, so a refused change is rejected and the view gets sync.rejected. ui_state_set asks the guards too (a refused value is logic-guard) and then runs the logic. A transition's writes reach the views as one changes message. The authority keeps $.app sparse, so logic reads $.app as the document's value with the shape defaults under what the authority holds. notify.<name> and logic.failed reach the views as app events (the root node's on); emit and failures are also queued for ui_events_read. ui_tree with logic: true lists the machines with their current state, the rules, the guards and the decision tables with their rows. Timers (after, debounce) run in the server process and are lost on a restart, where they are armed again. A call command runs the procedure of that name given to startServer (procedures: (payload, { appId }) => LogicAnswer); any other call is queued as a logic.call event for ui_events_read, and the agent answers it with ui_call_answer. At most 100 calls wait per app, and waiting calls are dropped on a restart or when the app is removed. Compute units, effects and expressions run the functions named by path in the catalogs given to startServer as functions (InstanceCatalog: a FunctionCatalog that may also have loadFor(id, instance), which builds the code for one running app; catalogFor binds it). The components' own catalog, COMPONENT_FUNCTIONS from @punyts/stateui-components, is always installed before them. The validator checks apps against the same entries (SUI-LOGIC-FUNCTION, SUI-LOGIC-FUNCTION-FIT), ui_validate answers with the functions the app names (each entry, or { path, missing: true }), and the guide topic functions lists them. copyAppParts with functions (the server's entries, Services.functions) answers with missingFunctions, the paths the copied app names that this server lacks. So an API key an effect needs stays on the server, and an effect whose records.into is a $.server map keeps its records there while the views get only the window and the status. An effect with no function is queued as a logic.effect event (AppEffects, at most 100 per app) and the agent answers it with ui_effect_answer; a newer request of the effect aborts the waiting one. ui_logic_trace lists each effect's token, whether a call runs and how many answers its cache holds.
Playwright. The server keeps one headless Chromium, started on the first call that needs it and closed on shutdown, with one page per app. The page loads the same view page a person opens (<view url>?app=<id>&statenet=<url>), so it is a view like any other: it receives the same messages, ui_command reaches it and its changes sync like any view's. ui_screenshot and ui_interact look up the element in the runtime frame and use Playwright's own click, fill, press, hover and select on the native control inside it, so the events are the ones a user raises.
Policy. The embedded endpoint's host page allows scripts, styles, connections and frames from its own origin only, no inline script, no inline style, no framing by other pages; the statenet view page is the CDN's (or Vite's) to set. The runtime page has default-src 'none', scripts only from its own origin plus 'unsafe-eval' (the expression library builds functions for binding expressions), no network, images and fonts as data: only, and may be framed by this server's pages only. Uploaded files are never served inline.
Data directory
The directory holds the owner's parts, one file each, the default persona's instances and, per app part, a side folder with its preview errors and uploaded files. The old single-document store (one folder per app with an app.json) is gone: the tools no longer read it, and only stateui-mcp convert does.
data/<appId>/ the side folder of an app part: errors.json, files.json and files/ (below); an old app's folder keeps them after convert
data/<kind>/<id>.json an owner part; data/names.json indexes them by name (Owner parts, below)
data/rename.pending.json the journal of a rename stopped halfway, replayed at start
data/personas/default/... the default persona's instances and persona records
data/.converted/<appId>/ app.json and state.json of a converted app, until convert --purgeThe side folder of an app part is named by its part id. The old store used the same folder for its app.json and state.json, which stateui-mcp convert reads and moves away:
data/<appId>/app.json the old store only: id, name, revision, createdAt, updatedAt and the document
data/<appId>/state.json the old store only: the synced state, its sync revision and change log
data/<appId>/errors.json the bounded preview error log (the newest 50); a view that renders again drops the errors of its earlier loads and of other views
data/<appId>/files.json metadata of the uploaded files
data/<appId>/files/<id> the bytes of one uploaded fileEvery file is written to a temporary file in the same folder and renamed into place, and the writes of one app run one at a time, so a reader never sees half a file and a write is checked against the revision it read. children and keyed data maps are ordered by key: the files are written with JSON.stringify and read with JSON.parse and nothing re-sorts them (integer-like keys are refused, because JavaScript would move them). Limits: 1 MiB per document, 2000 nodes, 10 MiB per file, 50 files and 100 MiB per app. Uploaded files that nothing references (not in the app part or in the state of its instance, read live from the instance's authority; $.server is not included) are removed after 24 hours, when the next upload to the app happens.
Owner parts. The owner-tree design moves apps to reusable parts (apps, themes, logic modules, models, datasets, components, patterns). UiPart (src/domain/UiPart.ts) is one stored part: an immutable UUID id, the kind, a slug name (isPartName of @punyts/stateui-app/core), the revision and the body of its kind. UiPartRepository (src/application/ports/) is the storage contract for every kind: create, findByName, findById, list, write and delete with expectedRevision, and rename; results are created, written, deleted, renamed, conflict, not-found, duplicate-name or invalid (a name that is not a slug, a body that is not an object, or a given id that is not a UUID or that a part of the kind has). create takes an optional id so the converter can keep an old app's id. FilePartRepository stores them in the same data directory, (PartFolders builds every path, from a kind and a UUID only):
data/<kind>/<id>.json id, kind, name, revision, createdAt, updatedAt and the body; kinds: apps, themes, logic, models, data, components, patterns
data/names.json { <kind>: { <name>: <id> } }A rename moves no file. The part file is the truth and is written first; names.json is an index written after it and rebuilt from the part files at the first call when it is missing or disagrees. Writes to one part run one at a time, and creates, renames and deletes of one kind run one at a time, so two creates of one name cannot both win. partRepository.contract.test.ts runs the same cases against FilePartRepository and the in-memory fake (src/testing/InMemoryUiPartRepository.ts). UsageIndex (src/application/) knows who uses what: an app's themes, datasets, persona models, logic modules and the components in its nodes, a module's needs, a dataset's model and the components in a component's tree. IndexedUiPartRepository builds it from the stored parts at the first call and keeps it in step with every change; deleteRule refuses to delete a part while anything uses it and names the users; a screen may always be deleted. WritePart (src/application/use-cases/) checks a part with the reader of its kind and refuses it with its own errors, writes it with expectedRevision (or creates it on a first write), then checks every app that reaches it and returns the ones it breaks as warnings (at most 20, with moreApps); a model write also names the dataset records that no longer fit. ValidatePartApp checks one app assembled with everything it reaches, each error naming its part.
RenamePart (src/application/use-cases/) renames a part and rewrites every part that names it, all together: theme lists, bindings' dataset and model, uses.logic keys (in their place), needs models, datasets' models and the composed names in nodes. It checks the new name as a slug that is not taken, keeps the part's id (so instances and persona data stay where they are) and gives the renamed part and each rewritten one the next revision; it reads again and retries when a part it rewrites moved meanwhile. UiPartRepository.rename takes those new bodies as rewrites. When it writes more than one part file, FilePartRepository first writes rename.pending.json (every part file with its new content), then the part files and names.json, and removes the journal last; a rename of a part that nothing names writes that part and names.json only. A journal that is still there was stopped halfway: FilePartRepository.recover (run by startServer before anything reads a part, and before the first call reads the names) writes the files that differ from it, removes it and rebuilds names.json; running it again changes nothing. Renaming a screen (kind: "screens") is a write of its app with the app's revision: the key in screens in its place, start and every navigate to it.
A dataset part is { model, records }, the records an ordered map. WriteData changes them with record operations whose paths are relative to records (p1, p1.price): add (a new key, r and a new id, so it is never integer-like; the result lists the keys it gave), and the document operations set, merge, remove and move. It checks every record the write touches against the dataset's model (checkRecord, errors at $.records.{key} naming the field) and writes nothing when one is invalid; records it leaves alone are not checked. expectedRevision is optional: without it the operations are applied to the newest records, again when another write got in first, so writes to different records do not conflict. Every committed write raises the dataset's revision by one. QueryData filters, sorts and windows a dataset's records with queryRecords of @punyts/stateui-app/core, the evaluator of the logic query command, and returns the window with the total that matched.
What a person does in an owner app is its instance, kept apart from the definition. UiInstanceRepository (src/application/ports/) stores the default persona's instance of each app as a diff over the definition (diffInstance of @punyts/stateui-app/core), and the records of each persona binding (uses.data.{binding} with scope: "persona", which has no part). FileUiInstanceRepository keeps them by app id, so a rename of the app keeps them:
data/personas/default/apps/<ownerId>/<appId>.json the diff (app, screens, route, theme, data); no file when nothing differs
data/personas/default/data/<appId>/<binding>.json { model, records }; a capital in the name is ^ and its small letterThe owner id of the local server is LOCAL_OWNER_ID (ownerId of createServices overrides it). A missing file reads as the definition, and a file that cannot be read is ignored with a problem the caller reports, never thrown at the person. Nothing there writes a part, and a part write never touches an instance. WritePersonaData checks the records against the binding's model as a dataset part's are checked; ResetInstance removes the instance and the persona records.
A running instance has its own state-sync authority. AppAuthorities is keyed by sync namespace, instances.<persona>.<ownerId>.<appId> (appNamespace). An instance's state is the assembled view: $.app and $.screens sparse, $.route, and $.data by binding, holding a copy of each shared dataset and the persona's records, with the instance laid over it. Its logic is the assembled logic, the app's units plus its bound modules. InstanceNamespaceStorage keeps that state as the instance (the diff and the persona records), never the shared copies or $.server. It keeps no sync log, so a loaded instance's revision is the clock in milliseconds and a view from before a restart gets a snapshot. AuthorityInstanceStates assembles the app on every call and restarts the instance over a changed definition; a change of only the records of a shared dataset is not one (definitionText).
Instances that bind one shared dataset see each other's changes through DatasetHub (src/infrastructure/sync/), which each instance's authority is attached to when it starts:
Before a change is applied, the records it touches are checked against the dataset's model, synchronously, with the model read once and again when it changes. A client change is refused in the authority's
onChangehandler; a write of the instance's logic or of a tool is refused by the data gate thatAppAuthoritiesgives eachAppLogic(InstanceDataGate), and the logic engine asks it asLogicHost.guard, so asave-datagets the reason as itsrejectedresult. The reason isSUI-MODEL-FIELD's message, naming the record key and the field.After a change is applied (
onAppliedfor a client change, the gate'sappliedfor a server write), each record it touched is written to the dataset part whole withWriteData, one write-through at a time per dataset. A change that leaves the records as the dataset has them writes nothing, so instances whose rules derive the same value settle. A committed write-through is applied to every other binding of the dataset with onewriteAlleach (AppAuthorities.receiveInstance, after which that instance's logic sees the change); a failed one puts the stored records back into the instance and is reported (Shared data not written).A write of the dataset part from elsewhere (a tool, a rename, a model change) raises its revision past the hub's, and what changed in the records is applied to every binding.
Persona bindings are never attached. Fan-out writes are server writes, which fire no
onApplied, so the hub never sees them again.SetPartStatewrites$.app,$.screens.{screen}and persona$.data.{binding}paths, and refuses content,$.themeand the other definition roots (definition-path), shared datasets (shared-dataset, namingui_data_write) and$.route(usenavigate).
The live view of an owner app has the same URL, /apps/<appId> with the app part's id. Its page shows the assembled app (InstanceViews: the app node, the screens, the themes, the bound data and modules) with the default persona's instance laid over it (the runtime's load takes it as instance), and its sync client talks to that instance's authority (data-namespace on the page). Besides $.data and $.app, the view syncs each screen's articulation ($.screens), the route ($.route) and the persona's choice of theme and overlays ($.theme.active, never the tokens); a route moved in another view arrives as a navigate command, and a theme picked in another view as writes to $.theme.active (the theme first). An overlay the server applies to one view (the mode of ui_screenshot, ?mode=) stays in that view and is not synced. Every part change that succeeds (IndexedUiPartRepository.onChange) reaches the open views of the apps that show the part (LiveViews.partChanged): the page writes a change of the app node in place and loads a changed theme, locale, screen or component again in full. A changed definition also restarts the instance's authority, so the views reconnect and get its state. The revision a view of an owner app reports is counted by InstanceViews, one more each time the assembled document changes, from 1 at start. BrowserPreview.open takes a screen and params (?screen=<name>¶ms=<json> on the view URL) to open the app there instead of where its instance is.
Converting the old apps
stateui-mcp convert turns each app folder that still has an app.json into owner parts, once. Stop the server first.
node dist/cli.js convert --data-dir ./data --dry-run # print the report, change nothing
node dist/cli.js convert --data-dir ./data # convert
node dist/cli.js convert --data-dir ./data --purge # later: delete data/.converted/For each app, convertDataDir (src/config/) runs splitDocument of @punyts/stateui-app/core on the document, with the live data of state.json in place of the document's (the articulation is dropped), and creates the parts: its themes, a dataset and an inferred model for each key of data, its components, then the app, whose part id is the old app id. Names that a stored part or an earlier app of the run has get another one, and the report lists them. The default persona's instance is cleared, then app.json and state.json move to data/.converted/<appId>/; errors.json, files.json and the uploaded bytes stay in data/<appId>/, so the app's files are still listed under the same id. An app the converter cannot split (a rule that switches a hidden tab strip, for one) keeps its files where they are and is listed with the reasons. The plan is made from the stored files alone, so a dry run prints the same report and writes nothing. A second run converts nothing new; when an earlier run created an app's parts and stopped before moving its files, the next run only moves them. The command exits 0 with a report, Nothing to convert in <dir>. when there is nothing, and 2 for an unknown option.
Run it once after installing this version. The old tools (ui_app_create with no app node, and the tools that read an app by appId) are gone and the server no longer reads app.json, so an app that is not converted is not reachable. The upgrade:
Stop the server.
stateui-mcp convert --dry-runand read the report: the parts each app becomes, the names that changed and the apps that cannot be converted, with the reasons.stateui-mcp convert.Start the server and check the apps;
.converted/still holds the old files.stateui-mcp convert --purge.
An app that is not converted keeps its folder; fix what the report names in that app (with the previous release) or rebuild it from parts. The --statenet option and Persisted apps (sync: "persisted") are gone with the old store: their state lived in the statenet under apps.<appId>, which this version does not read, so convert such an app from its app.json (its $.data snapshot is read from state.json, which a statenet-backed app does not have) or rebuild it.
Security notes
No port. The server listens on nothing: MCP is on stdio, and it reaches the statenet as a client.
The statenet has no authentication. It listens on loopback only, refuses a
Hostthat is not loopback and lets in web pages of the origins it is told (--allow-origin) only. Anyone who can reach it can read and change every app's live state; a page of an allowed origin can do what the app's views do. Do not put it on a network without your own authentication in front.The view relay. The statenet relays a page's emits to the server only, and the server's to the pages, so one page cannot send another the document or a command. The server takes a page's file requests for the app of its namespace only.
The embedded endpoint (
startHttpServer) binds127.0.0.1unless told otherwise. While it is bound to a loopback address, a request whoseHostis notlocalhost,127.0.0.1or[::1]is refused (DNS rebinding), and aPOSTwith anOriginheader from another host is refused. It has no authentication of its own:@punyts/magneticembeds it with atenantfunction that finds the signed-in user's workspace, so each user reaches only their own apps.An app in the page shares the page's origin. With
?surface=pagethe app's expressions run in the page, which therefore allows'unsafe-eval', and the app could reach what the page can: its cookies, its storage and its own server. Use it only for apps the signed-in person owns, as Magnetic's editor does.Apps run code. An app document can contain binding expressions that run in the sandboxed frame. The frame has no network (
connect-src 'none') and no forms. Its origin has its own storage, and it can read cookies that other local servers set for the same host name, but it has no way to send them anywhere except as app events to the server. The headless Chromium is a real browser on your machine: do not point it at documents you do not trust.Paths. Only UUIDs reach a file path. A file name is metadata and never part of a path.
Uploads. The type is sniffed from the bytes; the type the client claims is ignored. HTML, SVG, XML and executables are refused.
3D models (GLB only). A file is
model/gltf-binarywhen it starts with theglTFmagic number, version 2, and a header length equal to its size (detectMagicType(head, size)insrc/domain/UiFile.ts). A.gltf(JSON with external buffers and images, which the frame could not fetch), a GLB cut short, of another version or with a wrong length, and any file named.glbor.gltfthat is not such a GLB are refused with415 unsupported_type.ui_file_readanswers a GLB's reference withtext: null. The live view's host takes the allowed list fromsrc/domain/UiFile.tsitself;@punyts/stateui-componentskeeps a copy, and a test in each library pins both to one literal. The 10 MiB file limit is the model limit: a product model with a few hundred thousand triangles and 1K to 2K textures usually fits, one with several 4K textures or a scanned mesh often does not, and the Draco, Meshopt and KTX2 compression that would shrink it is not supported (G3.7b refuses it). Reduce the texture sizes or the mesh before uploading.
Develop
npm run typecheck # server and browser host script
npm run build # dist/ (server, Vite plugin) and dist/browser/host.js (the embedded endpoint's host script)
npm test # Vitest; the Playwright tests skip themselves when Chromium is missing
npm run dev # the statenet and the view page, for a client that runs the server on stdiotest/statenetBridge.test.ts drives the server through a real statenet with a page that speaks the protocol by hand; test/statenet.integration.test.ts runs the view page on Vite, a statenet, the server and Chromium together, and the command on stdio.
Layout: src/domain (pure rules, and the view relay's envelopes), src/application (ports and use cases), src/infrastructure/storage (the JSON file adapters), src/infrastructure/mcp (tools and server), src/infrastructure/statenet (the server's side of the views in a statenet), src/infrastructure/view (the view page's Vite plugin), src/infrastructure/http (the embedded endpoint: routes, pages, policy), src/infrastructure/preview (the hub of live views and the Playwright adapter), src/browser (the view that runs in the page: host.ts, its channels, statenetView.ts for the view page and hostPage.ts for the embedded endpoint), view/ (the Vite project of the view page), src/config (options and composition), src/testing (fixtures and in-memory fakes for tests; not built).
License
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Build, run, inspect, and continue AgentScript workflows on connected Super Chrome and Mac clients.
Drive a live Cinevva game session: edit game files, import CC0 assets, preview changes.
Draw diagrams, build HTML pages and write Markdown in a live editor the user sees.
Run multi-step tasks in a real Chrome browser: persistent environments, live view, human takeover.
Related MCP Servers
- AlicenseAqualityBmaintenanceEnables agents to inspect and drive Electron or Chrome/Chromium apps via the Chrome DevTools Protocol, exposing DOM snapshots, console logs, network requests, and gated interactions like clicking, typing, and navigating.668 npm1MIT
- AlicenseNot gradedqualityAmaintenanceEnables an AI agent to observe, plan, and act inside a real browser session by exposing navigation, snapshot, click, type, and screenshot MCP tools over local JSON-RPC and SSE. It runs a Playwright-backed browser in-process and provides stable element references for reliable actions.MIT
- AlicenseAqualityCmaintenanceEnables AI agents and MCP hosts to drive a persistent headless Chromium browser through Playwright, navigating pages, mapping visible fields and actions, clicking, typing, scrolling, and capturing screenshots via stdio tool calls. It also powers a local AI Test Studio dashboard that generates and runs structured end-to-end test plans with assertions, per-step timing, and screenshot evidence.41MIT
- AlicenseBqualityCmaintenanceEnables AI agents to build and audit web UIs by serving a fixed workflow and rule-priority guide, running deterministic static linting of source, rendering pages headlessly at multiple widths for screenshots and accessibility snapshots, and gathering element-level design feedback. All output is written only to a local log folder, leaving project files untouched and external network access blocked by default.6MIT