Developer docs menu

Node.js API

Embed the UAG in your own Node.js and Express application with UAGServer, and reach its project, forms and tools from your code.

The formio/uag Docker image is one way to run the UAG. The other is to embed it: install @formio/uag from npm, create a UAGServer, and mount its router in an Express application you own. You then control the process, the configuration and the modules, and your own routes run next to /mcp, /agent/capabilities and the project's routes.

This page covers the UAGServer class and its configuration, modules, the project and form interfaces your code and custom tools work with, the package's exports, and the uag command. For what goes inside a module, see Modules. For engines, see Engines and routing.

Requirements

Requirement Why
Node.js 22 or later @formio/uag and every engine package declare "node": ">=22.0.0".
--no-node-snapshot Form logic (conditionals, calculated values, custom validation) runs in isolated-vm, which needs Node's startup snapshot turned off: without it the process can crash later, in native code. Pass it to node, or set NODE_OPTIONS=--no-node-snapshot. The UAGServer constructor refuses to start without it, saying so; the uag command adds it for you.
A Form.io project PROJECT must point at a reachable Open Source server (with ADMIN_KEY), a self-hosted Enterprise project (with PROJECT_KEY and a LICENSE_KEY that includes the UAG), or a trial project on portal.form.io (with PROJECT_KEY; no UAG license needed). Without one, router() throws.
JWT_SECRET Tokens the UAG issues are signed with it. With an agent role, it must be the Form.io Enterprise server's. See Deployment.
Optional: MONGO The UAG's own database, for run records, runs that survive a restart and remote MCP sign-in (MCP_OAUTH). See The UAG database.

Install

bash
npm install @formio/uag express dotenv
# Engines are separate packages. Install the ones you will enable:
npm install @formio/uag-jev @formio/uag-claude

isolated-vm compiles a native module on install, so build images need make, python3 and g++ (on Alpine: apk add make python3 g++).

A minimal server

js
// server.js
require('dotenv/config');
const express = require('express');
const { UAGServer } = require('@formio/uag');

async function main() {
    const server = new UAGServer();
    const app = express();
    // Loads the project, installs the module template, enables the engines
    // and mounts /mcp, /agent/capabilities, /auth/* and the project routes
    // (each form's agent operations among them).
    app.use(await server.router());
    const port = process.env.PORT || 3200;
    app.listen(port, () => console.log(`UAG on http://localhost:${port}`));
}

main().catch((err) => {
    console.error('Failed to start the UAG:', err);
    process.exit(1);
});
bash
PROJECT=http://localhost:3001 ADMIN_KEY=CHANGEME JWT_SECRET=CHANGEME \
node --no-node-snapshot server.js

require('dotenv/config') loads a .env file from the working directory, as the uag command does.

note

