Guides

mx for AI agents

A paste-ready system prompt, the React, Vue and Svelte habits that break mx, and a checklist to run before handing code back.

Why agents get mx wrong#

If you are an AI coding assistant writing mx, read this first. Most mistakes come from one habit: pattern-matching mx onto React, Svelte or Vue. mx is a DOM reconciler rather than a framework, so it has no JSX, hooks, virtual DOM, signals or build step. The API is four names and a handful of rules that fit in a system prompt.

Key ideas

  • mx, dom, define and components are the whole API.
  • Attributes and events use native DOM names in lowercase, never React spellings.
  • State changes go through this.$({...}), which merges and re-renders.
Ships in the package too

The npm package @tltdsh/mx bundles an AGENTS.md with the same rules, so an agent editing an mx project picks them up locally. Read it at cdn.jsdelivr.net/npm/@tltdsh/mx/AGENTS.md, and see What mx Is Not for every React, Vue and Svelte feature that is deliberately absent and what replaces it.

Paste-ready system prompt#

Copy this block into an agent's system prompt verbatim. It covers the four API names, define semantics, the mx vs dom decision, $state merge rules, attributes, conditionals, keyed rows and the hard don'ts.

mx-agent-rules.jsJS
// ── MX ENGINE: RULES FOR WRITING CODE ──
// MX is a sub-1KB DOM reconciler. It is NOT React/Vue/Svelte. There is
// no JSX, no hooks, no virtual DOM, no signals, no build step.
// Loading the classic CDN script exposes mx, dom, define, components on window.
// The ESM build exports those names instead; it does not create globals:
//   import { mx, dom, define, components } from '@tltdsh/mx';
// Both builds require a browser DOM. See /installation for CDN module URLs.
// The four API names:
//   mx.tag(attrs?, ...children)   -> a description ARRAY (cheap), for render()
//   dom.tag(attrs?, ...children)  -> a real HTMLElement you can hold & mutate
//   define(name, spec)            -> register in MX, not customElements
//   components                    -> the component registry object
//
// DECISION RULE (mx vs dom):
//   Need a handle to call .$() / read .value / keep across renders? -> dom.tag()
//   Just handing output to render() to reconcile?                   -> mx.tag()
//   When unsure, use mx.

// ── COMPONENTS ──
define('user-card', {
    // $ runs when render() reaches an mx.userCard(...) description, or when
    // .$() is called directly. A dom() handle passed to render() is only
    // placed, never re-run: call el.$({...}) to update it.
    // It is not an attach/detach hook. It receives the MERGED $state object.
    // Destructure props with defaults. Return ONE mx description, OR an array
    // of children. A bare DOM node throws: return [node].
    // Write $(props) {} or $: function(props) {}. Never an arrow $: props =>,
    // which loses this.
    $({ name = '', active = false }) {
        return [
            mx.span({ class: 'name' }, name),
            active && mx.span({ class: 'badge' }, 'online')
        ];
    }
});
container.render(mx.userCard({ name: 'Ada', active: true }));
// On a component, attrs are props ONLY: class, id, title, aria-* go to $ and
// never become HTML attributes on <user-card>. Set host attributes yourself
// with this.$attrs({...}) inside $, or put them on the children you return.
// Children passed to mx.userCard(attrs, ...children) are ignored. The
// component's children are whatever $ returns.
// dom.userCard() with NO attrs object creates the element but never runs $
// (it stays empty, $state is undefined). Pass props: dom.userCard({}).

// ── STATE ($state) ──
// this.$({ key: val }) does Object.assign($state, {key:val}) then re-runs $.
// A parent's el.$({...}) merges the same way. Because the merge runs BEFORE
// your $ function, THE PARENT ALWAYS WINS any key it re-passes (controlled
// components). Keys you don't pass survive untouched.
//   this.$({ count: 5 })      // correct: merge + re-render
//   this.$state.count = 5     // mutates state but does not re-render
// Controlled one-time default initialization inside $ is valid; updates use this.$.
// For state that must survive parent re-passes, seed a private this._x once.

