Describe Form
describeForm() from @formkit/addons returns a plain, JSON-serializable description of a form: every field's name, address, type, label, validation rules, options, validity and error messages. It reads FormKit's node tree — not the DOM — so it works the same way in Vue and React, and it's ideal for:
- AI agents and tools that need to know what a form wants before filling it in (pair it with
node.input()andsubmitForm()). - Generated tests and fixtures.
- Documentation and debugging of large or schema-driven forms.
describeForm() is available in @formkit/addons 2.3.0 and later.
Installation
npm install @formkit/addons
describeForm is a plain function (not a plugin), so there is nothing to register — import it wherever you need it.
Usage
import { getNode } from '@formkit/core'
import { describeForm } from '@formkit/addons'
const form = getNode('signup')!
const description = describeForm(form)
Any FormKit node works — get it with getNode(id), or from a ref:
import { useRef } from 'react'
import { FormKit } from '@formkit/react'
import { describeForm } from '@formkit/addons'
export function Signup() {
// In React, the <FormKit> ref is the node itself.
const signup = useRef(null)
const describe = () => describeForm(signup.current)
return <FormKit ref={signup} type="form">…</FormKit>
}
For a form with an email, a password, and a select, the result looks like this:
{
"name": "form_1",
"address": "",
"type": "form",
"nodeType": "group",
"required": false,
"rules": [],
"valid": false,
"errors": [],
"children": [
{
"name": "email",
"address": "email",
"type": "email",
"nodeType": "input",
"label": "Email",
"required": true,
"rules": [{ "name": "required", "args": [] }, { "name": "email", "args": [] }],
"valid": false,
"errors": ["Email is required."]
},
{
"name": "plan",
"address": "plan",
"type": "select",
"nodeType": "input",
"label": "Plan",
"required": false,
"rules": [],
"options": [
{ "label": "Free", "value": "free" },
{ "label": "Pro", "value": "pro" }
],
"valid": true,
"errors": []
}
]
}
Driving a form
Every field includes an address relative to the node you described, so you can get back to the node with at():
const form = getNode('signup')!
for (const field of describeForm(form).children ?? []) {
if (field.type === 'email') form.at(field.address)?.input('[email protected]')
}
Filling a form with fillForm()
The write side of describeForm(). fillForm() sets values by address (or nested objects/arrays), accepts option labels for inputs with options, waits for the form to settle (debounces and async validation), and reports what happened (@formkit/addons 2.4.0+):
import { getNode } from '@formkit/core'
import { fillForm } from '@formkit/addons'
const result = await fillForm(
getNode('signup')!,
{ email: '[email protected]', plan: 'Pro', 'address.city': 'Lisbon' },
{ submit: true }
)
{
"valid": true,
"settled": true,
"submitted": true,
"fields": [{ "address": "email", "valid": true, "errors": [] }],
"invalid": [],
"errors": [],
"unknown": [],
"unmatched": [],
"skipped": []
}
- Addresses are the
addressvaluesdescribeForm()returns (users.0.name), or nested objects/arrays that mirror groups and lists. They're matched by literal child names — existing list items can be filled, but new list items (repeater rows) aren't created. - Options: give an option's value or its label (case-insensitive; values win, first match wins). A value that matches no option is not written and is listed in
unmatched(no-such-option). If the options load asynchronously, the value is written and flaggedoptions-not-loaded. - Disabled inputs and non-input targets are listed in
skipped, not written. invalidlists every input, group or list with errors — not just the ones you filled — including server errors set withsetErrors()(for example fromonSubmit).errorshas messages on the form itself.validisfalseif anything is blocking or has an error message.submit: truesubmits through the form's normal handler.submittedistrueonly ifonSubmitran and completed; a thrown/rejectedonSubmitis reported assubmitError.timeout(default5000ms) bounds the wait for validation and foronSubmit;settled: falsemeans it ran out (and a submit is skipped). In tests with fake timers, advance timers while awaitingfillForm().submittedis detected through the form'ssubmithook: a custom submit middleware that never callsnext()will reportsubmitted: false.strict: truethrows — before writing anything — on unknown addresses, unmatched options, or skipped fields.
Options
describeForm(node, {
values: true, // include current values (default: false)
redact: ['email'], // extra input types to redact (added to the defaults)
errors: 'visible', // only errors currently shown to the user (default: 'all')
})
values— Values are left out by default, so a description can be logged or sent to an agent without leaking user data. Setvalues: trueto include them.redact— Extra input types whose values are never included, even withvalues: true. They're added to the defaults —passwordandhidden(CSRF tokens and the like) are always redacted. Redacted fields are markedredacted: true. Passredact: falseto include everything.errors—'all'(default) includes every blocking validation and error message;'visible'includes only messages the user can currently see, respecting each input'svalidation-visibility.
What's included
| Property | Description |
|---|---|
name | The node's name (its key in the parent's value). |
address | Dot path from the described node, e.g. users.0.email. Empty for the described node itself. |
type | The input type (text, select, form, repeater, …). |
nodeType | input, group, or list. |
label, help, placeholder | When set. |
disabled, multiple | Present (and true) when set. |
required | Whether the required rule is applied. |
rules | Validation rules with their arguments. |
options | Options with their real values (option groups are flattened, with each option's group label; disabled options are flagged). |
optionsLoader | true when options are loaded by a function. The function is never called; options it has already loaded are included. |
valid | true when neither the node nor its descendants have blocking messages. |
errors | Error message strings for the node. |
value | The current value, when values: true and not redacted. |
children | Descriptions of child nodes, for groups and lists. |
The output is JSON-serializable: dates become ISO strings, regular expressions their source (e.g. "/^\\d+$/"), Maps and Sets arrays, and Files { name, size, type }. Functions and circular references are dropped, and other non-plain objects are copied as plain objects, so some detail can be lost.
Export JSON Schema
toJSONSchema() converts a form node into JSON Schema 2020-12. It uses the same node description as describeForm() and works in Vue and React. Groups become objects and lists become arrays; disabled and ignored nodes are omitted. Rules that cannot be represented are retained in x-formkit-rules and the description, so JSON Schema validation is not a replacement for FormKit validation.
import { useRef } from 'react'
import { FormKit } from '@formkit/react'
import { toJSONSchema } from '@formkit/addons'
export function Signup() {
const signup = useRef(null)
const schema = () => toJSONSchema(signup.current)
return <FormKit ref={signup} type="form">…</FormKit>
}
For a tool-calling API, pass the schema in the shape expected by your provider, then fill the form with the returned arguments:
import { getNode } from '@formkit/core'
import { fillForm, toJSONSchema } from '@formkit/addons'
const form = getNode('signup')!
const tools = [{
name: 'fill_signup',
description: 'Extract signup details',
input_schema: toJSONSchema(form),
}]
// Send `tools` to your model provider and parse its tool arguments.
await fillForm(form, toolArguments)
For server-side validation, export the schema from a form configured with the same fields and rules, then send or save it for your server. With Ajv and its formats plugin installed:
import Ajv2020 from 'ajv/dist/2020.js'
import addFormats from 'ajv-formats'
const ajv = new Ajv2020({ strict: false }) // permits x-formkit-rules
addFormats(ajv)
const validate = ajv.compile(schema)
if (!validate(requestBody)) {
console.error(validate.errors)
}
Pass { dialect: 'draft-07' } for draft-07 consumers, { labels: true } to include option labels as oneOf titles, or { strict: true } for strict structured-output modes: every object is closed (additionalProperties: false) and every property is listed in required, with optional fields made nullable (e.g. ["integer", "null"]) so the model can leave them empty. { values: true } includes current input values as defaults, except passwords and hidden inputs; treat the resulting schema as potentially sensitive. List item schemas are inferred from existing children; an empty list has an unconstrained item schema. Formats and unmappable rules depend on the validator and must also be enforced by the server where needed.
Expose forms to browser agents (WebMCP)
createWebMCPPlugin() is experimental (@formkit/addons 2.9.0+). It targets WebMCP, a draft browser API that is still changing, so this plugin's options and tool shapes may change in minor releases.
WebMCP lets a page hand tools directly to an AI agent running in the browser, through document.modelContext (older drafts use navigator.modelContext). With createWebMCPPlugin(), every FormKit form registers tools built on describeForm() and fillForm(). An agent can then read the form, fill it in, and (if you allow it) submit it through the real FormKit node, without scraping the DOM.
// formkit.config.react.jsx
import { defineFormKitConfig } from '@formkit/react'
import { createWebMCPPlugin } from '@formkit/addons'
export default defineFormKitConfig({
plugins: [createWebMCPPlugin({ submit: true })],
})
Every type="form" registers its tools when it is created and unregisters them when it is destroyed. If the browser has no modelContext, for example because it doesn't support WebMCP or the code is running during SSR, the plugin does nothing.
WebMCP tools
<id> is the form's id, lowercased, with every character outside [a-z0-9_] replaced by _. For example, id="sign-up" becomes formkit_fill_sign_up. Give each form a stable, unique id; if two forms produce the same tool name, only the first one is registered.
| Tool | Arguments | Does |
|---|---|---|
formkit_describe_<id> | none | Returns describeForm(form, { values }). Marked readOnlyHint. |
formkit_fill_<id> | { values, strict? } | Runs fillForm(form, values, { strict }) and returns its result. On a strict failure it returns { error } instead of throwing. |
formkit_submit_<id> | none | Only registered when submit: true. Submits through the form's normal handler (validation runs first, so an invalid form is not submitted) and returns { valid, errors, submitted, submitError? }. Marked consequentialHint. |
The fill tool's inputSchema is generated from the form. values has one property per enabled input, keyed by its describeForm() address (email, address.city). Each property has a JSON type (string, number, boolean, or array for multi-value inputs), an enum built from static option values, and a description made from the label, help text, and rules. The schema is regenerated when fields are added or removed, or when their options, labels, or disabled state change. Hidden, password, and disabled inputs are left out of the schema. Password inputs are included only when you set sensitive: true.
WebMCP options
createWebMCPPlugin({
forms: (node) => node.props.id !== 'internal', // which forms to expose
values: false, // include current values in describe results
submit: false, // register formkit_submit_<id>
sensitive: false, // allow agents to fill password inputs
wrapResult: undefined,
modelContext: undefined, // defaults to document/navigator.modelContext
})
| Option | Default | Description |
|---|---|---|
forms | — | (node) => boolean. Return false to skip a form. |
values | false | Include current values in the describe result. password and hidden values are always redacted. |
submit | false | Register a formkit_submit_<id> tool. |
sensitive | false | Let agents fill password inputs. When it's off, password inputs are left out of the fill schema and fill refuses them. Password values are never returned either way. |
wrapResult | — | (result, kind) => unknown. Transforms each tool result. By default the plain JSON object is returned, as the current WebMCP draft expects. Pass the exported webMCPTextResult to return MCP-style { content: [{ type: 'text', text }] } instead, for polyfills or agents that expect that shape. |
modelContext | document.modelContext ?? navigator.modelContext | The object tools are registered with. Pass a polyfill or a test double here. |
To opt out a single form, add data-agent="off":
<FormKit type="form" id="payment" data-agent="off">…</FormKit>
WebMCP safety
- Agents act as the user. Anything a tool does, the agent can do without the user touching the page. Only expose forms you'd be comfortable having an agent fill in, and opt out the rest with
data-agent="off"orforms. - Submitting is off by default. With
submit: true, submissions still go through validation and youronSubmithandler, just as when a user submits. The tool is markedconsequentialHintso browsers can ask the user to confirm, but that's up to the browser. Enforce anything important (authentication, CSRF, rate limits, confirmations for payments) on the server. - Values stay private by default.
describedoesn't return values unless you setvalues: true, andpasswordandhiddenvalues are never returned.fillresults never echo values back. - Validation still applies.
fillwrites throughnode.input(), so validation, dirty state, and events behave as if a user typed. The browser doesn't validate tool arguments againstinputSchema, sofillForm()reports any unknown addresses and unmatched options in its result. - Hidden and password inputs can't be filled.
fillrefuses to writehiddeninputs, so an agent can't overwrite tokens or ids your app sets. It also refusespasswordinputs unless you setsensitive: true. When a fill is refused,fillreturns{ error }and writes nothing. Hidden inputs stay locked even withsensitive: true. Disabled inputs are skipped, as withfillForm(). - No cost without WebMCP. When the browser has no
modelContext, the plugin reads only the node'stypeand returns. It adds no listeners and never describes the form.