The router can be mounted under a path (app.use('/uag', router)): the Agent API, the chat, submissions, /status, /mcp with client_credentials and @formio/uag-js (given https://app.example.com/uag as the UAG's URL) all work there. Remote MCP sign-in (MCP_OAUTH) is the exception: MCP clients look for /.well-known/oauth-protected-resource and /.well-known/oauth-authorization-server at the root of the host, so serve the UAG at a host's root (a host name of its own) when it is on.

Behind a reverse proxy

The UAG works out its public URL, which the OAuth discovery documents name, from each request: from the Host header, or, when Express trusts the proxy in front of it, from X-Forwarded-Proto and X-Forwarded-Host. BASE_URL (baseUrl) overrides it for every request. Trusting the proxy also gives the UAG callers' real addresses.

The uag command and the Docker image read TRUST_PROXY and set Express's trust proxy for you. In your own server the Express application is yours, so set it yourself. trustProxySetting reads TRUST_PROXY the way the uag command does: true or false, a number of proxy hops, or addresses and ranges such as loopback, 10.0.0.0/8, and undefined when it is empty.

js
const { UAGServer, trustProxySetting } = require('@formio/uag');

// Inside main(), as in the server above.
const app = express();
const trust = trustProxySetting(process.env.TRUST_PROXY);
if (trust !== undefined) app.set('trust proxy', trust);
app.use(await server.router());

Without it, a UAG behind a TLS-terminating proxy names http:// URLs in its OAuth documents, and remote MCP clients cannot sign in.

A server with a module, engines and your own routes

js
// server.js
require('dotenv/config');
const express = require('express');
const { UAGServer } = require('@formio/uag');
const crm = require('./module');            // see /developers/modules

async function main() {
    const server = new UAGServer({
        // Instances to enable. This list replaces UAG_ENGINES when it is set.
        engines: [
            'jev',
            { name: 'deep', type: 'claude', options: { model: 'claude-opus-5-5', researchEffort: 'high' } },
        ],
        routing: { value: ['deep'], timeouts: { jev: 2000, deep: 60000 } },
        agentApi: { threshold: 0.6 },
    });
    server.use(crm);

    const app = express();
    // Your routes first, so they win over the UAG's catch-all project routes.
    app.get('/healthz', (req, res) => res.json({ ok: true }));
    app.use(await server.router());

    // Once router() has resolved, the project is loaded.
    console.log('Forms the UAG exposes:', server.uagProject.formNames.join(', '));
    app.listen(process.env.PORT || 3200);
}

main().catch((err) => {
    console.error('Failed to start the UAG:', err);
    process.exit(1);
});

The UAG's router mounts the project routes and an admin passthrough, then /mcp after them: a request with an admin credential (x-admin-key, x-token) for a path the UAG does not serve is forwarded to the Form.io server. Other requests it does not serve fall through to the routes after it. Register your own routes before app.use(await server.router()) anyway, so admin requests reach them too, or mount the UAG under a path.

What router() does

await server.router() does all of the startup work, in this order. Any step that fails rejects the promise, so a misconfigured server stops before it serves anything.

  1. With MONGO set, connects to the UAG's database and checks it without writing anything. A database the UAG may not use (unreachable, holding uag-* collections it did not create, or created by a newer UAG) stops startup.
  2. Resolves each module's settings. An invalid setting stops startup, naming the module.
  3. Connects to PROJECT, retrying with backoff (retries, retryDelay) while the project is unreachable, for example while a Form.io container in the same compose file is still starting.
  4. Installs the module's project template, when templateSync allows it (see Modules).
  5. Loads the project's forms and resources, and registers every form tagged uag.
  6. Lists the plugins: the built-in converters, the engines named in config.engines (or else UAG_ENGINES), and the MCP tools. An engine that is not installed, has a missing setting or a duplicate name stops startup, with the instance named in the error.
  7. Starts the plugins, then calls each module's initialize.
  8. Mounts /uag-js/*, /agent/capabilities and the Action Logs, ahead of the project routes.
  9. With a database, uses it when the license includes the UAG: creates its collections and turns on run records, durable runs and, with MCP_OAUTH, remote MCP sign-in. Otherwise it leaves the database untouched, closes it, and logs why those features are off.
  10. Logs the edition (Open Source or Enterprise) and whether Agentic Formflow is licensed.
  11. Returns an Express Router with the routes below.
check the databasemodule settingsconnect to PROJECT,with retriessync the module'stemplateload the tagged formslist converters,engines and toolsstart plugins andmodulesmount /uag-js,capabilities, ActionLogsuse the database, iflicensedlog the editionmount the routes
Route Served by Purpose
POST /mcp, GET /mcp UAGRouter The MCP endpoint (Streamable HTTP, stateless: a new MCP server per request). Needs a bearer token. See MCP tools.
GET /uag-js/uag.use.js, /uag-js/uag-js.css, /uag-js/portal.js, /uag-js/portal.css, /uag-js/components/<type>.js and .css uagJsRouter @formio/uag-js from the UAG's own installation: uag.use.js registers itself with this UAG's URL, its plugin manifest and every module's component. Public (no credential, Access-Control-Allow-Origin: *), no-cache with an ETag; 404 for uag.use.js, uag-js.css, portal.js and portal.css when @formio/uag-js is not installed with the UAG (module components are served either way). See Renderer.
GET /agent/capabilities AgentRouter The Agent API's capabilities. Mounted ahead of the project routes. See Agent API.
POST /auth/token PKCE provider Token exchange: the client_credentials grant, always on; authorization codes too with MCP_OAUTH.
GET /.well-known/oauth-authorization-server, GET /.well-known/oauth-protected-resource, GET /auth/authorize, POST /auth/authorize, GET /auth/config.js, POST /auth/register PKCE provider OAuth discovery, the login page and client registration for remote MCP clients. Only with MCP_OAUTH=true, and answering 404 until the UAG's database is in use.
GET /action, GET /action/:id ActionLogRouter Action Logs for a portal stage connected to the UAG: Form.io's entries with the UAG's run records. Without the database, passed through to Form.io.
GET /status Server The status object (package versions by default).
GET {project}/plugins Project router The installed plugins (engines, tools, actions, converters, modules), for any authenticated caller of the project. See Plugins.
Form and submission paths, admin passthrough Project router Form.io's API for the project's forms, and admin requests forwarded to the Form.io server.
POST {form}/agent/extract, {form}/agent/decide, {form}/agent/generate, {form}/agent/chat FormAgentRouter, on each form's routes A form's agent operations and its chat, under the form's path or form/{formId}, with the form's credentials (agentCredentials), or anonymously where the form allows it. See Agent API.
<METHOD> {form}/<path> for each module route The module's routes.form, on each form's routes Every route a module declares, on every form, by path and by id, behind the agent operations' caller check, body limit, request id, rate limits and error shape. On a form with uagAnonymous: "true" whose Anonymous role may create submissions, visitors who are not signed in reach them too, under AGENT_ANONYMOUS_RATE_LIMIT and AGENT_ANONYMOUS_TOTAL_RATE_LIMIT; a route that must not be public declares access: ['update'] or checks req.auth.user. See Modules.

new UAGServer(config)

ts
class UAGServer extends Server {
    constructor(config?: UAGConfig);
    use(module: UAGModule): void;
    router(): Promise<Router>;
    /** The loaded UAG project, once router() has built the project router. */
    get uagProject(): UAGProjectInterface | undefined;
    /** CORS exposed headers: the server's, plus X-Request-Id. */
    get exposedHeaders(): string[];
}