// ── ATTRIBUTES (native DOM names, lowercase - NOT React) ──
mx.button({ onclick: handler });          // events: lowercase, set as property
// Only native on* properties fire. A custom onsave / onUserPicked is stored as
// a plain property and silently never fires; use addEventListener on a dom()
// handle (outside $) for CustomEvents.
mx.div({ class: 'active' });              // class - NOT className
mx.label({ for: 'email' });               // for - NOT htmlFor
mx.input({ '.value': text });             // '.name' sets a JS property directly
// value / checked / selected: render() syncs attribute AND property. dom.tag(attrs)
// and el.$attrs() only setAttribute, so a typed value or clicked box stays.
// Outside render(), write '.value' / '.checked' / '.selected' instead.
mx.button({ disabled: true });            // true -> setAttribute('disabled','true')
mx.button({ disabled: null });            // null / false / undefined -> removed
mx.div({ style: 'width:' + pct + '%' });  // style is a STRING, never an object

// ── CONDITIONAL RENDER ──
// render() skips false / null / undefined, but renders 0 as a text node "0".
!!list.length && mx.ul(...list.map(x => mx.li(x.name)));  // !! guards the 0 leak
// Arrays in children flatten, nested ones too: mx.ul(items.map(...)) and
// mx.ul(...items.map(...)) render the same. (mx 1.4.1 and earlier stringify an
// unspread array to "li,,a,li,,b"; spread if the code must run there too.)

// ── KEYED, STATEFUL ROWS (identity match) ──
// Real dom() nodes match by identity, so mx physically moves them and their
// internal state travels with them. Positional mx() rows would leave typed
// input / checkbox state at the old index after a sort.
// key is not special: mx.li({ key: id }) writes a plain key="..." attribute and
// rows still match by position (tag name, left to right). For identity, use this Map.
this._rows ||= new Map;
for (let [id] of this._rows)
    if (!items.find(i => i.id === id)) this._rows.delete(id);
for (let it of items) {
    let row = this._rows.get(it.id) || this._rows.set(it.id, dom.userRow()).get(it.id);
    row.$({ data: it });
}
container.render(...items.map(i => this._rows.get(i.id)));

// ── HARD DON'TS ──
// - No onClick / className / htmlFor / JSX. Lowercase DOM names only.
// - No PascalCase tags: mx.UserCard() -> tag "-user-card", and render() throws
//   InvalidCharacterError (Chromium). define('UserCard') does not throw. Use mx.userCard().
// - For updates use this.$({...}); direct state writes do not schedule rendering.
// - Never mutate a prop array in place: use [...items].sort(), not items.sort().
// - Never addEventListener inside $() (stacks each render). Assign this.onclick = fn.
// - clearInterval(this._interval) at the TOP of $() before re-arming a timer.
// - Hoist static option/config arrays OUT of $(); don't re-allocate them per render.
// - Don't read rendered text (el.textContent) to drive logic; read $state / data.
// - this.$({}) with an empty object is a code smell - pass the actual change.
  1. PastePut the block in the system prompt, unedited.
  2. GenerateThe agent writes mx with the rules in context.
  3. Self-checkRun the checklist under Verify your output.
  4. TestAssert invariants at the DOM.

The same rules also live in llms.txt for tools that fetch a site's plain-text summary. How to check the result at runtime is on the Testing page.

Install it as an agent skill#

The mx skill holds the rules from llms.txt, the readable engine source and four samples from these docs. Install it once and your agent loads it whenever it sees mx code, then reads the engine source when a rule leaves a question open.

  1. Claude Code: unzip it into ~/.claude/skills/, which gives you ~/.claude/skills/mx/SKILL.md.
  2. claude.ai: upload the zip under Customize > Skills.
  3. Other agents: point their skills directory at the unzipped mx/ folder.
Download the skill

Mistakes agents actually make#

