Chapter 25
Serialization, AJAX and MCP
25.1 Serialize and load values#
const data = await form.serialize({ encryptionKey: session.encryption });
// { fullName: 'Ada Lovelace', phone: '+447911123456', dateOfBirth: '2001-11-22',
// experience: 3, newsletter: true, password: 'pfe1.…' }
- Values are JSON-safe (strings, numbers, booleans, null). Dates are ISO strings and phones are E.164.
- Password fields are encrypted as PFE1 envelopes bound to the key's single-use challenge and the field name. Empty
ones become
''. - Without
encryptionKey,serialize()throws if a password field has content, so plaintext can't slip out. Usesecrets: 'omit'to leave password fields out (e.g. to save a draft locally).includeandexcludepick fields. form.values()still returns raw values:Secrethandles for passwords, whoseJSON.stringifyis"[redacted]".
const { applied, skipped } = form.setValues(record, { validate: true });
// skipped: { password: 'secret field', plan: 'not allowed', nope: 'unknown field' }
setValues fills fields from saved data, a record being edited, or an agent's draft. Each value goes through the
control's own checks: text is sanitised and length-limited, and choices must be one of the options. Password and
one-time-code fields can never be set this way. With mountPixiForm, use handle.form.serialize() and
handle.form.setValues().
25.2 AJAX without code (action)#
await mountPixiForm(host, {
fields: [/* … */],
action: '/api/register', // POST target
session: '/api/session', // → { csrfToken, encryption }
});
On submit, PixiFormUI validates, serializes with password fields encrypted, and POSTs JSON via secureSubmit, which
enforces same origin, sends the CSRF header, and refuses redirects. After a 403 it fetches the session once and
retries. The server replies { ok, message?, fieldErrors?, challenge? }:
fieldErrorsappear under the matching fields, and the first one gets focus;messageis shown as a toast;challengereplaces the used one, since PFE1 challenges are single-use.
Cross-origin endpoints need submitOptions: { allowedOrigins: ['https://api.example.com'] } and HTTPS. With
<pixi-form>, action also works from plain config, and no pixiform-submit event is fired.
For full control, keep using onSubmit with form.serialize() and secureSubmit() (§4), or build your own
onSubmit with actionSubmitter({ action, session }).
25.3 JSON Schema from the shared rules#
import { rulesToJsonSchema, publicRules } from 'pixiform'; // or shared/jsonSchema.ts on the server
const schema = rulesToJsonSchema(registrationRules); // secrets excluded by default
This produces JSON Schema 2020-12: types, minLength/maxLength, pattern, enum, minimum/maximum,
format: date, const: true for consent, and readable descriptions for rules JSON Schema can't express (relative
dates, ages, weekdays). Use it for MCP tools, OpenAPI or other form builders. The server stays authoritative with
validatePayload(), and validatePartial() validates drafts that contain only some fields.
25.4 MCP: let an AI assistant start a registration#
server/mcp.ts is an MCP server (stdio, no dependencies) with two tools:
| Tool | Effect |
|---|---|
validate_registration |
Checks details against the shared rules. Read-only; returns field errors and what's missing. |
start_registration |
Saves the details as a draft and returns a link for the person to finish. |
Passwords never pass through the assistant. The tools' schema has no password, password-confirmation or terms
fields (shared/agent.ts), and calls that include them are refused. The flow is:
- The assistant collects non-secret details and calls
start_registration. - The MCP server POSTs them to
/api/draftswith a bearer token (AGENT_API_TOKEN, or.keys/agent-tokenlocally). The server validates them withvalidatePartialand stores a draft for 30 minutes. - The assistant gives the person
https://your-site/#draft=<id>. The 128-bit id is in the URL fragment, so it isn't sent in requests orRefererheaders. - The page claims the draft once (
POST /api/drafts/claim, which needs a session and CSRF token), prefills the form withsetValues, and the person sets the password and accepts the terms themselves.
Run it and add it to an MCP client:
npm run mcp # PIXIFORM_URL=https://your-site AGENT_API_TOKEN=… in production
{ "mcpServers": { "pixiform": { "command": "node",
"args": ["--experimental-strip-types", "--no-warnings", "/path/to/pixiform/server/mcp.ts"],
"env": { "PIXIFORM_URL": "http://localhost:8787" } } } }
Agents driving a real browser (Playwright MCP, Chrome DevTools MCP) can also fill the canvas form directly. They find fields through the accessibility outline (§18), and their keystrokes count as trusted input. They can't read values back.