The constructor checks that the @formio/appserver-core that @formio/appserver loads, the UAG's only copy of it, is 2.26.4 or later, and throws if not (see assertSingleCore). It then fills every option you leave out from the environment, so new UAGServer() with no arguments configures itself the way the Docker image does.

UAGConfig extends ServerConfig, the Form.io server options, with the UAG's own.

UAG options

Option Type Default Meaning
baseUrl string BASE_URL, else '' Optional. Overrides the public URL the UAG otherwise derives from each request (see Behind a reverse proxy). Published in the OAuth discovery documents, and, while OAuth sign-in is on, in the WWW-Authenticate challenges on /mcp.
database { url, name?, config?, retentionDays? } from MONGO, UAG_DATABASE (uag), MONGO_CONFIG, TASK_RUN_RETENTION_DAYS (90) The UAG's own database. See The UAG database.
responseTemplates UAGTemplateConfig {} Lodash templates by name: replacements for built-in response templates, and new ones for your tools. See Modules.
toolOverrides UAGToolOverride {} Per built-in tool, fields merged over its definition (description, title, schema, execute). See Modules.
documents UAGDocumentsConfig see AI Document Limits for uploaded documents, and the engine that reads them (DOCUMENTS_ENGINE). maxFileBytes (DOCUMENTS_MAX_FILE_BYTES) also bounds read_document, and maxTotalBytes what one request sends a remote engine.
tools ToolInfo[] [] Custom MCP tools, served next to the built-in ones; a tool's bind(project) builds its project-specific part.
engines UAGEngineEntry[] UAG_ENGINES Engine instances to enable: "<type>", "<name>:<type>", or { name, type, options }, where type may be an engine type definition. When this is an array (even empty), UAG_ENGINES is ignored.
engineTypes Record<string, EngineTypeDefinition> none Engine types your application provides, by type name. Resolved before the built-in types and installed packages.
routing UAGRoutingConfig { decision: ['decision', 'agent'], value: ['agent'] } Engine preference lists and per-engine timeouts. See Engines and routing.
agentApi UAGAgentApiConfig see Engines and routing Thresholds, timeouts, research limits and rate limits for Agentic Formflow.
loginForm string none Declared on UAGConfig, but not read by this version. To change the login form, set auth.loginForm (LOGIN_FORM); to replace the login page, set auth.authAppHtml. See Modules.

Server options