Each pair is a real failure mode, with the wrong version first and the fix below it. The examples are deliberately generic, such as user tables, settings forms and dashboards. The first group is syntax carried over from React, the single biggest source of broken mx.

React attribute and event names

React names fail silently. Depending on the name, the handler never fires, the CSS selector never matches or the label never associates.
// React names: not the intended DOM APIs
mx.button({ onClick: save }, 'Save');
mx.div({ className: 'card' });
mx.label({ htmlFor: 'email' }, 'Email');
// Native DOM names, lowercase
mx.button({ onclick: save }, 'Save');
mx.div({ class: 'card' });
mx.label({ for: 'email' }, 'Email');
mx.input({ tabindex: 0 });

JSX and object styles

There is no JSX. mx.tag(attrs, ...children) is the only element syntax, and style is a string, not an object.
// JSX / object style - not a thing
return <div className="row">{name}</div>;
mx.div({ style: { width: pct + '%' } });   // -> style="[object Object]"
// Function calls, string style
return mx.div({ class: 'row' }, name);
mx.div({ style: 'width:' + pct + '%' });

PascalCase tags

Tag names are converted from camelCase to kebab-case with an unanchored /[A-Z]/g. A leading capital produces a leading hyphen, which is not a valid element name: render() throws InvalidCharacterError in Chromium.
// PascalCase -> tag "-user-card"
mx.UserCard();                    // render() throws InvalidCharacterError (Chromium)
define('UserCard', { $() {} });   // no error: registers '-user-card', never matched
// camelCase call site, kebab or camelCase in define (both convert)
mx.userCard();
define('user-card', { $() {} });   // define('userCard', ...) also works

The key prop

mx has no key prop. mx.li({ key: row.id }) writes a plain key="..." attribute, the rows still match by position and nothing warns. For identity across reorders, keep dom() nodes in a Map keyed by id.
// key is only an attribute: rows stay positional
list.render(...items.map(row => mx.li({ key: row.id }, row.name)));
// Keyed dom() Map: rows match by identity and move
let rows = new Map;
for (let row of items) {
    let li = rows.get(row.id) ?? rows.set(row.id, dom.li()).get(row.id);
    li.render(row.name);
}
list.render(...items.map(row => rows.get(row.id)));
Component method syntax

Method shorthand $(props) {} is the preferred style. $: function(props) {} is equally valid JavaScript and supported by define(). A $: statement label, Svelte-style, does not create reactive behavior.

JS
// Valid function-valued property; shorthand below is preferred
define('foo', { $: function(props) {} });
// $: total = a + b; // ordinary JS label, not reactive

// Method shorthand; derive values as plain locals inside $
define('foo', { $(props) {} });
define('sum', { $({ a = 0, b = 0 }) { return mx.span(a + b); } });

Rendering mistakes#

What render() accepts as a child, and how it matches old children to new ones.

The falsy-0 text-node leak

render() skips false, null and undefined, but 0 is valid content and renders as the text "0". Any number on the left of && leaks.
// When the array is empty, a bare "0" appears in the DOM
users.length && mx.div({ class: 'list' }, ...rows);
count && mx.span('Unread: ' + count);
// Coerce to boolean with !!
!!users.length && mx.div({ class: 'list' }, ...rows);
!!count && mx.span('Unread: ' + count);

Positional reuse of stateful rows

mx reconciles mx() children left to right by tag name, not by key. Reorder a list of positional rows and the DOM nodes stay put while their content updates, so a half-typed input or a checked box stays at the old index. Use real dom() nodes in a keyed Map: they match by identity and physically move.
// Positional: the typed note stays at row 0 after a sort
container.render(...rows.map(r => mx.div(
    mx.span(r.name),
    mx.input({ placeholder: 'note...' })   // this input never moves
)));
// Keyed dom() rows move by identity, state intact
this._rowMap ||= new Map;
for (let [id] of this._rowMap)
    if (!rows.find(r => r.id === id)) this._rowMap.delete(id);
for (let r of rows) {
    let row = this._rowMap.get(r.id) || this._rowMap.set(r.id, dom.userRow()).get(r.id);
    row.$({ data: r });
}
container.render(...rows.map(r => this._rowMap.get(r.id)));

State mistakes#

The declarative flow is always this.$({...}), which merges the change and re-runs $. Everything in this group routes around it.

Mutating $state directly

Assigning to $state skips the merge and never re-renders.
// Mutates the state but leaves the rendered DOM unchanged
this.$state.selected = id;
// Go through $()
this.$({ selected: id });

The empty this.$({}) smell

An empty this.$({}) merges nothing and re-runs $ with unchanged state. It almost always means the component mutates this._x as a hidden side effect and uses the empty call to force a paint. Make the change part of state instead.
// Hidden data flow - what changed?
$() {
    this._items.push(newRow);
    this.$({});
}
// The change IS the state update
$({ items = [] }) {
    return mx.button({ onclick: _ => this.$({ items: [...items, newRow] }) }, 'Add');
}

Mutating prop arrays in place

Props point at the parent's data. .sort(), .reverse() and .splice() mutate it, which is a side effect that reaches outside the component. Copy first.
// Sorts the parent's array
$({ rows = [] }) {
    rows.sort((a, b) => a.name.localeCompare(b.name));
}
// Copy, then sort the copy
$({ rows = [] }) {
    let sorted = [...rows].sort((a, b) => a.name.localeCompare(b.name));
}

Driving logic off rendered text

Never read a value back out of the DOM (el.textContent, an input's displayed value) to decide what to do next. The rendered text is an output of state, so treat state and data-* attributes as the source of truth.
// Parsing your own output back into logic
let count = Number(this.querySelector('.count').textContent);
if (count > 0) this.$({ hasItems: true });
// Read the state (or a data attribute) directly
if (this.$state.items.length) this.$({ hasItems: true });

Re-render hygiene#

Every $() call runs the whole function again. Anything it allocates or arms, it does on every render.

Interval stacking across re-renders

An un-cleared setInterval stacks a new timer each render.
// One extra timer per re-render
$({ live = false }) {
    if (live) this._timer = setInterval(refresh, 1000);
}
// Clear at the TOP, before any conditional
$({ live = false }) {
    clearInterval(this._timer);
    if (live) this._timer = setInterval(refresh, 1000);
}

Static arrays re-allocated inside $()

Constant option lists, column configs and lookup tables do not belong inside $(). A fresh array is built on every render, and passing a new identity downstream defeats any memoization.
// New array every render
define('status-select', {
    $({ value }) {
        let options = ['open', 'pending', 'closed'];   // re-allocated each call
        return mx.select({ '.value': value },
            ...options.map(o => mx.option({ value: o }, o)));
    }
});
// Hoist constants to module scope
let STATUSES = ['open', 'pending', 'closed'];
define('status-select', {
    $({ value }) {
        return mx.select({ '.value': value },
            ...STATUSES.map(o => mx.option({ value: o }, o)));
    }
});

Verify your output#

Before returning mx code, check it against this list. Every item maps to a mistake above.

Checklist: before you hand code back

  • Events are lowercase (onclick), attributes are DOM names (class, for), no className / htmlFor / JSX.
  • Every tag is camelCase or kebab-case, with no leading capital.
  • Any number on the left of && is guarded with !!.
  • State changes go through this.$({...}): never this.$state.x = ..., never an empty this.$({}).
  • Prop arrays are copied before sort, reverse or splice ([...arr]).
  • clearInterval / clearTimeout sits at the top of $(), and addEventListener never goes inside $().
  • Constant arrays and objects are hoisted out of $().
  • Stateful list rows use a keyed dom() Map, not positional mx() rows.
  • Need a handle (calling .$() later)? It is a dom.tag(), not an mx.tag().
  • Logic reads from $state or data, not from rendered text.
Cheat SheetThe whole API on one page.GotchasThe full catalog of pitfalls, with fixes.API ReferenceEvery name, argument and return value.What mx Is NotFramework features that are absent on purpose.