Option Type Default Meaning
project string PROJECT, else '' The project endpoint: the Open Source server URL, or the Enterprise project URL.
projects string[] PROJECTS, comma-separated More project endpoints to load. The UAG serves the first project loaded (uagProject); leave this unset.
license string UAG_LICENSE Deprecated: the license from UAG_LICENSE, still read until UAG 3.0. Prefer LICENSE_KEY. A license that includes the UAG enables Agentic Formflow and covers running against an Enterprise project.
licenseRemote boolean | string LICENSE_REMOTE true when the key is an offline (self-contained) license, verified by the UAG itself, never sent to the license server. Other keys are validated with the license server.
licenseServer string LICENSE_SERVER, else the built-in license server The Form.io license server's URL.
submissionProxy boolean | string true Where submissions go. true forwards them to the project's own submission API; a URL forwards them there. The UAG always runs in proxy mode: it stores no submissions, and runs only its own actions and modules' actions, never Form.io's.
processAsClient boolean true Evaluate form logic as a client would (the processAsClient flag in the evaluation context).
ttl number (seconds) PROJECT_TTL, else 900 How often the project is re-read for changed forms and actions. 0 means never: only a restart picks up changes.
templateSync 'boot' | 'refresh' | 'off' TEMPLATE_SYNC, else 'boot' When the module's project template is installed. See Modules.
template ProjectTemplate none The project template the module needs the project to have. Usually set by a module.
retries number PROJECT_RETRIES, else 5 Attempts to load the project at startup. Also used by remote engines to describe themselves.
retryDelay number (ms) PROJECT_RETRY_DELAY, else 5000 First delay between attempts, doubled each time.
cors CorsOptions | boolean | string CORS, else 'true' true allows every origin, false turns CORS off, any other string is an allowed origin (or several, separated by commas), an object is passed to the cors package.
maxBodySize string MAX_BODY_SIZE, else '16mb' The JSON body limit for the server's routes. Agent operations and module routes have a smaller one inside it: agentApi.bodyLimit (bytes), else AGENT_BODY_LIMIT, else 5 MB. A body over it is answered 413 with code payload_too_large, naming the limit.
cache boolean PROJECT_CACHE, else true With db, store each project load there and fall back to it when the project cannot be loaded. The UAG sets no db, so this has no effect unless you pass one.
db DBConfig none A database for the Form.io logic the UAG is built on. In the UAG, MONGO configures database, not db.
status any the package versions The body of GET /status.
auth AuthConfig see below Credentials and the login flow.

auth options

Option Type Default Meaning
adminKey string ADMIN_KEY Open Source: the server's admin key. Also accepted as x-admin-key on the Agent API.
projectKey string PROJECT_KEY Enterprise: the project's API key. Also accepted as x-token on the Agent API.
secret string JWT_SECRET; a random value per process when unset Signs the tokens the UAG issues, scoped tokens for remote research, and, for a Run task action with an agent role, the agent's Form.io tokens (it must then be the Form.io Enterprise server's). Set it: a random secret invalidates every token at each restart.
expire number (minutes) JWT_EXPIRE_TIME, else 60 Lifetime of the tokens the UAG issues.
portal string PORTAL_SECRET Enterprise: lets the Form.io portal connect to the UAG.
pkce boolean true The provider that issues UAG tokens at /auth/token and checks them on /mcp and the Agent API.
mcpOAuth boolean MCP_OAUTH === 'true' OAuth sign-in for remote MCP clients: discovery, the login page and client registration. Needs the UAG's database; without it, the UAG starts with sign-in off and says why.
loginForm string LOGIN_FORM, else <PROJECT>/user/login The login form's JSON URL, loaded by the browser on /auth/authorize (with mcpOAuth).
authAppHtml string the built-in page The HTML of the /auth/authorize page (with mcpOAuth). See Modules.
oidc OIDCConfig from OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_SCOPE (openid profile email), OIDC_RESPONSE_TYPE (code), OIDC_RESPONSE_MODE (query) An OpenID Connect provider for sign-in.
local LocalAuthConfig none Local login settings: userfield, passfield, allowedAttempts, lockWait, attemptWindow, resources.

Where a value comes from

For each option, the first of these wins:

  1. A module's config, passed to server.use(). Modules are merged into the configuration with Lodash merge, so a later module overrides an earlier one key by key.
  2. The object you pass to new UAGServer(config).
  3. The environment variable in the tables above.
  4. The default.

config.tools is the exception: MCP tools add up across modules, and a tool name two modules define stops startup, naming both.

The UAG database

The UAG needs no database: submissions stay in Form.io. With one of its own, set by MONGO (or config.database), it adds:

  • a record of every Run task run, shown in the project's Action Logs in a portal stage connected to the UAG;
  • runs after the save that survive a restart, for actions with an agent role, taken by one replica at a time;
  • OAuth sign-in for remote MCP clients (MCP_OAUTH), with authorization codes stored by their hash.
Setting Variable Default Meaning
database.url MONGO none The connection string. It can be the one Form.io uses: the database it names is ignored.
database.name UAG_DATABASE uag The database the UAG uses, selected by name on the connection, so the connection's authentication is unchanged.
database.config MONGO_CONFIG none MongoDB driver options, as JSON or an object.
database.retentionDays TASK_RUN_RETENTION_DAYS 90 Days a run record is kept. 0 keeps records forever.

The UAG reads and writes only collections named uag-* (uag-meta, uag-authcodes, uag-taskruns), never submissions. Using the database needs a license that includes the UAG, on every edition, including projects on Form.io's hosted service. Without the license the UAG starts, writes nothing to the database, and logs which features are off. server.database is the database once it is in use; GET /agent/capabilities reports durableRuns and mcpOAuth.

server.destroy()

await server.destroy() stops the server's work in process: each module's close(api), in the reverse order the modules were used, then the plugins' close, then the project. Call it when your own server shuts down, or between tests. The uag command and the Docker image call it on SIGTERM or SIGINT.

server.use(module)

ts
type UAGModule = ServerModule<UAGModuleApi> & { config?: UAGConfig };

type ServerModule<Api> = {
    // Identity, and the module API (see Modules: Settings, routes and components)
    name?: string;
    title?: string;
    version?: string;
    apiVersion?: number;
    host?: string;                                     // 'uag': only the UAG runs it
    settings?(config, env): object;
    routes?: { form?: Record<string, ModuleRoute<Api>> };
    components?: ModuleComponent[];
    initialize?(api: Api): void | Promise<void>;
    close?(api: Api): void | Promise<void>;
    // Everything else a module may add
    config?: ServerConfig;
    plugins?: PluginEntry[];
    pluginTypes?: PluginType[] | ((api: Api) => PluginType[]);
    formRoutes?: RequestHandler | RequestHandler[];   // raw Express routers on every form
    db?: ServerDB;
    providers?: ProviderInterfaceLibrary;
    actions?: Record<string, Action>;
    processors?: AppServerProcessors;
    hooks?: Record<string, HookFn | HookFn[]>;
    ProjectInterface?: typeof ProjectInterface;
    FormInterface?: typeof FormInterface;
};

use() applies a module to the server: it checks its module keys, merges config, adds actions, providers, processors, plugin types and plugins, registers hooks, and sets db. It takes a list, and an ES module namespace (require() of an ES module) by its default export, even when the namespace has named exports too. A module with none of a module's keys adds nothing, and use() warns about it. A module used twice, by name, is used once; a module named in MODULES_DISABLED (config.modules.disabled) is not used. Call it before router(): the project, its tools and its response templates are built from the configuration at startup, and a module with module keys used after stops startup.

Import every module type from @formio/uag: UAGModule, UAGModuleApi, UAGModuleRoute, ModuleForm, ModuleComponent. In JavaScript, /** @type {import('@formio/uag').UAGModule} */ types a module, and /** @type {import('@formio/uag').UAGModuleRoute} */ a route, api included.

ProjectInterface and FormInterface replace the classes the server builds the project and its forms from. The UAGServer constructor installs UAGProjectInterface and UAGFormInterface; a module that replaces them must extend the UAG's classes, or the UAG loses its MCP tools and Agent API. What each part of a module does is covered in Modules.

The project: UAGProjectInterface

server.uagProject is the loaded project, an instance of UAGProjectInterface. Custom tools receive the same object as extra.project, and a bound tool's bind receives it when it builds the tool (see Modules).

ts
class UAGProjectInterface extends ProjectInterface implements FormflowHost {
    /** The UAG configuration (the merged module config). */
    get config(): UAGConfig;
    /** Every form and resource the project has, by machine name. */
    forms: Record<string, FormInterface>;
    /** The names of the forms tagged "uag". */
    get formNames(): string[];
    /** A form by machine name, name or id, or null. */
    getForm(nameOrId?: string): Promise<FormInterface | null>;
    /** The response templates (built at startup from responseTemplates and the built-ins). */
    uagTemplate: UAGTemplate | null;
    /** An MCP tool result whose text is a rendered response template. */
    mcpResponse(template: ResponseTemplate, data?: object, isError?: boolean): { content: { type: 'text'; text: string }[]; isError?: true };
    /** An MCP tool result carrying `data` as JSON text and as structuredContent. */
    mcpJSONResponse(data?: object, isError?: boolean): { content: { type: 'text'; text: string }[]; structuredContent: object; isError?: true };
    /** The engines enabled at startup. */
    engines: EngineRegistry;
    /** A fresh MCP server with every tool registered; a scope narrows it to read-only tools. */
    buildMcpServer(scope?: Pick<ScopedTokenClaims, 'tools'>): Promise<McpServer>;
    /** /mcp, and unless excluded, `/agent/capabilities`. A form's agent operations are on its own routes. */
    uagRouter(includeAgentApi?: boolean): Router;
    /** `GET /agent/capabilities`, behind its own authentication. */
    agentRouter(): Router;
    /** Authenticate a /mcp request: a UAG bearer token, or a scoped token and the identity it carries. */
    authorizeRequest(req: SubmissionRequest, res: Response, next: NextFunction): Promise<void>;
    /** Whether runs after the save are recorded and survive a restart (the UAG's database is in use). */
    durableRuns(): boolean;
    // FormflowHost: what Agentic Formflow reads from the host.
    formflowEngines(): EngineRegistry;
    formflowConfig(): FormflowConfig;
    formflowForm(name: string): Promise<FormflowForm | null>;
    formflowTools(): Promise<FormflowTool[]>;
}

mcpResponse takes a template name. Custom template names are not members of the ResponseTemplate enum; in TypeScript, cast them ('crmPipelineSummary' as ResponseTemplate), in JavaScript pass the string. Rendering a name that is neither in responseTemplates nor a built-in template throws Failed to render template '<name>': Template '<name>' not found at <path>.

Tools are built for every MCP request (buildMcpServer), so toolOverrides and tools are read each time. Response templates are read when the project initializes at startup, and each is compiled once and cached.

Forms: UAGFormInterface

Every form and resource is a UAGFormInterface. A form tagged uag has uag set; its agent tasks are in uagFields.

ts
class UAGFormInterface extends FormInterface implements FormflowForm {
    /** The form's UAG registration, or null when it is not tagged "uag". */
    uag: { name: string; title: string; description?: string; machineName?: string } | null;
    /** The form's tasks, by task name: criteria, fields, inputs and task settings. */
    uagFields: Record<string, UAGFields>;
    /** The form definition. */
    form: AppServerForm;

    // Reading and writing submissions, with the caller's permissions.
    find(query: Record<string, any>, auth?: AuthRequest): Promise<{ items: Submission[]; count: number; skip: number; limit: number }>;
    count(query: Record<string, any>, auth?: AuthRequest): Promise<number>;
    loadSubmission(id: string, auth?: AuthRequest): Promise<Submission | null>;
    /**
     * Run the create (no _id) or update chain, hooks and actions included, and return the saved
     * submission. `request` adds fields to the request the chain sees.
     */
    submit(submission: any, auth: AuthRequest, request?: Record<string, any>): Promise<Submission | null>;

    // Fields and data.
    /** The fields still to collect, required and optional, with their rules and any validation errors. */
    getFields(submission: Submission, auth: AuthRequest, within?: string | string[]): Promise<FormFieldInfo>;
    getComponent(path: string): Component | undefined;
    getComponentInfo(component: Component, path: string): UAGComponentInfo;
    validateData(submission: Submission, auth: AuthRequest): Promise<FormFieldError[]>;
    /** Flat { "data.path": value } pairs to a submission. Comma-separated strings become select boxes or multi-values. */
    convertToSubmission(data?: Record<string, any>): Submission;
    /** A submission's values in form order, labeled, for templates. */
    formatData(data?: DataObject): UAGData;
    formatSubmission(submission: Submission): UAGSubmission;
    inputComponent(component: Component): boolean;
    isNestedComponent(component: Component): boolean;
}

Queries use Form.io's submission query syntax: { 'data.stage': 'lead' }, { 'data.email__regex': '/@example\\.com$/i' }, operators such as __gt, __lt, __in, __ne, and limit. Pass the caller's AuthRequest: with the default submission proxy, the request goes to Form.io with the caller's own token, so Form.io's permissions apply.

The types the form methods return:

ts
type UAGComponentInfo = {
    path: string; label: string; type: string; format: string; description: string;
    validation: any; options?: { label: string; value: string }[];
    prompt?: string; nested?: boolean; rule?: string;
};
type FormFieldError = { label: string; path: string; error: string };
type FormFieldInfo = {
    rowIndex: number; total: number; totalRequired: number; totalRequiredCollected: number;
    errors: FormFieldError[];
    required: { rules: Record<string, string>; components: UAGComponentInfo[] };
    optional: { rules: Record<string, string>; components: UAGComponentInfo[] };
};
type UAGData = Array<{ label: string; value: any; path: string; prefix?: string }>;
type UAGSubmission = { _id?: string; data: UAGData; created?: string | Date; modified?: string | Date };
type UAGFields = {
    task: string;
    criteria: string;
    components: Record<string, UAGComponentInfo>;
    /** Data paths of the components flagged uagField: "input". */
    inputs?: string[];
    /** Custom properties of the task's criteria component, such as uagEngine and uagTools. */
    settings?: Record<string, string>;
};

The caller: AuthRequest

Tools, actions and Agent API operations receive an AuthRequest: who is calling, and what they may do.

Member Meaning
project The project the request is for.
admin true for the admin or project key, and for scoped tokens issued for an admin caller.
user The signed-in user's submission, or null.
formPermissions(form) { create, read, update, delete } for this caller on a form.
checkFormMethodAccess(method) Whether the caller may perform a method on the request's form.

Calling Agentic Formflow in process

The Agent API is a thin HTTP layer over FormflowService, which @formio/uag exports as Formflow. Code running in the same process, such as a custom route, can call it directly once router() has resolved:

js
const { Formflow, AuthRequest } = require('@formio/uag');

app.post('/internal/triage', express.json(), async (req, res) => {
    const project = server.uagProject;
    const auth = new AuthRequest(project, true);   // runs as administrator
    const service = Formflow.formflow(project);
    const result = await service.extract(
        { form: 'claim', task: 'triage', text: req.body.description },
        { auth, requestId: req.get('x-request-id'), identity: Formflow.identityOf(auth) }
    );
    res.json(result);   // { tasks, data, fields, errors, excluded, engines }
});

The service applies the same license check, permissions, routing, validation and rate limits as the HTTP endpoints, and throws Formflow.FormflowError with an HTTP status (and code) on failure. Its methods are extract, decide, generate and capabilities, with the request bodies described in Agent API plus form, the form's name (which the HTTP operations take from the URL), and runTask(form, task, submission, auth, options), which runs a task on a submission as "Agent: Run task" does, without saving it. For runTask, form is the form object, not its name (await project.formflowForm('claim')), and the result is a TaskRun: the reconciled submission in submission, with fields, written, cleared, refused, task, answer, results and failed. identity decides who research tools and scoped tokens act as.

Public exports

require('@formio/uag') exports:

Export Kind What it is
UAGServer class The server.
UAGModule type ServerModule & { config?: UAGConfig }.
assertNodeSnapshotDisabled(execArgv?, nodeOptions?) function Throws unless Node was started with --no-node-snapshot (in its arguments or NODE_OPTIONS). The constructor calls it.
assertSingleCore(version?) function Throws unless the @formio/appserver-core that @formio/appserver loads is 2.26.4 or later. The constructor calls it. Fix it by upgrading @formio/appserver.
UAGProjectInterface, UAGFormInterface classes The project and form interfaces above.
UAGConfig, UAGForm, UAGTemplateConfig, UAGDocumentsConfig, UAGToolOverride, UAGEngineEntry, UAGRoutingConfig, UAGRateLimit, UAGAgentApiConfig, UAGAnonymousConfig, UAGChatConfig types Configuration types (src/config.ts).
trustProxySetting(value) function Parses a TRUST_PROXY value into Express's trust proxy setting, or undefined when it is empty. See Behind a reverse proxy.
UAGTemplate, ResponseTemplate class, enum The response template renderer, and the built-in template names.
UAGRouter(project) function The bare MCP handler, with no authentication: tools then get no extra.authInfo. Mount it behind project.authorizeRequest, or use project.uagRouter(), which does.
ToolInfo, ToolExtra, ToolEntry, ToolAnnotations, ParentInfo, DataUpdate, SearchQuery types Tool definition types.
sanitizeRichText(html), isRichText(component), RICH_TEXT_TAGS, RICH_TEXT_RULE functions, constants The HTML rich text fields keep, as the UAG sanitizes what engines write into them. Modules can use them for HTML they produce, such as a document reader's output.
reads(title), creates(title), overwrites(title) functions Annotation presets for tools.
escapeSearchPattern(value) function Escape a literal for a __regex query (handles /).
getTools(project) and getForms, getFormFields, getFieldInfo, collectData, confirmSubmission, submitCompletedForm, findSubmission, submissionUpdate, fetchExternalData, agentProvide, agentDecide, readDocument functions The built-in tool factories: each takes the project and returns a promise of its ToolInfo (await getForms(project)); getTools resolves to all of them.
loadUAGEngines(config?, env?) function Enable engines as router() does, returning an EngineRegistry.
BUILT_IN_ENGINES, RemoteEngine, StubDecisionEngine, StubAgentEngine, MIN_KEY_LENGTH, UAG_ROOT values The built-in engine types, the shortest engine server key (32), and the UAG's install root, where engine packages are looked up first.
AgentRouter(project, authenticate) function The router for GET /agent/capabilities on its own.
FormAgentRouter(project, credentials), agentCredentials(project), agentNotFound(project) functions A form's agent operations (agent/extract, agent/decide, agent/generate, agent/chat), mounted on each form's routes; the credential check they run behind; and the 404 for an agent operation of a form the project does not have.
definePlugin(plugin), definePluginType(type), PluginRegistry, loadPluginFile(path), PLUGIN_NAME, Plugin, PluginType, PluginEntry functions, class, types The plugin framework, from @formio/appserver-core. server.plugins is the server's registry. See Plugins.
usePluginFiles(server, env?), pluginFiles(env?), pluginFilesIn(path), DEFAULT_PLUGINS_DIR functions, constant Load the plugins files UAG_PLUGINS names (or those in /app/plugins when it exists), as the uag command does after the module, and return the files loaded; the files a setting or a path gives, in load order; and /app/plugins. See Plugins.
Converter, DocumentPlugin, DocumentContext, DocumentResult, DocumentFile, Issue types The converter and document plugin contracts (experimental in 2.0).
BUILT_IN_CONVERTERS, identify(buffer, hint, converters?), ConverterRoutes, runConverter values, functions Converters: the built-in ones, byte-based identification, converter routes and conversion. Modules reach them through api.converters.
UAGModule, UAGModuleApi, UAGModuleRequest, UAGModuleRoute, ModuleForm, ModuleComponent, GeneratingEngine types The module API and its types. See Modules.
@formio/uag/testing: createTestModuleApi, mountModuleRoutes, testForm, testAuth functions Test a module without a project. See Modules.
sanitizeMarkdown(markdown) function The Markdown the AI Document keeps: raw HTML removed (its text kept), only http, https and mailto links, no images, no code fence around the whole value.
The Form.io server classes various Server, ProjectInterface, FormInterface, AuthRequest, Action, ActionInfo, SubmissionRequest, SubmissionResponse, ServerConfig, Utils, Database, the Formflow namespace and the rest of the Form.io logic the UAG is built on.

The package's types are in lib/index.d.ts ("types": "lib/index.d.ts").

The uag command

The package installs two commands: uag, which starts a server like the Docker image does, and uag-eval (see Evaluation).

bash
npx uag                                   # the UAG, no module
UAG_MODULE=./module npx uag               # with a module (a file or a folder)
UAG_ENGINES=claude CLAUDE_API_KEY=... npx uag

uag:

  • loads .env from the working directory first, so a module that reads the environment sees it too;
  • restarts itself with --no-node-snapshot when that flag is in neither the command line nor NODE_OPTIONS, forwarding SIGINT, SIGTERM and SIGHUP and exiting with the child's code;
  • requires UAG_MODULE, resolved against the working directory, and passes it to server.use() (a module exported as a promise is awaited first);
  • then loads the plugins files: those UAG_PLUGINS names (off turns it off), or else those in /app/plugins when it exists, its index.mjs or each add-on folder's (see usePluginFiles in Public exports);
  • sets Express's trust proxy from TRUST_PROXY, when it is set;
  • listens on PORT (default 3200);
  • prints the error and exits with code 1 when startup fails;
  • on SIGTERM or SIGINT, stops taking connections, calls server.destroy() (each module's close, then each plugin's), and exits with code 0, or 1 when that fails or takes more than 10 seconds.

The Docker image runs node --no-node-snapshot index.js, whose index.js is the same start-up with the module in /app/module:

js
// index.js in the image
const { start, fail } = require('./bin/uag');
start(require('./module')).catch(fail);

bin/uag.js also exports start(module) and fail(error) for scripts that want the same behavior with a module object of their own.

Running without the snapshot

isolated-vm, which evaluates form logic in a sandbox, cannot run with Node's startup snapshot on. The ways to turn it off:

bash
node --no-node-snapshot server.js
NODE_OPTIONS=--no-node-snapshot node server.js
npx tsx --no-node-snapshot server.ts
dockerfile
ENV NODE_OPTIONS=--no-node-snapshot

The uag command and the Docker image set it themselves. Test runners need it too: the UAG's own tests run mocha --no-node-snapshot.

Next steps