diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts
index af2f1a1aaf..092af1fb47 100644
--- a/docs/.vitepress/config.ts
+++ b/docs/.vitepress/config.ts
@@ -324,6 +324,7 @@ export default extendConfig(
{ text: 'Head Management', link: '/guide/pages-routing/head' },
{ text: 'Islands', link: '/guide/pages-routing/islands' },
{ text: 'Markdown', link: '/guide/pages-routing/markdown' },
+ { text: 'WebMCP', link: '/guide/pages-routing/webmcp' },
],
},
{
diff --git a/docs/guide/pages-routing/webmcp.md b/docs/guide/pages-routing/webmcp.md
new file mode 100644
index 0000000000..23e319891c
--- /dev/null
+++ b/docs/guide/pages-routing/webmcp.md
@@ -0,0 +1,235 @@
+---
+description: 'Let AI agents in the browser use your pages through WebMCP tools: submit forms, read page data, and navigate.'
+outline: deep
+---
+
+# WebMCP
+
+[WebMCP](https://webmachinelearning.github.io/webmcp/) lets a page offer tools to AI agents running in the browser, such as a browser assistant. A tool has a name, a description, and a JSON Schema for its input. The agent calls it instead of clicking through the page. Tools run in the page, with the user's session, and change the same UI the user sees.
+
+The `@void/webmcp` package offers three kinds of tools for Void Pages:
+
+- **Form tools**: `useFormTool()` lets an agent fill in a `useForm()` form and submit it through the page action.
+- **Component tools**: `useAgentTool()` registers a tool while a component is mounted.
+- **A `navigate` tool**: opens any page in your app.
+
+::: warning Experimental
+WebMCP is an early web standard. Chrome supports it behind a flag and in an origin trial; other browsers do not support it yet. Where WebMCP is unavailable, these APIs do nothing, so you can ship them now.
+:::
+
+## Setup
+
+Install the package:
+
+```sh
+npm install @void/webmcp
+```
+
+Add `voidWebMcp()` to your Vite plugins:
+
+```ts
+// vite.config.ts
+import { voidReact } from '@void/react/plugin'; // or voidVue, voidSvelte, voidSolid
+import { voidWebMcp } from '@void/webmcp/plugin';
+import { defineConfig } from 'vite-plus';
+import { voidPlugin } from 'void';
+
+export default defineConfig({
+ plugins: [voidPlugin(), voidReact(), voidWebMcp()],
+});
+```
+
+The plugin offers the [`navigate` tool](#navigation-tool). Form and component tools come from the framework entries: `@void/webmcp/react`, `@void/webmcp/vue`, `@void/webmcp/svelte`, and `@void/webmcp/solid`.
+
+## Trying it locally
+
+In Chrome, enable `chrome://flags/#enable-webmcp-testing`, or start Chrome with `--enable-features=WebMCP`. Then use an agent that supports WebMCP, such as Chrome's Model Context Tool Inspector extension, which lists the page's tools and lets you call them.
+
+To offer tools to visitors before WebMCP ships, register your origin for the [WebMCP origin trial](https://developer.chrome.com/origintrials/) and serve the token it gives you.
+
+## Form tools
+
+Pass a `useForm()` form to `useFormTool()` to let agents submit it:
+
+```ts
+import { useForm } from '@void/react'; // or @void/vue, @void/svelte, @void/solid
+import { useFormTool } from '@void/webmcp/react'; // or /vue, /svelte, /solid
+
+const form = useForm('/users', { name: '', email: '' });
+useFormTool(form, {
+ name: 'add_user',
+ description: 'Add a person to the user directory. Use when the user asks to add someone.',
+});
+```
+
+When an agent calls `add_user`:
+
+1. The form is filled in with the agent's values, so the user sees them.
+2. The form is submitted through the page action, like a user submit. `pending`, `onSuccess`, and `onError` behave the same way.
+3. The agent receives the result. Validation errors from the action appear in the form and are sent to the agent, so it can correct its input and try again.
+
+The tool's input schema comes from the form's defaults. Strings, numbers, booleans, arrays, and objects are described; file fields are left out, so agents cannot fill them in. Agents can send only some fields; the others keep their current values.
+
+| Option | Description |
+| ------------- | ------------------------------------------------------------------------------------------------------------ |
+| `name` | Tool name: 1 to 128 ASCII letters, digits, `_`, `-`, or `.`. Unique on the page. |
+| `description` | What submitting the form does, and when an agent should do it. |
+| `title` | A human-readable name for the tool. |
+| `method` | The method the form submits with. Defaults to `"post"`. |
+| `confirm` | Fill in the form without submitting it. The agent is told that the user must review and submit it. |
+| `input` | A [Standard Schema](https://standardschema.dev) that validates the agent's values before the form is filled. |
+| `inputSchema` | A JSON Schema for the fields, when the defaults do not describe them well enough. |
+| `annotations` | Hints for the agent; see [annotations](#annotations). |
+| `enabled` | `false`, or a function returning `false`, makes the tool reject calls, for example while a form is locked. |
+
+Use `confirm: true` for forms whose effects the user should approve, such as payments or deleting data:
+
+```ts
+const form = useForm('/checkout', { address: '', quantity: 1 });
+useFormTool(form, {
+ name: 'prepare_order',
+ description: 'Fill in the checkout form for the user to review.',
+ confirm: true,
+});
+```
+
+::: tip
+An agent acts with the signed-in user's permissions, through the same action as the user. Keep validating and authorizing in the action; `input` only gives the agent earlier feedback.
+:::
+
+## Component tools
+
+`useAgentTool()` offers a tool while the component is mounted. It is removed when the component unmounts, for example when the user navigates to another page.
+
+::: code-group
+
+```tsx [React]
+import { useAgentTool } from '@void/webmcp/react';
+import type { Props } from './index.server.ts';
+
+export default function UsersPage({ users }: Props) {
+ useAgentTool({
+ name: 'list_users',
+ description: 'List the people in the user directory with their ids.',
+ annotations: { readOnlyHint: true },
+ execute: () => users,
+ });
+ // ...
+}
+```
+
+```vue [Vue]
+
+```
+
+```svelte [Svelte]
+
+```
+
+```tsx [Solid]
+import { useAgentTool } from '@void/webmcp/solid';
+import type { Props } from './index.server.ts';
+
+export default function UsersPage(props: Props) {
+ useAgentTool({
+ name: 'list_users',
+ description: 'List the people in the user directory with their ids.',
+ annotations: { readOnlyHint: true },
+ execute: () => props.users,
+ });
+ // ...
+}
+```
+
+:::
+
+`execute` reads the current props and state each time it is called.
+
+### Tool input
+
+Pass a Standard Schema as `input` to validate calls. Schemas that support [Standard JSON Schema](https://standardschema.dev/json-schema), such as Zod and ArkType, also describe the tool's parameters to the agent. Otherwise, set `inputSchema` to a JSON Schema yourself.
+
+```ts
+import { useRouter } from '@void/react'; // or @void/vue, @void/svelte, @void/solid
+import { useAgentTool } from '@void/webmcp/react'; // or /vue, /svelte, /solid
+import { z } from 'zod';
+
+const router = useRouter();
+
+useAgentTool({
+ name: 'search_products',
+ description: 'Search the product catalog and show the results to the user.',
+ input: z.object({ query: z.string().describe('Words to search for') }),
+ async execute({ query }) {
+ await router.visit(`/products?q=${encodeURIComponent(query)}`);
+ return `Showing results for "${query}".`;
+ },
+});
+```
+
+Invalid calls are rejected with the schema's messages before `execute` runs.
+
+### Results
+
+What `execute` returns is sent to the agent:
+
+| Return value | Agent receives |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------- |
+| Nothing | `Done.` |
+| A string | The string. |
+| Another value | The value as JSON. |
+| `{ content, isError? }` | The [MCP tool result](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool-result) as is. |
+| A thrown error | An error result with the error's message. |
+
+Use `defineAgentTool()` to declare a tool outside a component and pass it to `useAgentTool()` later. It checks the name and infers the input type from `input`. To offer a tool outside components, call `registerAgentTool()` from `@void/webmcp`; it returns a function that removes the tool.
+
+## Navigation tool
+
+`voidWebMcp()` offers a `navigate` tool that opens a page in your app. Pass `navigate: false` to leave it out:
+
+```ts
+voidWebMcp({ navigate: false });
+```
+
+The tool takes a `path`. Its description lists your pages, such as `/users/[id]`, with their Markdown titles. It navigates on the client like a `Link` and returns the new URL and title. Paths that match no page, and other origins, are rejected.
+
+## Annotations
+
+`annotations` tell the agent how a tool behaves:
+
+| Annotation | Meaning |
+| ---------------------- | -------------------------------------------------------------------------- |
+| `readOnlyHint` | The tool only reads data, so an agent can call it without asking the user. |
+| `consequentialHint` | The tool has effects that are hard to undo; the agent may ask first. |
+| `untrustedContentHint` | The result can contain content from sources the app does not control. |
+
+## Writing good tools
+
+- Describe what the tool does for the user and when to use it. Agents choose tools by their descriptions.
+- Name the tool after the task, such as `add_user`, not after the UI, such as `submit_form`.
+- Return data the agent can act on, such as ids and URLs, rather than a plain `Done.`.
+- Offer a tool only on pages where it works, so the agent sees what it can do right now.
diff --git a/docs/reference/api.md b/docs/reference/api.md
index 05a09b43da..e9f3a21b2f 100644
--- a/docs/reference/api.md
+++ b/docs/reference/api.md
@@ -29,7 +29,7 @@ Use this reference to find public imports, signatures, and return types. For set
| [Deployment artifacts](./api/deploy.md) | Package built apps for managed deployment. |
| [Types](./api/types.md) | Typed URLs, route types, handler context, and head metadata. |
| [Environment variables](./api/env.md) | Validated environment values and binding types. |
-| [Pages adapters](./api/pages.md) | React, Vue, Svelte, Solid, and Markdown. |
+| [Pages adapters](./api/pages.md) | React, Vue, Svelte, Solid, Markdown, and WebMCP. |
## User-Facing Imports {#user-facing-imports}
diff --git a/docs/reference/api/pages.md b/docs/reference/api/pages.md
index 390670498e..91602def4c 100644
--- a/docs/reference/api/pages.md
+++ b/docs/reference/api/pages.md
@@ -104,7 +104,7 @@ Imported from `"@void/vue"`.
| `useRouter()` | Returns the Void Router with current route state (`url`, `path`, `query`, `params`) and navigation methods: `visit`, `refresh`, awaitable `prefetch`, `flush`, `flushAll`. |
| `useParams()` | Returns dynamic route params for the page currently being rendered. Pass the page's pattern as the type argument, such as `useParams<'/users/[id]'>()`, to type them. |
| `useNavigation()` | Returns pending navigation state: `{ state, location, method }`, where `state` is `"idle"`, `"loading"`, or `"submitting"` and `location` is the pending destination. |
-| `useForm(url, defaults, options?)` | Typed reactive form helper bound to a page action URL. Returns `{ data, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, reset, setError, clearErrors, clearError }`. |
+| `useForm(url, defaults, options?)` | Typed reactive form helper bound to a page action URL. Returns `{ data, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, submit, reset, setError, clearErrors, clearError }`. |
| `useIslandForm(defaults)` | Form helper for island components. Same form state as `useForm()`, plus `submit(url, method)`. `post(url)`, `put(url)`, `patch(url)`, and `delete(url)` take the action URL and submit with `fetch()`. With [`routing.typedRoutes`](../config.md#routing-typedroutes), the URL is a [`RouteUrl`](./types.md#route-types). |
| `action(url, options?)` | Awaitable one-shot page action helper. Uses `POST` by default and accepts `{ data, method, params, preserveScroll }`, where `method` can be `"PUT"`, `"PATCH"`, or `"DELETE"`. Returns an [`ActionResult`](../../guide/pages-routing/actions-and-forms.md#action-helper). |
| `isVoidActionError(error)` | Checks and narrows `error` to `VoidActionError`, including thrown `401`, `403`, and `500` errors. See [Handling action errors](../../guide/pages-routing/actions-and-forms.md#validation-errors). |
@@ -160,7 +160,7 @@ Imported from `"@void/react"`.
| `useRouter()` | Returns the Void Router with current route state (`url`, `path`, `query`, `params`) and navigation methods: `visit`, `refresh`, awaitable `prefetch`, `flush`, `flushAll`. React navigations are scheduled as transitions. |
| `useParams()` | Returns dynamic route params for the page currently being rendered. Pass the page's pattern as the type argument, such as `useParams<'/users/[id]'>()`, to type them. |
| `useNavigation()` | Returns pending navigation state: `{ state, location, method }`, where `state` is `"idle"`, `"loading"`, or `"submitting"` and `location` is the pending destination. |
-| `useForm(url, defaults, options?)` | Form helper hook. Returns `{ data, setData, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, reset, setError, clearErrors, clearError }`. |
+| `useForm(url, defaults, options?)` | Form helper hook. Returns `{ data, setData, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, submit, reset, setError, clearErrors, clearError }`. |
| `useIslandForm(defaults)` | Form helper hook for island components. Same form state as `useForm()`. `post(url)`, `put(url)`, `patch(url)`, and `delete(url)` take the action URL and submit with `fetch()`. With [`routing.typedRoutes`](../config.md#routing-typedroutes), the URL is a [`RouteUrl`](./types.md#route-types). |
| `action(url, options?)` | Awaitable one-shot page action helper. Uses `POST` by default and accepts `{ data, method, params, preserveScroll }`, where `method` can be `"PUT"`, `"PATCH"`, or `"DELETE"`. Returns an [`ActionResult`](../../guide/pages-routing/actions-and-forms.md#action-helper). |
| `isVoidActionError(error)` | Checks and narrows `error` to `VoidActionError`, including thrown `401`, `403`, and `500` errors. See [Handling action errors](../../guide/pages-routing/actions-and-forms.md#validation-errors). |
@@ -242,7 +242,7 @@ Imported from `"@void/svelte"`.
| Export | Description |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Link` | Svelte component for SPA navigation. Renders `` for GET, `` for non-GET methods. Props: `href`, `method`, `data`, `prefetch`, `cacheFor`, `preserveScroll`, `preserveState`, `replace`, `reloadDocument`, `viewTransition`, `activeMatch`, `onNavigate`. Adds `aria-current="page"` and `data-void-active` to the link to the current page ([active links](../../guide/pages-routing/overview.md#active-links)), and `data-void-pending` to links to a page while it loads ([pending links](../../guide/pages-routing/overview.md#pending-links)). |
-| `useForm(url, defaults, options?)` | Form helper using Svelte 5 runes. Returns `{ data, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, reset, setError, clearErrors, clearError }`. |
+| `useForm(url, defaults, options?)` | Form helper using Svelte 5 runes. Returns `{ data, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, submit, reset, setError, clearErrors, clearError }`. |
| `useIslandForm(defaults)` | Form helper for island components. Same form state as `useForm()`, plus `submit(url, method)`. `post(url)`, `put(url)`, `patch(url)`, and `delete(url)` take the action URL and submit with `fetch()`. With [`routing.typedRoutes`](../config.md#routing-typedroutes), the URL is a [`RouteUrl`](./types.md#route-types). |
| `action(url, options?)` | Awaitable one-shot page action helper. Uses `POST` by default and accepts `{ data, method, params, preserveScroll }`, where `method` can be `"PUT"`, `"PATCH"`, or `"DELETE"`. Returns an [`ActionResult`](../../guide/pages-routing/actions-and-forms.md#action-helper). |
| `isVoidActionError(error)` | Checks and narrows `error` to `VoidActionError`, including thrown `401`, `403`, and `500` errors. See [Handling action errors](../../guide/pages-routing/actions-and-forms.md#validation-errors). |
@@ -296,7 +296,7 @@ Imported from `"@void/solid"`.
| Export | Description |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Link` | Solid component for SPA navigation. Renders `` for GET, `` for non-GET methods. Props: `href`, `method`, `data`, `prefetch`, `cacheFor`, `preserveScroll`, `preserveState`, `replace`, `reloadDocument`, `viewTransition`, `activeMatch`, `onNavigate`. Adds `aria-current="page"` and `data-void-active` to the link to the current page ([active links](../../guide/pages-routing/overview.md#active-links)), and `data-void-pending` to links to a page while it loads ([pending links](../../guide/pages-routing/overview.md#pending-links)). |
-| `useForm(url, defaults, options?)` | Form helper using Solid stores. Returns `{ data, setData, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, reset, setError, clearErrors, clearError }`. |
+| `useForm(url, defaults, options?)` | Form helper using Solid stores. Returns `{ data, setData, post, put, patch, delete, pending, errors, error, hasChanges, wasSuccessful, recentlySuccessful, submit, reset, setError, clearErrors, clearError }`. |
| `useIslandForm(defaults)` | Form helper for island components. Same form state as `useForm()`. `post(url)`, `put(url)`, `patch(url)`, and `delete(url)` take the action URL and submit with `fetch()`. With [`routing.typedRoutes`](../config.md#routing-typedroutes), the URL is a [`RouteUrl`](./types.md#route-types). |
| `action(url, options?)` | Awaitable one-shot page action helper. Uses `POST` by default and accepts `{ data, method, params, preserveScroll }`, where `method` can be `"PUT"`, `"PATCH"`, or `"DELETE"`. Returns an [`ActionResult`](../../guide/pages-routing/actions-and-forms.md#action-helper). |
| `isVoidActionError(error)` | Checks and narrows `error` to `VoidActionError`, including thrown `401`, `403`, and `500` errors. See [Handling action errors](../../guide/pages-routing/actions-and-forms.md#validation-errors). |
@@ -335,8 +335,30 @@ export default defineConfig({
See [Markdown Pages](../../guide/pages-routing/markdown.md) for setup and framework-specific examples.
+## WebMCP Package {#webmcp-package}
+
+The optional `@void/webmcp` package lets AI agents in the browser use your pages through [WebMCP](../../guide/pages-routing/webmcp.md) tools. Install it alongside a Pages adapter. Add `voidWebMcp()` to your Vite plugins to offer a `navigate` tool.
+
+```ts
+import { voidWebMcp } from '@void/webmcp/plugin';
+
+export default defineConfig({
+ plugins: [voidPlugin(), voidReact(), voidWebMcp()],
+});
+```
+
+| Import path | Contents |
+| ------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
+| `@void/webmcp/plugin` | `voidWebMcp({ navigate? })`. `navigate` defaults to `true`. |
+| `@void/webmcp/react`, `/vue`, `/svelte`, `/solid` | `useAgentTool(tool)`, `useFormTool(form, options)`, `defineAgentTool(tool)`, `isWebMcpSupported()` |
+| `@void/webmcp` | `registerAgentTool(tool)`, `defineAgentTool(tool)`, `isWebMcpSupported()`, and the tool types |
+
+`useAgentTool()` offers a tool while the component is mounted. `useFormTool()` lets agents fill in and submit a `useForm()` form. `registerAgentTool()` offers a tool outside components and returns a function that removes it. All of them do nothing where WebMCP is unavailable.
+
## Form
Each Pages adapter exports `Form`. Pass the object returned by `useForm()` as `form`; `method` defaults to `post`. It renders validation and action errors, preserves controlled input, and respects known quota retry deadlines without submitting automatically. `renderError` customizes action-error presentation; Svelte uses a snippet. See [Actions and Forms](../../guide/pages-routing/actions-and-forms.md).
Pass `{ throwOnError: false }` as the third argument to `useForm()` to show HTTP failures inline. Validation errors populate `form.errors`; other HTTP failures populate `form.error`. React also calls `onError`. Unexpected failures still throw, and cancelled submissions don't set a form error. See [Handling action errors](../../guide/pages-routing/actions-and-forms.md#validation-errors).
+
+`form.submit(method?)` submits the form like `post()` and the other method helpers. It returns a promise that resolves with the outcome: `{ status: 'success' }`, `{ status: 'invalid', errors }`, `{ status: 'error', error }`, or `{ status: 'cancelled' }` when a newer submission replaced it or the request was aborted. Failures that `useForm()` throws reject the promise. The method defaults to `"post"`.
diff --git a/packages/react/src/runtime/use-form.ts b/packages/react/src/runtime/use-form.ts
index 5798d754d8..75082d927b 100644
--- a/packages/react/src/runtime/use-form.ts
+++ b/packages/react/src/runtime/use-form.ts
@@ -1,4 +1,5 @@
import {
+ startTransition,
useActionState,
useCallback,
useContext,
@@ -17,7 +18,13 @@ import {
parseFormResetArgs,
submitAction,
} from 'void/pages-client';
-import type { FormResetOptions, FormState, VoidActionError } from 'void/pages-client';
+import type {
+ FormResetOptions,
+ FormState,
+ FormMethod,
+ FormSubmitResult,
+ VoidActionError,
+} from 'void/pages-client';
import type { ActionUrl, ResolveActionBody, ActionFormOptions } from 'void/routes';
import { RouterContext } from './context.ts';
@@ -25,6 +32,9 @@ type SubmitPayload = {
method: string;
snapshot: Record;
dispatchData: Record;
+ /** Set for a submission started with `submit()`, which resolves with its result. */
+ settle?: (outcome: SubmissionOutcome) => void;
+ fail?: (error: unknown) => void;
};
type SubmissionOutcome =
@@ -106,76 +116,90 @@ export function useForm(
return nextOutcome;
};
- const [outcome, dispatchAction, pending] = useActionState(
- async (previousOutcome, payload) => {
- if (!router) {
- throw new Error('useForm(): requires the Void Router.');
- }
+ const runSubmission = async (
+ previousOutcome: SubmissionOutcome,
+ payload: SubmitPayload,
+ ): Promise => {
+ if (!router) {
+ throw new Error('useForm(): requires the Void Router.');
+ }
- let result;
- try {
- // Params are filled in on submit, so a param that would change the
- // request path (such as "..") fails this submit, not the page render.
- result = await submitAction(
- router,
- interpolateRouteParams(url, options?.params),
- {
- method: payload.method,
- data: payload.snapshot,
- preserveScroll: options?.preserveScroll,
- _resolveOnShell: true,
- },
- options,
- );
- } catch (submitError) {
- if (isAbortError(submitError)) {
- return { status: 'idle', defaults: previousOutcome.defaults };
- }
- throw submitError;
+ let result;
+ try {
+ // Params are filled in on submit, so a param that would change the
+ // request path (such as "..") fails this submit, not the page render.
+ result = await submitAction(
+ router,
+ interpolateRouteParams(url, options?.params),
+ {
+ method: payload.method,
+ data: payload.snapshot,
+ preserveScroll: options?.preserveScroll,
+ _resolveOnShell: true,
+ },
+ options,
+ );
+ } catch (submitError) {
+ if (isAbortError(submitError)) {
+ return { status: 'idle', defaults: previousOutcome.defaults };
}
+ throw submitError;
+ }
- if (!result.ok) {
- const validationErrors = isCallSiteActionError(result.error)
- ? getValidationErrors(result.error.body)
- : null;
- if (validationErrors) {
- return runErrorCallback(
- {
- status: 'validation',
- defaults: previousOutcome.defaults,
- errors: validationErrors,
- },
- validationErrors,
- );
- }
+ if (!result.ok) {
+ const validationErrors = isCallSiteActionError(result.error)
+ ? getValidationErrors(result.error.body)
+ : null;
+ if (validationErrors) {
return runErrorCallback(
{
- status: 'error',
+ status: 'validation',
defaults: previousOutcome.defaults,
- error: result.error,
+ errors: validationErrors,
},
- result.error,
+ validationErrors,
);
}
+ return runErrorCallback(
+ {
+ status: 'error',
+ defaults: previousOutcome.defaults,
+ error: result.error,
+ },
+ result.error,
+ );
+ }
- const nextDefaults = options?.resetOnSuccess
- ? cloneFormValue(initialDefaults)
- : cloneFormValue(payload.snapshot);
- const nextOutcome: SubmissionOutcome = { status: 'success', defaults: nextDefaults };
- // Helpers called after an await still belong to this successful submission.
- callbackOutcomeRef.current = nextOutcome;
- try {
- await options?.onSuccess?.();
- } finally {
- if (callbackOutcomeRef.current === nextOutcome) {
- callbackOutcomeRef.current = null;
- }
+ const nextDefaults = options?.resetOnSuccess
+ ? cloneFormValue(initialDefaults)
+ : cloneFormValue(payload.snapshot);
+ const nextOutcome: SubmissionOutcome = { status: 'success', defaults: nextDefaults };
+ // Helpers called after an await still belong to this successful submission.
+ callbackOutcomeRef.current = nextOutcome;
+ try {
+ await options?.onSuccess?.();
+ } finally {
+ if (callbackOutcomeRef.current === nextOutcome) {
+ callbackOutcomeRef.current = null;
}
- if (options?.resetOnSuccess && dataRef.current === payload.dispatchData) {
- dataRef.current = cloneFormValue(initialDefaults);
- setDataState(dataRef.current);
+ }
+ if (options?.resetOnSuccess && dataRef.current === payload.dispatchData) {
+ dataRef.current = cloneFormValue(initialDefaults);
+ setDataState(dataRef.current);
+ }
+ return nextOutcome;
+ };
+
+ const [outcome, dispatchAction, pending] = useActionState(
+ async (previousOutcome, payload) => {
+ try {
+ const nextOutcome = await runSubmission(previousOutcome, payload);
+ payload.settle?.(nextOutcome);
+ return nextOutcome;
+ } catch (submitError) {
+ payload.fail?.(submitError);
+ throw submitError;
}
- return nextOutcome;
},
{ status: 'idle', defaults: initialDefaults },
);
@@ -299,6 +323,22 @@ export function useForm(
[dispatchAction],
);
+ const submit = useCallback(
+ (method: FormMethod = 'post') =>
+ new Promise((resolve, reject) => {
+ startTransition(() => {
+ dispatchAction({
+ method: method.toUpperCase(),
+ snapshot: cloneFormValue(dataRef.current),
+ dispatchData: dataRef.current,
+ settle: (next) => resolve(toSubmitResult(next)),
+ fail: reject,
+ });
+ });
+ }),
+ [dispatchAction],
+ );
+
const post = useMemo(() => dispatchMethodAction('POST'), [dispatchMethodAction]);
const put = useMemo(() => dispatchMethodAction('PUT'), [dispatchMethodAction]);
const patch = useMemo(() => dispatchMethodAction('PATCH'), [dispatchMethodAction]);
@@ -313,6 +353,7 @@ export function useForm(
hasChanges,
wasSuccessful,
recentlySuccessful,
+ submit,
post,
put,
patch,
@@ -323,3 +364,16 @@ export function useForm(
clearError,
};
}
+
+function toSubmitResult(outcome: SubmissionOutcome): FormSubmitResult {
+ switch (outcome.status) {
+ case 'success':
+ return { status: 'success' };
+ case 'validation':
+ return { status: 'invalid', errors: outcome.errors };
+ case 'error':
+ return { status: 'error', error: outcome.error };
+ case 'idle':
+ return { status: 'cancelled' };
+ }
+}
diff --git a/packages/react/test/unit/use-form.test.ts b/packages/react/test/unit/use-form.test.ts
index a82fcbc0e6..e18bc6248e 100644
--- a/packages/react/test/unit/use-form.test.ts
+++ b/packages/react/test/unit/use-form.test.ts
@@ -810,3 +810,25 @@ describe('useForm state derivation and error management', () => {
}
});
});
+
+describe('useForm submit()', () => {
+ it('resolves with how the submission ended', async () => {
+ const visit = vi.fn(async () => ({}));
+ const { formRef } = await mountForm(visit);
+ await act(async () => {
+ formRef.current!.setData('title', 'Hello');
+ });
+
+ let result: unknown;
+ await act(async () => {
+ result = await formRef.current!.submit('put');
+ });
+
+ expect(result).toEqual({ status: 'success' });
+ expect(visit).toHaveBeenCalledWith(
+ actionUrl,
+ expect.objectContaining({ method: 'PUT', data: { title: 'Hello' } }),
+ );
+ expect(formRef.current!.wasSuccessful).toBe(true);
+ });
+});
diff --git a/packages/solid/src/runtime/use-form.ts b/packages/solid/src/runtime/use-form.ts
index ec38857f0c..a00849b0c8 100644
--- a/packages/solid/src/runtime/use-form.ts
+++ b/packages/solid/src/runtime/use-form.ts
@@ -11,9 +11,11 @@ import {
submitAction,
} from 'void/pages-client';
import type {
+ FormMethod,
FormResetOptions,
FormState,
FormSubmitOptions,
+ FormSubmitResult,
VoidActionError,
} from 'void/pages-client';
import type { ActionUrl, ResolveActionBody, ActionFormOptions } from 'void/routes';
@@ -126,7 +128,11 @@ export function useForm(
setActionError(null);
}
- async function submit(method: string, opts: FormSubmitOptions = {}) {
+ async function submit(method: string, opts: FormSubmitOptions = {}): Promise {
+ await run(method, opts);
+ }
+
+ async function run(method: string, opts: FormSubmitOptions = {}): Promise {
const requestId = ++latestRequestId;
// Edits made while this request is in flight stay unsaved.
const submittedData = cloneFormValue(data);
@@ -158,7 +164,7 @@ export function useForm(
);
// A newer submit owns the form's state, even if this one still completed.
if (requestId !== latestRequestId) {
- return;
+ return { status: 'cancelled' };
}
if (!result.ok) {
@@ -167,10 +173,10 @@ export function useForm(
: null;
if (validationErrors) {
replaceErrors(validationErrors);
- } else {
- setActionError(result.error);
+ return { status: 'invalid', errors: validationErrors };
}
- return;
+ setActionError(result.error);
+ return { status: 'error', error: result.error };
}
setWasSuccessful(true);
@@ -186,9 +192,10 @@ export function useForm(
successTimeout = setTimeout(() => {
setRecentlySuccessful(false);
}, 2000);
+ return { status: 'success' };
} catch (submitError) {
if (isAbortError(submitError)) {
- return;
+ return { status: 'cancelled' };
}
throw submitError;
} finally {
@@ -225,6 +232,7 @@ export function useForm(
setError: setFieldError,
clearErrors,
clearError,
+ submit: (method: FormMethod = 'post') => run(method.toUpperCase()),
post: (opts?: FormSubmitOptions) => submit('POST', opts),
put: (opts?: FormSubmitOptions) => submit('PUT', opts),
patch: (opts?: FormSubmitOptions) => submit('PATCH', opts),
diff --git a/packages/svelte/src/runtime/use-form.svelte.ts b/packages/svelte/src/runtime/use-form.svelte.ts
index 6ccd00927f..a50aed67f4 100644
--- a/packages/svelte/src/runtime/use-form.svelte.ts
+++ b/packages/svelte/src/runtime/use-form.svelte.ts
@@ -10,9 +10,11 @@ import {
submitAction,
} from 'void/pages-client';
import type {
+ FormMethod,
FormResetOptions,
FormState,
FormSubmitOptions,
+ FormSubmitResult,
VoidRouter,
VoidActionError,
} from 'void/pages-client';
@@ -123,7 +125,11 @@ export function useForm(
error = null;
}
- async function submit(method: string, opts: FormSubmitOptions = {}) {
+ async function submit(method: string, opts: FormSubmitOptions = {}): Promise {
+ await run(method, opts);
+ }
+
+ async function run(method: string, opts: FormSubmitOptions = {}): Promise {
const requestId = ++latestRequestId;
// Edits made while this request is in flight stay unsaved.
const submittedData = cloneFormValue(data);
@@ -151,7 +157,7 @@ export function useForm(
);
// A newer submit owns the form's state, even if this one still completed.
if (requestId !== latestRequestId) {
- return;
+ return { status: 'cancelled' };
}
if (!result.ok) {
@@ -162,10 +168,10 @@ export function useForm(
for (const [field, message] of Object.entries(validationErrors)) {
setError(field, message);
}
- } else {
- error = result.error;
+ return { status: 'invalid', errors: validationErrors };
}
- return;
+ error = result.error;
+ return { status: 'error', error: result.error };
}
wasSuccessful = true;
@@ -181,9 +187,10 @@ export function useForm(
successTimeout = setTimeout(() => {
recentlySuccessful = false;
}, 2000);
+ return { status: 'success' };
} catch (submitError) {
if (isAbortError(submitError)) {
- return;
+ return { status: 'cancelled' };
}
throw submitError;
} finally {
@@ -219,6 +226,7 @@ export function useForm(
setError,
clearErrors,
clearError,
+ submit: (method: FormMethod = 'post') => run(method.toUpperCase()),
post: (opts?: FormSubmitOptions) => submit('POST', opts),
put: (opts?: FormSubmitOptions) => submit('PUT', opts),
patch: (opts?: FormSubmitOptions) => submit('PATCH', opts),
diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md
index 2df952b689..1dcc06ff80 100644
--- a/packages/void/AGENTS.md
+++ b/packages/void/AGENTS.md
@@ -51,6 +51,8 @@ Pages and island actions opt in to `X-VoidPages-Redirect: manual`. The routing m
`submitAction()` appends the current page query to an action URL on the same path and names the added segments in `X-VoidPages-Preserved-Query`. Exclude that suffix when selecting an action and when marking its key before middleware; the action and loader still receive the full query. Named-action `c.redirect()` also strips the suffix before merging the request query. Rewrites with their own query clear this metadata so their explicit parameters can select an action. Keep the segments verbatim: history and scroll preservation compare the returned page URL with `location.pathname + location.search` as strings.
+Vite plugins extend the Pages client entry through `api.voidPagesClient = { module, options? }` (`pages/client-extensions.ts`). The generated entry calls each module's default export with a `PagesClientContext` (router, client page patterns, `matchPage`) and the JSON options. `@void/webmcp` uses it for the `navigate` tool; keep optional features like that in their own packages instead of the adapters.
+
Pages `_not-found`/`_error` recovery uses finite render plans that retain logical layout slots. Never serialize original exceptions through framework hydration helpers, rerun a failed loader/action, or cache an error document. Native client boundaries reset on every visit/refresh and preserve healthy ancestor layouts.
Recover response-less 4xx/5xx Hono `HTTPException`s only for page GET/HEAD requests: nearest boundary for loaders/handler middleware, root boundary for application middleware. Preserve redirects, explicit responses, API routes, actions, and existing 404 recovery. Middleware recovery must identify the actual matched endpoint without loading its module or replaying request code.
diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md
index f36ee0b6e0..f076889fc2 100644
--- a/packages/void/skills/void/SKILL.md
+++ b/packages/void/skills/void/SKILL.md
@@ -43,6 +43,7 @@ Use `void deploy --skip-migrations` when database migrations run separately; it
| App type detection and mode behavior | `docs/guide/app-types.md`, `docs/reference/config.md` |
| Server/API routing and middleware | `docs/guide/server-routing.md`, `docs/integrations/hono.md` |
| Pages mode, loader/action, forms, layouts | `docs/guide/pages-routing/*.md`, `docs/guide/type-safety.md` |
+| Browser agent tools (WebMCP) | `docs/guide/pages-routing/webmcp.md` |
| Database and migrations | `docs/guide/database.md`, `docs/guide/type-safety.md` |
| D1 replicas, bookmarks, read-after-write | `docs/guide/database/d1.md`, `docs/reference/api/database.md` |
| Typed fetch and end-to-end typing | `docs/guide/typed-fetch.md`, `docs/guide/type-safety.md` |
diff --git a/packages/void/src/pages/client-context.ts b/packages/void/src/pages/client-context.ts
new file mode 100644
index 0000000000..54cab0d676
--- /dev/null
+++ b/packages/void/src/pages/client-context.ts
@@ -0,0 +1,26 @@
+import type { VoidRouter } from './client.ts';
+import { decodePagePath } from './url.ts';
+
+/** A page of the app. `path` writes params as `[id]` and catch-all params as `[...slug]`. */
+export type ClientPage = { path: string; title?: string };
+
+/** What the default export of a Pages client extension module receives. */
+export type PagesClientContext = {
+ router: VoidRouter;
+ /** The app's pages, with their Markdown titles. */
+ pages: ReadonlyArray;
+ /** Whether a page matches `pathname`, a URL pathname such as `/users/1`. */
+ matchPage: (pathname: string) => boolean;
+};
+
+export function createPagesClientContext(
+ router: VoidRouter,
+ matchRoute: (path: string) => string | null,
+ pages: ReadonlyArray,
+): PagesClientContext {
+ return {
+ router,
+ pages,
+ matchPage: (pathname) => matchRoute(decodePagePath(pathname)) !== null,
+ };
+}
diff --git a/packages/void/src/pages/client-extensions.ts b/packages/void/src/pages/client-extensions.ts
new file mode 100644
index 0000000000..b2d474f812
--- /dev/null
+++ b/packages/void/src/pages/client-extensions.ts
@@ -0,0 +1,105 @@
+import type { Plugin } from 'vite';
+import type { ClientPage } from './client-context.ts';
+import type { PageScanResult } from './types.ts';
+
+/**
+ * Code another Vite plugin adds to the Pages client entry. A plugin offers it as
+ * `api.voidPagesClient`. The client entry imports `module` and calls its default export with a
+ * `PagesClientContext` and `options` once the router exists.
+ */
+export type PagesClientExtension = {
+ /** A module specifier the client entry can import, such as a package export. */
+ module: string;
+ /** A JSON-serializable value passed to the default export. */
+ options?: unknown;
+};
+
+function isClientExtension(value: unknown): value is PagesClientExtension {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ typeof (value as { module?: unknown }).module === 'string'
+ );
+}
+
+/** The client extensions that resolved Vite plugins offer, in plugin order. */
+export function collectClientExtensions(
+ plugins: ReadonlyArray,
+): Array {
+ const extensions: Array = [];
+ for (const plugin of plugins) {
+ const extension: unknown = (plugin.api as { voidPagesClient?: unknown } | undefined)
+ ?.voidPagesClient;
+ if (extension === undefined) {
+ continue;
+ }
+ if (!isClientExtension(extension)) {
+ throw new TypeError(
+ `Vite plugin "${plugin.name}" sets api.voidPagesClient without a module specifier.`,
+ );
+ }
+ extensions.push(extension);
+ }
+ return extensions;
+}
+
+/** `/users/:id` as `/users/[id]`, the route syntax of page files and typed route strings. */
+function displayPattern(pattern: string): string {
+ return pattern
+ .split('/')
+ .map((segment) => {
+ if (segment === '*') {
+ return '[...path]';
+ }
+ const match = /^:([^{}]+)(\{\.\+\})?$/.exec(segment);
+ if (!match) {
+ return segment;
+ }
+ return match[2] ? `[...${match[1]}]` : `[${match[1]}]`;
+ })
+ .join('/');
+}
+
+/** The app's pages, once each, with their Markdown titles. */
+export function clientPages(scan: PageScanResult): Array {
+ const pages: Array = [];
+ const seen = new Set();
+ for (const page of scan.pages) {
+ const path = displayPattern(page.pattern);
+ if (seen.has(path)) {
+ continue;
+ }
+ seen.add(path);
+ const title = page.metadata?.title;
+ pages.push(title ? { path, title } : { path });
+ }
+ return pages;
+}
+
+/**
+ * Client entry code that runs each extension. It expects `router` and `matchRoute` in scope, as
+ * every generated client entry defines them.
+ */
+export function generateClientExtensionCode(
+ scan: PageScanResult,
+ extensions: ReadonlyArray,
+): string {
+ if (extensions.length === 0) {
+ return '';
+ }
+ const lines = [
+ '',
+ 'import { createPagesClientContext as __voidPagesClientContext } from "void/pages-client";',
+ ...extensions.map(
+ (extension, index) =>
+ `import __voidClientExtension${index} from ${JSON.stringify(extension.module)};`,
+ ),
+ `const __voidClientContext = __voidPagesClientContext(router, matchRoute, ${JSON.stringify(clientPages(scan))});`,
+ ...extensions.map(
+ (extension, index) =>
+ `__voidClientExtension${index}(__voidClientContext, ${JSON.stringify(extension.options ?? null)});`,
+ ),
+ '',
+ ];
+ return lines.join('\n');
+}
diff --git a/packages/void/src/pages/client.ts b/packages/void/src/pages/client.ts
index 9fc9483286..39d1583f55 100644
--- a/packages/void/src/pages/client.ts
+++ b/packages/void/src/pages/client.ts
@@ -657,10 +657,16 @@ export {
type FormMethod,
type FormState,
type FormSubmitOptions,
+ type FormSubmitResult,
type IslandFormState,
} from './form-presentation.ts';
export type { PageError, ErrorPageProps } from './types.ts';
+export {
+ createPagesClientContext,
+ type ClientPage,
+ type PagesClientContext,
+} from './client-context.ts';
export {
pageBoundarySlots,
clientPageError,
diff --git a/packages/void/src/pages/form-presentation.ts b/packages/void/src/pages/form-presentation.ts
index f5d0772da0..8ac459bd7f 100644
--- a/packages/void/src/pages/form-presentation.ts
+++ b/packages/void/src/pages/form-presentation.ts
@@ -12,6 +12,12 @@ export type FormModel = []> = Pick & {
data?: Record;
};
+/** How a `useForm()` submission ended. */
+export type FormSubmitResult =
+ | { status: 'success' }
+ | { status: 'invalid'; errors: Record }
+ | { status: 'error'; error: VoidActionError }
+ | { status: 'cancelled' };
/** Submission state that `useForm()` and `useIslandForm()` report in every adapter. */
export type FormStatus = {
readonly error: VoidActionError | null;
@@ -43,6 +49,11 @@ export type FormState = FormStatus &
setError(field: keyof TData & string, message: string): void;
clearErrors(...fields: ReadonlyArray): void;
clearError(): void;
+ /**
+ * Submit the current values and resolve with how the submission ended. Validation and action
+ * errors resolve; with `throwOnError` on, other HTTP failures reject.
+ */
+ submit(method?: FormMethod): Promise;
}>;
/**
* The `useIslandForm()` contract every adapter shares. Errors are keyed by whatever names the
diff --git a/packages/void/src/pages/index.ts b/packages/void/src/pages/index.ts
index b5e4457878..7319885dc3 100644
--- a/packages/void/src/pages/index.ts
+++ b/packages/void/src/pages/index.ts
@@ -15,6 +15,7 @@ export { resolveHead, renderHeadToString, renderHtmlAttrs, renderBodyAttrs } fro
export type { HeadDescriptor, HeadConfig } from './head.ts';
export { generateComponentManifest } from './manifest.ts';
export { createPagesPlugin, resolvePrefetchConfig } from './plugin.ts';
+export type { PagesClientExtension } from './client-extensions.ts';
export type { PagesPluginOptions, PrefetchConfig } from './plugin.ts';
export { resolveStaticPageDataBuildOptions } from './static-data.ts';
export type { StaticPageDataBuildOptions } from './static-data.ts';
diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts
index ee9bfd4974..c5536926e7 100644
--- a/packages/void/src/pages/plugin.ts
+++ b/packages/void/src/pages/plugin.ts
@@ -2,6 +2,8 @@ import { existsSync } from 'node:fs';
import { dirname } from 'pathslash';
import { normalizePath } from 'vite';
import type { Plugin, ResolvedConfig, UserConfig } from 'vite';
+import { collectClientExtensions, generateClientExtensionCode } from './client-extensions.ts';
+import type { PagesClientExtension } from './client-extensions.ts';
import { assertLinkPrefetchValue } from './prefetch.ts';
import type { CacheForInput, LinkPrefetchValue } from './prefetch.ts';
import { scanPages } from './scan.ts';
@@ -61,6 +63,7 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp
let pageScan: PageScanResult | null = null;
let isDev = false;
let viteConfig: ResolvedConfig | undefined;
+ let clientExtensions: Array = [];
const root = options.root ?? dirname(pagesDir);
const normalizedPagesDir = normalizePath(pagesDir);
let pendingRescan: Promise | null = null;
@@ -115,7 +118,10 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp
const staticPageData = isDev
? { enabled: false, fastPath: false }
: resolveStaticPageDataBuildOptions(root, { publicDir: viteConfig?.publicDir });
- return options.generateClient(pageScan, staticPageData);
+ return (
+ options.generateClient(pageScan, staticPageData) +
+ generateClientExtensionCode(pageScan, clientExtensions)
+ );
}
},
},
@@ -162,6 +168,7 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp
configResolved(config) {
viteConfig = config;
+ clientExtensions = collectClientExtensions(config.plugins);
},
config(_, env) {
diff --git a/packages/void/test/unit/pages-client-extensions.test.ts b/packages/void/test/unit/pages-client-extensions.test.ts
new file mode 100644
index 0000000000..35db5cdd05
--- /dev/null
+++ b/packages/void/test/unit/pages-client-extensions.test.ts
@@ -0,0 +1,89 @@
+import type { Plugin } from 'vite';
+import { describe, expect, it, vi } from 'vite-plus/test';
+import { createPagesClientContext } from '../../src/pages/client-context.ts';
+import {
+ clientPages,
+ collectClientExtensions,
+ generateClientExtensionCode,
+} from '../../src/pages/client-extensions.ts';
+import type { VoidRouter } from '../../src/pages/client.ts';
+import type { PageDefinition, PageScanResult } from '../../src/pages/types.ts';
+
+const page = (pattern: string, metadata?: PageDefinition['metadata']) =>
+ ({ pattern, metadata }) as PageDefinition;
+
+const scan = (pages: Array): PageScanResult => ({
+ pages,
+ layouts: [],
+ namedLayouts: [],
+});
+
+describe('Pages client extensions', () => {
+ it('lists pages once each in page-file route syntax', () => {
+ expect(
+ clientPages(
+ scan([
+ page('/', { title: 'Home' }),
+ page('/users/:id'),
+ page('/docs/:slug{.+}'),
+ page('/files/*'),
+ page('/users/:id'),
+ ]),
+ ),
+ ).toEqual([
+ { path: '/', title: 'Home' },
+ { path: '/users/[id]' },
+ { path: '/docs/[...slug]' },
+ { path: '/files/[...path]' },
+ ]);
+ });
+
+ it('collects api.voidPagesClient from Vite plugins in order', () => {
+ const plugins = [
+ { name: 'first', api: { voidPagesClient: { module: 'first/client', options: { a: 1 } } } },
+ { name: 'unrelated', api: { other: true } },
+ { name: 'plain' },
+ { name: 'second', api: { voidPagesClient: { module: 'second/client' } } },
+ ] as Array;
+ expect(collectClientExtensions(plugins)).toEqual([
+ { module: 'first/client', options: { a: 1 } },
+ { module: 'second/client' },
+ ]);
+ });
+
+ it('rejects an extension without a module specifier', () => {
+ const plugins = [{ name: 'broken', api: { voidPagesClient: {} } }] as Array;
+ expect(() => collectClientExtensions(plugins)).toThrow(
+ 'Vite plugin "broken" sets api.voidPagesClient without a module specifier.',
+ );
+ });
+
+ it('adds no client code without extensions', () => {
+ expect(generateClientExtensionCode(scan([page('/')]), [])).toBe('');
+ });
+
+ it('calls each extension with the page context and its options', () => {
+ const code = generateClientExtensionCode(scan([page('/', { title: 'Home' })]), [
+ { module: 'first/client', options: { navigate: true } },
+ { module: 'second/client' },
+ ]);
+ expect(code).toContain('import __voidClientExtension0 from "first/client";');
+ expect(code).toContain('import __voidClientExtension1 from "second/client";');
+ expect(code).toContain(
+ 'const __voidClientContext = __voidPagesClientContext(router, matchRoute, [{"path":"/","title":"Home"}]);',
+ );
+ expect(code).toContain('__voidClientExtension0(__voidClientContext, {"navigate":true});');
+ expect(code).toContain('__voidClientExtension1(__voidClientContext, null);');
+ });
+
+ it('matches decoded pathnames against the route matcher', () => {
+ const matchRoute = vi.fn((path: string) => (path.startsWith('/users/') ? 'users' : null));
+ const context = createPagesClientContext({} as VoidRouter, matchRoute, [
+ { path: '/users/[id]' },
+ ]);
+ expect(context.matchPage('/users/J%C3%BCrgen')).toBe(true);
+ expect(matchRoute).toHaveBeenCalledWith('/users/Jürgen');
+ expect(context.matchPage('/missing')).toBe(false);
+ expect(context.pages).toEqual([{ path: '/users/[id]' }]);
+ });
+});
diff --git a/packages/void/test/unit/pages-plugin-adapters.test.ts b/packages/void/test/unit/pages-plugin-adapters.test.ts
index 825a74e94c..61dcda40c9 100644
--- a/packages/void/test/unit/pages-plugin-adapters.test.ts
+++ b/packages/void/test/unit/pages-plugin-adapters.test.ts
@@ -11,7 +11,7 @@ import { pagesPlugin as vuePagesPlugin } from '../../../vue/src/plugin-pages.ts'
type Hook = T | { handler: T; filter?: { id: RegExp } };
type PagesPluginHooks = {
config: Hook<(config: object, env: { command: 'serve' | 'build' }) => unknown>;
- configResolved: (config: { publicDir: string | false }) => void;
+ configResolved: (config: { publicDir: string | false; plugins: Array }) => void;
buildStart: Hook<() => Promise>;
resolveId: Hook<(id: string) => string | undefined>;
load: Hook<(id: string) => Promise>;
@@ -137,7 +137,11 @@ describe.each(adapters)('$name Pages plugin contract', (adapter) => {
mkdirSync(publicDir);
writeFileSync(join(publicDir, '_redirects'), '/old /new 302');
await handler(plugin.config)({}, { command: 'build' });
- plugin.configResolved({ publicDir });
+ const extension = {
+ name: 'extension',
+ api: { voidPagesClient: { module: 'extension/client' } },
+ };
+ plugin.configResolved({ publicDir, plugins: [plugin, extension] });
await handler(plugin.buildStart)();
const client = await handler(plugin.load)('\0virtual:void-pages-client');
@@ -147,8 +151,10 @@ describe.each(adapters)('$name Pages plugin contract', (adapter) => {
expect(client).toContain('prefetchHoverDelay: 123');
expect(client).toContain('parseCacheFor("45s")');
expect(client).toContain('prefetchDefaultStrategy: ["hover","click"]');
+ expect(client).toContain('__voidPagesClientContext(router, matchRoute, [{"path":"/"}])');
+ expect(client).toContain('__voidClientExtension0(__voidClientContext, null);');
- plugin.configResolved({ publicDir: false });
+ plugin.configResolved({ publicDir: false, plugins: [] });
expect(await handler(plugin.load)('\0virtual:void-pages-client')).toContain(
'staticPageDataFastPath: true',
);
diff --git a/packages/vue/src/runtime/use-form.ts b/packages/vue/src/runtime/use-form.ts
index e6087c5ba8..f5f4679374 100644
--- a/packages/vue/src/runtime/use-form.ts
+++ b/packages/vue/src/runtime/use-form.ts
@@ -9,9 +9,11 @@ import {
submitAction,
} from 'void/pages-client';
import type {
+ FormMethod,
FormResetOptions,
FormState,
FormSubmitOptions,
+ FormSubmitResult,
VoidRouter,
VoidActionError,
} from 'void/pages-client';
@@ -101,7 +103,11 @@ export function useForm(
error.value = null;
}
- async function submit(method: string, opts: FormSubmitOptions = {}) {
+ async function submit(method: string, opts: FormSubmitOptions = {}): Promise {
+ await run(method, opts);
+ }
+
+ async function run(method: string, opts: FormSubmitOptions = {}): Promise {
const requestId = ++latestRequestId;
// Edits made while this request is in flight stay unsaved.
const submittedData = cloneFormValue(data);
@@ -133,7 +139,7 @@ export function useForm(
);
// A newer submit owns the form's state, even if this one still completed.
if (requestId !== latestRequestId) {
- return;
+ return { status: 'cancelled' };
}
if (!result.ok) {
@@ -142,10 +148,10 @@ export function useForm(
: null;
if (validationErrors) {
Object.assign(errors, validationErrors);
- } else {
- error.value = result.error;
+ return { status: 'invalid', errors: validationErrors };
}
- return;
+ error.value = result.error;
+ return { status: 'error', error: result.error };
}
wasSuccessful.value = true;
@@ -161,9 +167,10 @@ export function useForm(
successTimeout = setTimeout(() => {
recentlySuccessful.value = false;
}, 2000);
+ return { status: 'success' };
} catch (submitError) {
if (isAbortError(submitError)) {
- return;
+ return { status: 'cancelled' };
}
throw submitError;
} finally {
@@ -185,6 +192,7 @@ export function useForm(
setError,
clearErrors,
clearError,
+ submit: (method: FormMethod = 'post') => run(method.toUpperCase()),
post: (opts?: FormSubmitOptions) => submit('POST', opts),
put: (opts?: FormSubmitOptions) => submit('PUT', opts),
patch: (opts?: FormSubmitOptions) => submit('PATCH', opts),
diff --git a/packages/vue/test/unit/use-form.test.ts b/packages/vue/test/unit/use-form.test.ts
index 01dbfaef41..a01931ad4c 100644
--- a/packages/vue/test/unit/use-form.test.ts
+++ b/packages/vue/test/unit/use-form.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test';
-import type { VoidRouter } from 'void/pages-client';
+import { VoidActionError } from 'void/pages-client';
+import type { FormSubmitResult, VoidRouter } from 'void/pages-client';
import { createSSRApp, defineComponent, h, nextTick } from 'vue';
import { renderToString } from 'vue/server-renderer';
import { useForm as typedUseForm } from '../../src/runtime/use-form.ts';
@@ -13,6 +14,7 @@ type TestForm = {
pending: boolean;
wasSuccessful: boolean;
post(): Promise;
+ submit(method?: 'post' | 'put' | 'patch' | 'delete'): Promise;
reset: (...args: Array) => void;
};
@@ -118,6 +120,34 @@ describe('useForm reset', () => {
});
});
+describe('useForm submit()', () => {
+ it('resolves with how the submission ended', async () => {
+ const visit = vi.fn(async () => ({}));
+ const form = await mountForm({ title: '' }, undefined, { visit } as unknown as VoidRouter);
+ form.data.title = 'Hello';
+
+ await expect(form.submit('put')).resolves.toEqual({ status: 'success' });
+ expect(visit).toHaveBeenCalledWith(
+ '/notes?create',
+ expect.objectContaining({ method: 'PUT', data: { title: 'Hello' } }),
+ );
+
+ visit.mockRejectedValueOnce(
+ new VoidActionError({
+ body: { errors: { title: 'Title is required' } },
+ status: 422,
+ statusText: '',
+ url: '/notes?create',
+ }),
+ );
+ await expect(form.submit()).resolves.toEqual({
+ status: 'invalid',
+ errors: { title: 'Title is required' },
+ });
+ expect(form.errors.title).toBe('Title is required');
+ });
+});
+
describe('useForm setError', () => {
it('clears errors after repeated nested object and array edits', async () => {
const app = createSSRApp(
diff --git a/packages/webmcp/README.md b/packages/webmcp/README.md
new file mode 100644
index 0000000000..c867b9cb0f
--- /dev/null
+++ b/packages/webmcp/README.md
@@ -0,0 +1,45 @@
+# @void/webmcp
+
+[WebMCP](https://webmachinelearning.github.io/webmcp/) tools for [Void](https://void.cloud) Pages. Let AI agents in the browser fill in and submit your forms, read page data, and navigate your app.
+
+## Setup
+
+Install alongside `void` and your framework adapter:
+
+```sh
+npm install @void/webmcp
+```
+
+Add `voidWebMcp()` to your Vite config to offer a `navigate` tool. For example, with React:
+
+```ts
+import { voidReact } from '@void/react/plugin';
+import { voidWebMcp } from '@void/webmcp/plugin';
+import { defineConfig } from 'vite';
+import { voidPlugin } from 'void';
+
+export default defineConfig({
+ plugins: [voidPlugin(), voidReact(), voidWebMcp()],
+});
+```
+
+Offer tools from your pages with `useFormTool()` and `useAgentTool()`:
+
+```tsx
+import { useForm } from '@void/react';
+import { useFormTool } from '@void/webmcp/react';
+
+const form = useForm('/users', { name: '', email: '' });
+useFormTool(form, {
+ name: 'add_user',
+ description: 'Add a person to the user directory. Use when the user asks to add someone.',
+});
+```
+
+Vue, Svelte, and Solid import from `@void/webmcp/vue`, `@void/webmcp/svelte`, and `@void/webmcp/solid`. Where the browser does not support WebMCP, these APIs do nothing.
+
+## Documentation
+
+See [WebMCP](https://void.cloud/guide/pages-routing/webmcp) for form tools, component tools, input schemas, and the `navigate` tool.
+
+Read the [Void documentation](https://void.cloud) online or use the Markdown guides and references in `node_modules/void/docs/`, included with the `void` package.
diff --git a/packages/webmcp/package.json b/packages/webmcp/package.json
new file mode 100644
index 0000000000..f4f9bac67b
--- /dev/null
+++ b/packages/webmcp/package.json
@@ -0,0 +1,98 @@
+{
+ "name": "@void/webmcp",
+ "version": "1.11.0",
+ "description": "Let AI agents in the browser use Void pages through WebMCP tools.",
+ "homepage": "https://void.cloud",
+ "bugs": {
+ "url": "https://github.com/voidzero-dev/void/issues"
+ },
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/voidzero-dev/void.git",
+ "directory": "packages/webmcp"
+ },
+ "files": [
+ "dist"
+ ],
+ "type": "module",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.mts",
+ "import": "./dist/index.mjs"
+ },
+ "./plugin": {
+ "types": "./dist/plugin.d.mts",
+ "import": "./dist/plugin.mjs"
+ },
+ "./client": {
+ "types": "./dist/client.d.mts",
+ "import": "./dist/client.mjs"
+ },
+ "./react": {
+ "types": "./dist/react.d.mts",
+ "import": "./dist/react.mjs"
+ },
+ "./vue": {
+ "types": "./dist/vue.d.mts",
+ "import": "./dist/vue.mjs"
+ },
+ "./svelte": {
+ "types": "./dist/svelte.d.mts",
+ "import": "./dist/svelte.mjs"
+ },
+ "./solid": {
+ "types": "./dist/solid.d.mts",
+ "import": "./dist/solid.mjs"
+ }
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "scripts": {
+ "build": "vp pack",
+ "dev": "vp pack --watch",
+ "typecheck": "tsrs --noEmit --rootDir ../.."
+ },
+ "devDependencies": {
+ "@types/node": "catalog:",
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "happy-dom": "catalog:",
+ "react": "catalog:",
+ "react-dom": "catalog:",
+ "solid-js": "catalog:",
+ "svelte": "catalog:",
+ "tsrs": "catalog:",
+ "vite": "catalog:",
+ "vite-plus": "catalog:",
+ "void": "workspace:*",
+ "vue": "catalog:",
+ "zod": "^4.6.7"
+ },
+ "peerDependencies": {
+ "react": "^19.0.0",
+ "solid-js": "^1.9.0",
+ "svelte": "^5.0.0",
+ "vite": "^8.0.0",
+ "void": "workspace:*",
+ "vue": "^3.5.0"
+ },
+ "peerDependenciesMeta": {
+ "react": {
+ "optional": true
+ },
+ "solid-js": {
+ "optional": true
+ },
+ "svelte": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ },
+ "vue": {
+ "optional": true
+ }
+ }
+}
diff --git a/packages/webmcp/src/client.ts b/packages/webmcp/src/client.ts
new file mode 100644
index 0000000000..a56398c537
--- /dev/null
+++ b/packages/webmcp/src/client.ts
@@ -0,0 +1,12 @@
+import type { PagesClientContext } from 'void/pages-client';
+import { registerNavigateTool } from './tools.ts';
+
+/** Runs in the Pages client entry when the app uses `voidWebMcp()`. */
+export default function startWebMcp(
+ context: PagesClientContext,
+ options: { navigate?: boolean } | null,
+): void {
+ if (options?.navigate !== false) {
+ registerNavigateTool(context);
+ }
+}
diff --git a/packages/webmcp/src/index.ts b/packages/webmcp/src/index.ts
new file mode 100644
index 0000000000..d813b4c39d
--- /dev/null
+++ b/packages/webmcp/src/index.ts
@@ -0,0 +1,13 @@
+export {
+ defineAgentTool,
+ isWebMcpSupported,
+ registerAgentTool,
+ registerFormAgentTool,
+ type AgentForm,
+ type AgentTool,
+ type AgentToolAnnotations,
+ type AgentToolContext,
+ type AgentToolResult,
+ type FormToolHost,
+ type FormToolOptions,
+} from './tools.ts';
diff --git a/packages/webmcp/src/plugin.ts b/packages/webmcp/src/plugin.ts
new file mode 100644
index 0000000000..cb1263fbd2
--- /dev/null
+++ b/packages/webmcp/src/plugin.ts
@@ -0,0 +1,16 @@
+import type { Plugin } from 'vite';
+import type { PagesClientExtension } from 'void/pages';
+
+export type VoidWebMcpOptions = {
+ /** Offer a `navigate` tool that opens any of the app's pages. Defaults to `true`. */
+ navigate?: boolean;
+};
+
+/** Offer the app's pages to agents in the browser through WebMCP. */
+export function voidWebMcp(options: VoidWebMcpOptions = {}): Plugin {
+ const extension: PagesClientExtension = {
+ module: '@void/webmcp/client',
+ options: { navigate: options.navigate ?? true },
+ };
+ return { name: 'void:webmcp', api: { voidPagesClient: extension } };
+}
diff --git a/packages/webmcp/src/react.ts b/packages/webmcp/src/react.ts
new file mode 100644
index 0000000000..b807702385
--- /dev/null
+++ b/packages/webmcp/src/react.ts
@@ -0,0 +1,75 @@
+import { useEffect, useInsertionEffect, useRef } from 'react';
+import { agentFormHost, registerAgentTool, registerFormAgentTool } from './tools.ts';
+import type { AgentForm, AgentTool, FormToolOptions } from './tools.ts';
+
+export {
+ defineAgentTool,
+ isWebMcpSupported,
+ type AgentTool,
+ type AgentToolAnnotations,
+ type AgentToolContext,
+ type AgentToolResult,
+ type FormToolOptions,
+} from './tools.ts';
+
+type SettersForm = AgentForm & { setData(field: string, value: unknown): void };
+
+function isEnabled(enabled: AgentTool['enabled']): boolean {
+ return typeof enabled === 'function' ? enabled() : enabled !== false;
+}
+
+/**
+ * Offer a WebMCP tool to agents in the browser while the component is mounted. Calls use the
+ * latest `execute` and `enabled`; a changed name, description or schema registers the tool again.
+ */
+export function useAgentTool(tool: AgentTool): void {
+ const latest = useRef(tool);
+ useInsertionEffect(() => {
+ latest.current = tool;
+ }, [tool]);
+ const key = JSON.stringify([
+ tool.name,
+ tool.title,
+ tool.description,
+ tool.inputSchema,
+ tool.annotations,
+ ]);
+ useEffect(() => {
+ return registerAgentTool({
+ ...latest.current,
+ enabled: () => isEnabled(latest.current.enabled),
+ execute: (input, context) => latest.current.execute(input, context),
+ });
+ }, [key]);
+}
+
+/**
+ * Let agents fill in and submit a `useForm()` form while the component is mounted. A call fills
+ * in the values the user sees, then submits the form, unless `confirm` is set.
+ */
+export function useFormTool(form: SettersForm, options: FormToolOptions): void {
+ const latest = useRef({ form, options });
+ useInsertionEffect(() => {
+ latest.current = { form, options };
+ }, [form, options]);
+ const key = JSON.stringify([
+ options.name,
+ options.title,
+ options.description,
+ options.method,
+ options.confirm,
+ options.annotations,
+ options.inputSchema,
+ ]);
+ useEffect(() => {
+ const { form: current, options: initial } = latest.current;
+ return registerFormAgentTool(
+ { ...initial, enabled: () => isEnabled(latest.current.options.enabled) },
+ { ...(current.data as Record) },
+ agentFormHost(
+ () => latest.current.form,
+ (field, value) => latest.current.form.setData(field, value),
+ ),
+ );
+ }, [key]);
+}
diff --git a/packages/webmcp/src/solid.ts b/packages/webmcp/src/solid.ts
new file mode 100644
index 0000000000..05f4717452
--- /dev/null
+++ b/packages/webmcp/src/solid.ts
@@ -0,0 +1,41 @@
+import { onCleanup, onMount } from 'solid-js';
+import { agentFormHost, registerAgentTool, registerFormAgentTool } from './tools.ts';
+import type { AgentForm, AgentTool, FormToolOptions } from './tools.ts';
+
+export {
+ defineAgentTool,
+ isWebMcpSupported,
+ type AgentTool,
+ type AgentToolAnnotations,
+ type AgentToolContext,
+ type AgentToolResult,
+ type FormToolOptions,
+} from './tools.ts';
+
+type SettersForm = AgentForm & { setData(field: string, value: unknown): void };
+
+/** Offer a WebMCP tool to agents in the browser while the component is mounted. */
+export function useAgentTool(tool: AgentTool): void {
+ onMount(() => {
+ onCleanup(registerAgentTool(tool));
+ });
+}
+
+/**
+ * Let agents fill in and submit a `useForm()` form while the component is mounted. A call fills
+ * in the values the user sees, then submits the form, unless `confirm` is set.
+ */
+export function useFormTool(form: SettersForm, options: FormToolOptions): void {
+ onMount(() => {
+ onCleanup(
+ registerFormAgentTool(
+ options,
+ { ...(form.data as Record) },
+ agentFormHost(
+ () => form,
+ (field, value) => form.setData(field, value),
+ ),
+ ),
+ );
+ });
+}
diff --git a/packages/webmcp/src/standard-schema.ts b/packages/webmcp/src/standard-schema.ts
new file mode 100644
index 0000000000..d6fd37ccf4
--- /dev/null
+++ b/packages/webmcp/src/standard-schema.ts
@@ -0,0 +1,41 @@
+/**
+ * Standard Schema V1 types, inlined from the spec, which lets libraries copy them.
+ * https://github.com/standard-schema/standard-schema
+ */
+export type StandardSchemaV1 = {
+ readonly '~standard': StandardSchemaV1.Props ;
+};
+
+export declare namespace StandardSchemaV1 {
+ type Props = {
+ readonly version: 1;
+ readonly vendor: string;
+ readonly validate: (value: unknown) => Result | Promise>;
+ readonly types?: Types | undefined;
+ };
+
+ type Result = SuccessResult | FailureResult;
+
+ type SuccessResult = {
+ readonly value: Output;
+ readonly issues?: undefined;
+ };
+
+ type FailureResult = {
+ readonly issues: ReadonlyArray;
+ };
+
+ type Issue = {
+ readonly message: string;
+ readonly path?: ReadonlyArray | undefined;
+ };
+
+ type PathSegment = {
+ readonly key: PropertyKey;
+ };
+
+ type Types = {
+ readonly input: Input;
+ readonly output: Output;
+ };
+}
diff --git a/packages/webmcp/src/svelte.ts b/packages/webmcp/src/svelte.ts
new file mode 100644
index 0000000000..5ce69f2c29
--- /dev/null
+++ b/packages/webmcp/src/svelte.ts
@@ -0,0 +1,37 @@
+import { onMount } from 'svelte';
+import { agentFormHost, registerAgentTool, registerFormAgentTool } from './tools.ts';
+import type { AgentForm, AgentTool, FormToolOptions } from './tools.ts';
+
+export {
+ defineAgentTool,
+ isWebMcpSupported,
+ type AgentTool,
+ type AgentToolAnnotations,
+ type AgentToolContext,
+ type AgentToolResult,
+ type FormToolOptions,
+} from './tools.ts';
+
+/** Offer a WebMCP tool to agents in the browser while the component is mounted. */
+export function useAgentTool(tool: AgentTool): void {
+ onMount(() => registerAgentTool(tool));
+}
+
+/**
+ * Let agents fill in and submit a `useForm()` form while the component is mounted. A call fills
+ * in the values the user sees, then submits the form, unless `confirm` is set.
+ */
+export function useFormTool(form: AgentForm, options: FormToolOptions): void {
+ onMount(() =>
+ registerFormAgentTool(
+ options,
+ { ...(form.data as Record) },
+ agentFormHost(
+ () => form,
+ (field, value) => {
+ (form.data as Record)[field] = value;
+ },
+ ),
+ ),
+ );
+}
diff --git a/packages/webmcp/src/tools.ts b/packages/webmcp/src/tools.ts
new file mode 100644
index 0000000000..050159cfa0
--- /dev/null
+++ b/packages/webmcp/src/tools.ts
@@ -0,0 +1,490 @@
+///
+
+import type { FormMethod, FormSubmitResult, PagesClientContext } from 'void/pages-client';
+import type { StandardSchemaV1 } from './standard-schema.ts';
+
+/** Hints that tell the browser or agent how a tool behaves. */
+export type AgentToolAnnotations = {
+ /** The tool only reads data, so an agent can call it without asking. */
+ readOnlyHint?: boolean;
+ /** The tool has effects that are hard to undo, so the agent may ask the user first. */
+ consequentialHint?: boolean;
+ /** The tool can return content from sources the app does not control. */
+ untrustedContentHint?: boolean;
+};
+
+export type AgentToolContext = {
+ /** Aborted when the agent or the user cancels the call. */
+ readonly signal: AbortSignal;
+};
+
+/** An MCP tool result. `execute` may return one to control exactly what the agent receives. */
+export type AgentToolResult = {
+ content: Array<{ type: 'text'; text: string }>;
+ isError?: boolean;
+};
+
+/** A WebMCP tool that a page offers to agents in the browser. */
+export type AgentTool> = {
+ /** 1 to 128 ASCII letters, digits, `_`, `-` or `.`. */
+ name: string;
+ title?: string;
+ /** What the tool does for the user, and when an agent should use it. */
+ description: string;
+ /**
+ * A Standard Schema that validates each call. A schema that implements Standard JSON
+ * Schema also describes the tool's parameters to the agent.
+ */
+ input?: StandardSchemaV1;
+ /** A JSON Schema describing the parameters, when `input` cannot describe them. */
+ inputSchema?: Record;
+ annotations?: AgentToolAnnotations;
+ /** Whether a call can run now. A disabled tool stays registered and rejects calls. */
+ enabled?: boolean | (() => boolean);
+ /**
+ * Runs a call. A string is sent as text and other values as JSON; an `AgentToolResult` is sent
+ * as it is. An error thrown here reaches the agent as an error result with its message.
+ */
+ execute(input: TInput, context: AgentToolContext): unknown;
+};
+
+/** Options of `useFormTool()`. */
+export type FormToolOptions = {
+ /** 1 to 128 ASCII letters, digits, `_`, `-` or `.`. */
+ name: string;
+ title?: string;
+ /** What submitting the form does for the user, and when an agent should do it. */
+ description: string;
+ /** The method the form submits with. Defaults to `"post"`. */
+ method?: FormMethod;
+ /** A Standard Schema that validates the form's values before they are filled in. */
+ input?: StandardSchemaV1;
+ /** A JSON Schema describing the fields, when the defaults and `input` cannot. */
+ inputSchema?: Record;
+ annotations?: AgentToolAnnotations;
+ /** Fill in the form without submitting it, so the user reviews and submits it. */
+ confirm?: boolean;
+ /** Whether a call can run now. A disabled tool stays registered and rejects calls. */
+ enabled?: boolean | (() => boolean);
+};
+
+/** The parts of a `useForm()` form that its tool drives. */
+export type FormToolHost = {
+ isPending(): boolean;
+ values(): Record;
+ fill(values: Record): void;
+ submit(method: FormMethod): Promise;
+};
+
+/** A form returned by `useForm()` in any Pages adapter. */
+export type AgentForm = {
+ readonly pending: boolean;
+ readonly data: object;
+ submit(method?: FormMethod): Promise;
+};
+
+/** The host a form tool drives. `fill` sets one field the way the adapter's forms do. */
+export function agentFormHost(
+ form: () => AgentForm,
+ fill: (field: string, value: unknown) => void,
+): FormToolHost {
+ return {
+ isPending: () => form().pending,
+ values: () => ({ ...(form().data as Record) }),
+ fill(values) {
+ for (const [field, value] of Object.entries(values)) {
+ fill(field, value);
+ }
+ },
+ submit: (method) => form().submit(method),
+ };
+}
+
+/** The subset of JSON Schema that form tools infer from their defaults. */
+type InferredJsonSchema = {
+ type?: 'string' | 'number' | 'boolean' | 'array' | 'object';
+ items?: InferredJsonSchema;
+ properties?: Record;
+ additionalProperties?: boolean;
+};
+
+type ModelContextTool = {
+ name: string;
+ title?: string;
+ description: string;
+ inputSchema?: Record;
+ annotations?: AgentToolAnnotations;
+ execute(input: unknown, options: AgentToolContext): Promise;
+};
+
+type ModelContext = {
+ registerTool(tool: ModelContextTool, options: { signal: AbortSignal }): unknown;
+};
+
+type Registration = { tool: ModelContextTool; controller: AbortController | null };
+
+const TOOL_NAME = /^[\w.-]{1,128}$/;
+
+/** Registrations by name. The last one registered is the one the browser has. */
+const registrations = new Map>();
+
+/** Define a tool for `useAgentTool()`, inferring its input type from `input`. */
+export function defineAgentTool>(
+ tool: AgentTool,
+): AgentTool {
+ assertToolName(tool.name);
+ return tool;
+}
+
+function assertToolName(name: string): void {
+ if (!TOOL_NAME.test(name)) {
+ throw new TypeError(
+ `Invalid agent tool name "${name}". Use 1 to 128 ASCII letters, digits, "_", "-" or ".".`,
+ );
+ }
+}
+
+function getModelContext(): ModelContext | undefined {
+ if (typeof document === 'undefined') {
+ return undefined;
+ }
+ const context: unknown = (document as { modelContext?: unknown }).modelContext;
+ if (
+ typeof context === 'object' &&
+ context !== null &&
+ typeof (context as Partial).registerTool === 'function'
+ ) {
+ return context as ModelContext;
+ }
+ return undefined;
+}
+
+/** Whether the browser offers WebMCP tools to agents. */
+export function isWebMcpSupported(): boolean {
+ return getModelContext() !== undefined;
+}
+
+function activate(context: ModelContext, registration: Registration): void {
+ const controller = new AbortController();
+ registration.controller = controller;
+ void new Promise((resolve) => {
+ resolve(context.registerTool(registration.tool, { signal: controller.signal }));
+ }).catch((error: unknown) => {
+ if (!controller.signal.aborted) {
+ console.error(
+ `[@void/webmcp] Could not register the agent tool "${registration.tool.name}".`,
+ error,
+ );
+ }
+ });
+}
+
+function deactivate(registration: Registration | undefined): void {
+ registration?.controller?.abort();
+ if (registration) {
+ registration.controller = null;
+ }
+}
+
+/**
+ * Offer a tool to agents until the returned function is called. Does nothing in browsers
+ * without WebMCP. When two tools share a name, the newer one is offered until it is removed.
+ */
+export function registerAgentTool(tool: AgentTool): () => void {
+ assertToolName(tool.name);
+ const context = getModelContext();
+ if (!context) {
+ return () => {};
+ }
+ const registration: Registration = { tool: toModelContextTool(tool), controller: null };
+ let stack = registrations.get(tool.name);
+ if (!stack) {
+ stack = [];
+ registrations.set(tool.name, stack);
+ }
+ deactivate(stack.at(-1));
+ stack.push(registration);
+ activate(context, registration);
+
+ let removed = false;
+ return () => {
+ if (removed) {
+ return;
+ }
+ removed = true;
+ const current = registrations.get(tool.name);
+ const index = current?.indexOf(registration) ?? -1;
+ if (!current || index === -1) {
+ return;
+ }
+ const wasActive = index === current.length - 1;
+ current.splice(index, 1);
+ deactivate(registration);
+ const next = current.at(-1);
+ if (wasActive && next) {
+ activate(context, next);
+ }
+ if (current.length === 0) {
+ registrations.delete(tool.name);
+ }
+ };
+}
+
+function isEnabled(enabled: AgentTool['enabled']): boolean {
+ return typeof enabled === 'function' ? enabled() : enabled !== false;
+}
+
+function toModelContextTool(tool: AgentTool): ModelContextTool {
+ const inputSchema = resolveInputSchema(tool.input, tool.inputSchema);
+ return {
+ name: tool.name,
+ ...(tool.title === undefined ? {} : { title: tool.title }),
+ description: tool.description,
+ ...(inputSchema ? { inputSchema } : {}),
+ ...(tool.annotations ? { annotations: tool.annotations } : {}),
+ async execute(rawInput, { signal }) {
+ try {
+ if (!isEnabled(tool.enabled)) {
+ throw new Error(`The tool "${tool.name}" is not available right now.`);
+ }
+ const input = isRecord(rawInput) ? rawInput : {};
+ const value = tool.input ? await parseInput(tool.input, input) : (input as TInput);
+ return toToolResult(await tool.execute(value, { signal }));
+ } catch (error) {
+ // Browsers report a rejected call without its message, so send the message as a result.
+ if (signal.aborted) {
+ throw error;
+ }
+ return textResult(errorMessage(error), true);
+ }
+ },
+ };
+}
+
+function textResult(text: string, isError = false): AgentToolResult {
+ return isError
+ ? { content: [{ type: 'text', text }], isError }
+ : { content: [{ type: 'text', text }] };
+}
+
+function isToolResult(value: unknown): value is AgentToolResult {
+ return isRecord(value) && Array.isArray(value.content);
+}
+
+function toToolResult(value: unknown): AgentToolResult {
+ if (isToolResult(value)) {
+ return value;
+ }
+ if (value === undefined || value === null) {
+ return textResult('Done.');
+ }
+ return textResult(typeof value === 'string' ? value : JSON.stringify(value));
+}
+
+function errorMessage(error: unknown): string {
+ if (error instanceof Error) {
+ return error.message;
+ }
+ return typeof error === 'string' ? error : 'The tool failed.';
+}
+
+type StandardJsonSchemaProps = {
+ jsonSchema?: { input?: (options: { target: string }) => Record };
+};
+
+/** The tool's JSON Schema: `inputSchema`, else the one `input` describes through Standard JSON Schema. */
+export function resolveInputSchema(
+ input: StandardSchemaV1 | undefined,
+ inputSchema: Record | undefined,
+): Record | undefined {
+ if (inputSchema) {
+ return inputSchema;
+ }
+ const convert = (input?.['~standard'] as StandardJsonSchemaProps | undefined)?.jsonSchema?.input;
+ if (typeof convert !== 'function') {
+ return undefined;
+ }
+ try {
+ const { $schema: _dialect, ...schema } = convert({ target: 'draft-2020-12' });
+ return schema;
+ } catch {
+ return undefined;
+ }
+}
+
+async function parseInput(
+ schema: StandardSchemaV1,
+ value: unknown,
+): Promise {
+ const result = await schema['~standard'].validate(value);
+ if (result.issues) {
+ throw new Error(`The input is invalid. ${formatIssues(result.issues)}`);
+ }
+ return result.value;
+}
+
+function formatIssues(issues: ReadonlyArray): string {
+ return issues
+ .map((issue) => {
+ const path = issue.path
+ ?.map((segment) => String(typeof segment === 'object' ? segment.key : segment))
+ .join('.');
+ return path ? `${path}: ${issue.message}` : issue.message;
+ })
+ .join('; ');
+}
+
+function isRecord(value: unknown): value is Record {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function isFileValue(value: unknown): boolean {
+ return (
+ (typeof Blob !== 'undefined' && value instanceof Blob) ||
+ (typeof FileList !== 'undefined' && value instanceof FileList)
+ );
+}
+
+function inferValueSchema(value: unknown): InferredJsonSchema {
+ if (typeof value === 'string') {
+ return { type: 'string' };
+ }
+ if (typeof value === 'number') {
+ return { type: 'number' };
+ }
+ if (typeof value === 'boolean') {
+ return { type: 'boolean' };
+ }
+ if (Array.isArray(value)) {
+ return value.length > 0
+ ? { type: 'array', items: inferValueSchema(value[0]) }
+ : { type: 'array' };
+ }
+ if (isRecord(value)) {
+ return { type: 'object' };
+ }
+ return {};
+}
+
+/** Form fields an agent can fill in: every default except files, which agents cannot send. */
+function formToolFields(defaults: Record): Array {
+ return Object.keys(defaults).filter((field) => !isFileValue(defaults[field]));
+}
+
+function inferFormInputSchema(
+ defaults: Record,
+ fields: ReadonlyArray,
+): InferredJsonSchema {
+ const properties: Record = {};
+ for (const field of fields) {
+ properties[field] = inferValueSchema(defaults[field]);
+ }
+ return { type: 'object', properties, additionalProperties: false };
+}
+
+function currentPath(): string {
+ return typeof window === 'undefined' ? '/' : window.location.pathname + window.location.search;
+}
+
+/**
+ * The tool `useFormTool()` offers. A call fills in the form, so the user sees the values, then
+ * submits it like the user would, unless `confirm` is set.
+ */
+export function createFormAgentTool(
+ options: FormToolOptions,
+ defaults: Record,
+ host: FormToolHost,
+): AgentTool {
+ const fields = formToolFields(defaults);
+ return {
+ name: options.name,
+ ...(options.title === undefined ? {} : { title: options.title }),
+ description: options.description,
+ inputSchema:
+ resolveInputSchema(options.input, options.inputSchema) ??
+ inferFormInputSchema(defaults, fields),
+ ...(options.annotations ? { annotations: options.annotations } : {}),
+ ...(options.enabled === undefined ? {} : { enabled: options.enabled }),
+ async execute(values, { signal }) {
+ if (host.isPending()) {
+ throw new Error('The form is already being submitted. Wait for it to finish.');
+ }
+ for (const field of Object.keys(values)) {
+ if (!fields.includes(field)) {
+ throw new Error(
+ `The form has no field "${field}". Its fields are: ${fields.join(', ') || 'none'}.`,
+ );
+ }
+ }
+ if (options.input) {
+ await parseInput(options.input, { ...host.values(), ...values });
+ }
+ signal.throwIfAborted();
+ host.fill(values);
+ if (options.confirm) {
+ return {
+ status: 'requires_user_action',
+ message: 'The form is filled in. Ask the user to review and submit it.',
+ };
+ }
+ const outcome = await host.submit(options.method ?? 'post');
+ switch (outcome.status) {
+ case 'success':
+ return { status: 'submitted', url: currentPath() };
+ case 'invalid':
+ throw new Error(
+ `The form was not submitted. ${Object.entries(outcome.errors)
+ .map(([field, message]) => `${field}: ${message}`)
+ .join('; ')}`,
+ );
+ case 'error':
+ throw new Error(outcome.error.message);
+ case 'cancelled':
+ throw new Error('The submission was cancelled.');
+ }
+ },
+ };
+}
+
+/** Offer a form's tool until the returned function is called. */
+export function registerFormAgentTool(
+ options: FormToolOptions,
+ defaults: Record,
+ host: FormToolHost,
+): () => void {
+ return registerAgentTool(createFormAgentTool(options, defaults, host));
+}
+
+/** Offer a `navigate` tool that opens one of the app's pages. */
+export function registerNavigateTool({ router, pages, matchPage }: PagesClientContext): () => void {
+ const list = pages
+ .map((page) => (page.title ? `${page.path} (${page.title})` : page.path))
+ .join(', ');
+ return registerAgentTool<{ path?: unknown }>({
+ name: 'navigate',
+ description:
+ 'Open a page of this app. Use when the user wants something on a page that is not open. Each page offers its own tools.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: {
+ type: 'string',
+ description: `The page path, optionally with a query string. Replace each [param] with a value. Pages: ${list}`,
+ },
+ },
+ required: ['path'],
+ additionalProperties: false,
+ },
+ annotations: { readOnlyHint: true },
+ async execute(input) {
+ const path = typeof input.path === 'string' ? input.path.trim() : '';
+ const url =
+ path.startsWith('/') && !path.startsWith('//') ? new URL(path, location.origin) : null;
+ if (!url || url.origin !== location.origin || !matchPage(url.pathname)) {
+ throw new Error(`No page matches "${path}". Pages: ${list}`);
+ }
+ await router.visit(url.pathname + url.search + url.hash);
+ return { url: currentPath(), title: document.title };
+ },
+ });
+}
diff --git a/packages/webmcp/src/vue.ts b/packages/webmcp/src/vue.ts
new file mode 100644
index 0000000000..2c2872a2c0
--- /dev/null
+++ b/packages/webmcp/src/vue.ts
@@ -0,0 +1,45 @@
+import { onMounted, onUnmounted } from 'vue';
+import { agentFormHost, registerAgentTool, registerFormAgentTool } from './tools.ts';
+import type { AgentForm, AgentTool, FormToolOptions } from './tools.ts';
+
+export {
+ defineAgentTool,
+ isWebMcpSupported,
+ type AgentTool,
+ type AgentToolAnnotations,
+ type AgentToolContext,
+ type AgentToolResult,
+ type FormToolOptions,
+} from './tools.ts';
+
+function useRegistration(register: () => () => void): void {
+ let unregister: (() => void) | undefined;
+ onMounted(() => {
+ unregister = register();
+ });
+ onUnmounted(() => unregister?.());
+}
+
+/** Offer a WebMCP tool to agents in the browser while the component is mounted. */
+export function useAgentTool(tool: AgentTool): void {
+ useRegistration(() => registerAgentTool(tool));
+}
+
+/**
+ * Let agents fill in and submit a `useForm()` form while the component is mounted. A call fills
+ * in the values the user sees, then submits the form, unless `confirm` is set.
+ */
+export function useFormTool(form: AgentForm, options: FormToolOptions): void {
+ useRegistration(() =>
+ registerFormAgentTool(
+ options,
+ { ...(form.data as Record) },
+ agentFormHost(
+ () => form,
+ (field, value) => {
+ (form.data as Record)[field] = value;
+ },
+ ),
+ ),
+ );
+}
diff --git a/packages/webmcp/test/unit/react.test.ts b/packages/webmcp/test/unit/react.test.ts
new file mode 100644
index 0000000000..6b61f9aeb9
--- /dev/null
+++ b/packages/webmcp/test/unit/react.test.ts
@@ -0,0 +1,106 @@
+// @vitest-environment happy-dom
+
+import { act, createElement, useState } from 'react';
+import { createRoot } from 'react-dom/client';
+import type { Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test';
+import type { FormSubmitResult } from 'void/pages-client';
+import { useAgentTool, useFormTool } from '../../src/react.ts';
+import type { AgentToolResult } from '../../src/react.ts';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+type RegisteredTool = {
+ name: string;
+ description: string;
+ inputSchema?: Record;
+ execute(input: unknown, options: { signal: AbortSignal }): Promise;
+};
+
+let tools: Map;
+let root: Root | undefined;
+
+beforeEach(() => {
+ tools = new Map();
+ Object.defineProperty(document, 'modelContext', {
+ configurable: true,
+ value: {
+ registerTool(tool: RegisteredTool, { signal }: { signal: AbortSignal }) {
+ tools.set(tool.name, tool);
+ signal.addEventListener('abort', () => tools.delete(tool.name), { once: true });
+ return Promise.resolve();
+ },
+ },
+ });
+});
+
+afterEach(() => {
+ if (root) {
+ act(() => root?.unmount());
+ root = undefined;
+ }
+ Reflect.deleteProperty(document, 'modelContext');
+});
+
+function render(element: ReturnType) {
+ root = createRoot(document.createElement('div'));
+ act(() => root?.render(element));
+}
+
+async function call(name: string, input: unknown = {}): Promise {
+ const tool = tools.get(name);
+ if (!tool) {
+ throw new Error(`Tool "${name}" is not registered.`);
+ }
+ let result: AgentToolResult | undefined;
+ await act(async () => {
+ result = await tool.execute(input, { signal: new AbortController().signal });
+ });
+ return result as AgentToolResult;
+}
+
+describe('useAgentTool', () => {
+ it('registers while mounted and calls the latest execute', async () => {
+ let setLabel!: (label: string) => void;
+ function Tool() {
+ const [label, update] = useState('first');
+ setLabel = update;
+ useAgentTool({ name: 'label', description: 'Read the label', execute: () => label });
+ return null;
+ }
+ render(createElement(Tool));
+ expect((await call('label')).content[0]?.text).toBe('first');
+
+ act(() => setLabel('second'));
+ expect((await call('label')).content[0]?.text).toBe('second');
+
+ act(() => root?.unmount());
+ root = undefined;
+ expect(tools.has('label')).toBe(false);
+ });
+});
+
+describe('useFormTool', () => {
+ it('fills the form with setData and submits it', async () => {
+ const setData = vi.fn();
+ const submit = vi.fn(async (): Promise => ({ status: 'success' }));
+ function Form() {
+ useFormTool(
+ { pending: false, data: { name: '', email: '' }, setData, submit },
+ { name: 'add_user', description: 'Add a user' },
+ );
+ return null;
+ }
+ render(createElement(Form));
+
+ expect(tools.get('add_user')?.inputSchema).toMatchObject({
+ properties: { name: { type: 'string' }, email: { type: 'string' } },
+ });
+ const result = await call('add_user', { name: 'Ada', email: 'ada@example.com' });
+
+ expect(setData).toHaveBeenCalledWith('name', 'Ada');
+ expect(setData).toHaveBeenCalledWith('email', 'ada@example.com');
+ expect(submit).toHaveBeenCalledOnce();
+ expect(result.isError).toBeUndefined();
+ });
+});
diff --git a/packages/webmcp/test/unit/tools.test.ts b/packages/webmcp/test/unit/tools.test.ts
new file mode 100644
index 0000000000..94aa3fbeab
--- /dev/null
+++ b/packages/webmcp/test/unit/tools.test.ts
@@ -0,0 +1,435 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test';
+import { VoidActionError } from 'void/pages-client';
+import type { FormSubmitResult, VoidRouter } from 'void/pages-client';
+import { z } from 'zod';
+import {
+ createFormAgentTool,
+ defineAgentTool,
+ isWebMcpSupported,
+ registerAgentTool,
+ registerNavigateTool,
+} from '../../src/tools.ts';
+import type { AgentToolResult, FormToolHost } from '../../src/tools.ts';
+
+type RegisteredTool = {
+ name: string;
+ title?: string;
+ description: string;
+ inputSchema?: Record;
+ annotations?: Record;
+ execute(input: unknown, options: { signal: AbortSignal }): Promise;
+};
+
+let tools: Map;
+let registerTool: ReturnType;
+
+function stubModelContext() {
+ tools = new Map();
+ registerTool = vi.fn((tool: RegisteredTool, { signal }: { signal: AbortSignal }) => {
+ if (tools.has(tool.name)) {
+ throw new DOMException(`Duplicate tool name "${tool.name}"`, 'InvalidStateError');
+ }
+ tools.set(tool.name, tool);
+ signal.addEventListener('abort', () => tools.delete(tool.name), { once: true });
+ return Promise.resolve();
+ });
+ vi.stubGlobal('document', { modelContext: { registerTool }, title: 'Page' });
+ vi.stubGlobal('window', { location: { pathname: '/', search: '' } });
+ vi.stubGlobal('location', { origin: 'https://app.test' });
+}
+
+function tool(name: string): RegisteredTool {
+ const registered = tools.get(name);
+ if (!registered) {
+ throw new Error(`Tool "${name}" is not registered.`);
+ }
+ return registered;
+}
+
+function call(name: string, input: unknown = {}) {
+ return tool(name).execute(input, { signal: new AbortController().signal });
+}
+
+function ok(text: unknown): AgentToolResult {
+ return { content: [{ type: 'text', text: text as string }] };
+}
+
+function failed(text: unknown): AgentToolResult {
+ return { content: [{ type: 'text', text: text as string }], isError: true };
+}
+
+async function flush() {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('registerAgentTool', () => {
+ it('does nothing in browsers without WebMCP', () => {
+ vi.stubGlobal('document', {});
+ expect(isWebMcpSupported()).toBe(false);
+ const unregister = registerAgentTool({ name: 'noop', description: 'x', execute: () => 1 });
+ expect(() => unregister()).not.toThrow();
+ });
+
+ it('rejects names that WebMCP does not accept', () => {
+ expect(() =>
+ defineAgentTool({ name: 'add to cart', description: 'x', execute: () => 1 }),
+ ).toThrow(/Invalid agent tool name "add to cart"/);
+ });
+
+ describe('with WebMCP', () => {
+ beforeEach(stubModelContext);
+
+ it('registers the tool until it is removed', async () => {
+ const unregister = registerAgentTool({
+ name: 'greet',
+ title: 'Greet',
+ description: 'Say hello.',
+ annotations: { readOnlyHint: true },
+ execute: () => 'Hello',
+ });
+ await flush();
+ expect(tool('greet')).toMatchObject({
+ title: 'Greet',
+ description: 'Say hello.',
+ annotations: { readOnlyHint: true },
+ });
+ await expect(call('greet')).resolves.toEqual(ok('Hello'));
+ unregister();
+ expect(tools.has('greet')).toBe(false);
+ });
+
+ it('describes and validates the input with a Standard JSON Schema', async () => {
+ const execute = vi.fn(({ query }: { query: string }) => [query]);
+ registerAgentTool(
+ defineAgentTool({
+ name: 'search',
+ description: 'Find products.',
+ input: z.object({ query: z.string().min(2) }),
+ execute,
+ }),
+ );
+ await flush();
+ expect(tool('search').inputSchema).not.toHaveProperty('$schema');
+ expect(tool('search').inputSchema).toMatchObject({
+ type: 'object',
+ properties: { query: { type: 'string', minLength: 2 } },
+ required: ['query'],
+ });
+ await expect(call('search', { query: 'tea' })).resolves.toEqual(ok('["tea"]'));
+ await expect(call('search', { query: 'x' })).resolves.toEqual(
+ failed(expect.stringMatching(/^The input is invalid\. query: /)),
+ );
+ expect(execute).toHaveBeenCalledTimes(1);
+ });
+
+ it('prefers an explicit inputSchema and passes the abort signal', async () => {
+ const controller = new AbortController();
+ registerAgentTool({
+ name: 'echo',
+ description: 'Echo.',
+ inputSchema: { type: 'object', properties: { text: { type: 'string' } } },
+ execute: (input, { signal }) => ({ input, aborted: signal.aborted }),
+ });
+ await flush();
+ expect(tool('echo').inputSchema).toEqual({
+ type: 'object',
+ properties: { text: { type: 'string' } },
+ });
+ controller.abort();
+ await expect(
+ tool('echo').execute({ text: 'hi' }, { signal: controller.signal }),
+ ).resolves.toEqual(ok('{"input":{"text":"hi"},"aborted":true}'));
+ });
+
+ it('rejects calls while disabled and reports a void result as done', async () => {
+ let enabled = false;
+ registerAgentTool({
+ name: 'toggle',
+ description: 'Toggle.',
+ enabled: () => enabled,
+ execute: () => undefined,
+ });
+ await flush();
+ await expect(call('toggle')).resolves.toEqual(
+ failed('The tool "toggle" is not available right now.'),
+ );
+ enabled = true;
+ await expect(call('toggle')).resolves.toEqual(ok('Done.'));
+ });
+
+ it('offers the newest tool with a shared name and restores the older one', async () => {
+ const removeFirst = registerAgentTool({ name: 'cart', description: 'A', execute: () => 'a' });
+ const removeSecond = registerAgentTool({
+ name: 'cart',
+ description: 'B',
+ execute: () => 'b',
+ });
+ await flush();
+ await expect(call('cart')).resolves.toEqual(ok('b'));
+ removeSecond();
+ await flush();
+ await expect(call('cart')).resolves.toEqual(ok('a'));
+ removeSecond();
+ removeFirst();
+ expect(tools.has('cart')).toBe(false);
+ expect(registerTool).toHaveBeenCalledTimes(3);
+ });
+
+ it('keeps the newest tool when an older one is removed first', async () => {
+ const removeFirst = registerAgentTool({ name: 'cart', description: 'A', execute: () => 'a' });
+ registerAgentTool({ name: 'cart', description: 'B', execute: () => 'b' });
+ removeFirst();
+ await flush();
+ await expect(call('cart')).resolves.toEqual(ok('b'));
+ expect(registerTool).toHaveBeenCalledTimes(2);
+ });
+
+ it('sends an MCP result as it is and keeps aborts as rejections', async () => {
+ const result: AgentToolResult = { content: [{ type: 'text', text: 'raw' }] };
+ const abort = new AbortController();
+ registerAgentTool({ name: 'raw', description: 'x', execute: () => result });
+ registerAgentTool({
+ name: 'slow',
+ description: 'x',
+ execute: (_input, { signal }) => {
+ abort.abort();
+ signal.throwIfAborted();
+ },
+ });
+ registerAgentTool({
+ name: 'thrower',
+ description: 'x',
+ execute: () => {
+ throw new Error('Out of stock');
+ },
+ });
+ await flush();
+ await expect(call('raw')).resolves.toBe(result);
+ await expect(call('thrower')).resolves.toEqual(failed('Out of stock'));
+ await expect(tool('slow').execute({}, { signal: abort.signal })).rejects.toThrow();
+ });
+
+ it('logs a registration the browser rejects', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ registerTool.mockImplementationOnce(() => Promise.reject(new Error('Not allowed')));
+ registerAgentTool({ name: 'blocked', description: 'x', execute: () => 1 });
+ await flush();
+ expect(error).toHaveBeenCalledWith(
+ '[@void/webmcp] Could not register the agent tool "blocked".',
+ expect.any(Error),
+ );
+ });
+ });
+});
+
+function formHost(
+ values: Record,
+ outcome: FormSubmitResult = { status: 'success' },
+): FormToolHost & { submitted: Array } {
+ const submitted: Array = [];
+ return {
+ submitted,
+ isPending: () => false,
+ values: () => ({ ...values }),
+ fill(next) {
+ Object.assign(values, next);
+ },
+ submit(method) {
+ submitted.push(method);
+ return Promise.resolve(outcome);
+ },
+ };
+}
+
+function runFormTool(
+ formTool: ReturnType,
+ input: Record,
+) {
+ return formTool.execute(input, { signal: new AbortController().signal });
+}
+
+describe('createFormAgentTool', () => {
+ beforeEach(() => {
+ vi.stubGlobal('window', { location: { pathname: '/notes/1', search: '?tab=all' } });
+ });
+
+ it('infers the input from the defaults, leaving out files', () => {
+ const formTool = createFormAgentTool(
+ { name: 'create_note', description: 'Create a note.' },
+ { title: '', stars: 0, pinned: false, tags: ['a'], meta: {}, cover: new Blob([]) },
+ formHost({}),
+ );
+ expect(formTool.inputSchema).toEqual({
+ type: 'object',
+ properties: {
+ title: { type: 'string' },
+ stars: { type: 'number' },
+ pinned: { type: 'boolean' },
+ tags: { type: 'array', items: { type: 'string' } },
+ meta: { type: 'object' },
+ },
+ additionalProperties: false,
+ });
+ });
+
+ it('uses the JSON Schema of `input` when it has one', () => {
+ const formTool = createFormAgentTool(
+ { name: 'create_note', description: 'x', input: z.object({ title: z.string() }) },
+ { title: '' },
+ formHost({}),
+ );
+ expect(formTool.inputSchema).toMatchObject({ required: ['title'] });
+ });
+
+ it('fills in and submits the form, then reports the current page', async () => {
+ const values: Record = { title: '', body: 'kept' };
+ const host = formHost(values);
+ const formTool = createFormAgentTool(
+ { name: 'update_note', description: 'x', method: 'put' },
+ { title: '', body: '' },
+ host,
+ );
+ await expect(runFormTool(formTool, { title: 'Hello' })).resolves.toEqual({
+ status: 'submitted',
+ url: '/notes/1?tab=all',
+ });
+ expect(values).toEqual({ title: 'Hello', body: 'kept' });
+ expect(host.submitted).toEqual(['put']);
+ });
+
+ it('only fills in the form when the user must confirm', async () => {
+ const values: Record = { title: '' };
+ const host = formHost(values);
+ const formTool = createFormAgentTool(
+ { name: 'create_note', description: 'x', confirm: true },
+ { title: '' },
+ host,
+ );
+ await expect(runFormTool(formTool, { title: 'Draft' })).resolves.toMatchObject({
+ status: 'requires_user_action',
+ });
+ expect(values.title).toBe('Draft');
+ expect(host.submitted).toEqual([]);
+ });
+
+ it('rejects fields the form does not have, before filling anything in', async () => {
+ const values: Record = { title: '' };
+ const formTool = createFormAgentTool(
+ { name: 'f', description: 'x' },
+ { title: '' },
+ formHost(values),
+ );
+ await expect(runFormTool(formTool, { title: 'a', role: 'admin' })).rejects.toThrow(
+ 'The form has no field "role". Its fields are: title.',
+ );
+ expect(values.title).toBe('');
+ });
+
+ it('validates the filled-in values with `input`', async () => {
+ const values: Record = { email: 'a@b.co', message: '' };
+ const formTool = createFormAgentTool(
+ {
+ name: 'contact',
+ description: 'x',
+ input: z.object({ email: z.email(), message: z.string().min(5) }),
+ },
+ { email: '', message: '' },
+ formHost(values),
+ );
+ await expect(runFormTool(formTool, { message: 'Hi' })).rejects.toThrow(
+ /^The input is invalid\. message: /,
+ );
+ expect(values.message).toBe('');
+ });
+
+ it('reports validation errors, action errors and cancelled submissions', async () => {
+ const options = { name: 'f', description: 'x' };
+ await expect(
+ runFormTool(
+ createFormAgentTool(
+ options,
+ { title: '' },
+ formHost({}, { status: 'invalid', errors: { title: 'Required', slug: 'Taken' } }),
+ ),
+ {},
+ ),
+ ).rejects.toThrow('The form was not submitted. title: Required; slug: Taken');
+ await expect(
+ runFormTool(
+ createFormAgentTool(
+ options,
+ {},
+ formHost(
+ {},
+ {
+ status: 'error',
+ error: new VoidActionError({
+ body: null,
+ status: 409,
+ statusText: 'Conflict',
+ url: '/',
+ }),
+ },
+ ),
+ ),
+ {},
+ ),
+ ).rejects.toThrow('Action failed with 409 Conflict');
+ await expect(
+ runFormTool(createFormAgentTool(options, {}, formHost({}, { status: 'cancelled' })), {}),
+ ).rejects.toThrow('The submission was cancelled.');
+ });
+
+ it('rejects a call while the form is submitting', async () => {
+ const host = { ...formHost({}), isPending: () => true };
+ await expect(
+ runFormTool(createFormAgentTool({ name: 'f', description: 'x' }, {}, host), {}),
+ ).rejects.toThrow('The form is already being submitted.');
+ });
+});
+
+describe('registerNavigateTool', () => {
+ beforeEach(stubModelContext);
+
+ it('opens a page that matches a route', async () => {
+ const visit = vi.fn((url: string) => {
+ window.location.pathname = url.split('?')[0] ?? url;
+ return Promise.resolve({});
+ });
+ const matchRoute = (path: string) =>
+ path === '/' ? 'index' : /^\/users\/[^/]+$/.test(path) ? 'users/[id]' : null;
+ registerNavigateTool({
+ router: { visit } as unknown as VoidRouter,
+ pages: [{ path: '/', title: 'Home' }, { path: '/users/[id]' }],
+ matchPage: (pathname) => matchRoute(pathname) !== null,
+ });
+ await flush();
+ expect(tool('navigate')).toMatchObject({
+ annotations: { readOnlyHint: true },
+ inputSchema: {
+ properties: {
+ path: { description: expect.stringContaining('Pages: / (Home), /users/[id]') },
+ },
+ required: ['path'],
+ },
+ });
+ await expect(call('navigate', { path: '/users/42?tab=posts' })).resolves.toEqual(
+ ok('{"url":"/users/42","title":"Page"}'),
+ );
+ expect(visit).toHaveBeenCalledWith('/users/42?tab=posts');
+
+ for (const path of ['/missing', '//evil.test/', 'https://evil.test/', 42]) {
+ await expect(call('navigate', { path })).resolves.toEqual(
+ failed(expect.stringMatching(/^No page matches/)),
+ );
+ }
+ expect(visit).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/webmcp/tsconfig.json b/packages/webmcp/tsconfig.json
new file mode 100644
index 0000000000..1eb72c2113
--- /dev/null
+++ b/packages/webmcp/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "rootDir": "../..",
+ "noEmit": true,
+ "target": "ES2022",
+ "lib": ["ES2022", "DOM"],
+ "types": ["node"],
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "strict": true,
+ "noUnusedLocals": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "outDir": "dist",
+ "declaration": true,
+ "isolatedDeclarations": true,
+ "allowImportingTsExtensions": true
+ },
+ "include": ["src", "test"]
+}
diff --git a/packages/webmcp/vite.config.ts b/packages/webmcp/vite.config.ts
new file mode 100644
index 0000000000..6e35584dc4
--- /dev/null
+++ b/packages/webmcp/vite.config.ts
@@ -0,0 +1,19 @@
+import { defineConfig } from 'vite-plus';
+
+export default defineConfig({
+ pack: {
+ entry: [
+ 'src/index.ts',
+ 'src/plugin.ts',
+ 'src/client.ts',
+ 'src/react.ts',
+ 'src/vue.ts',
+ 'src/svelte.ts',
+ 'src/solid.ts',
+ ],
+ format: 'esm',
+ dts: true,
+ clean: true,
+ deps: { neverBundle: ['vite', 'void', 'react', 'vue', 'svelte', 'solid-js'] },
+ },
+});
diff --git a/playground/react-pages/package.json b/playground/react-pages/package.json
index d314c52e80..a8f9e0e90f 100644
--- a/playground/react-pages/package.json
+++ b/playground/react-pages/package.json
@@ -18,6 +18,7 @@
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@void/react": "workspace:*",
+ "@void/webmcp": "workspace:*",
"tsrs": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
diff --git a/playground/react-pages/pages/users/index.tsx b/playground/react-pages/pages/users/index.tsx
index 158e16e85b..7c5d4859b6 100644
--- a/playground/react-pages/pages/users/index.tsx
+++ b/playground/react-pages/pages/users/index.tsx
@@ -1,4 +1,5 @@
import { Link, Form, useForm } from '@void/react';
+import { useAgentTool, useFormTool } from '@void/webmcp/react';
import { useFormStatus } from 'react-dom';
import type { Props } from './index.server.ts';
@@ -12,9 +13,17 @@ function SubmitButton() {
}
export default function UsersPage({ users }: Props) {
- const form = useForm('/users', {
- name: '',
- email: '',
+ const form = useForm('/users', { name: '', email: '' });
+ useFormTool(form, {
+ name: 'add_user',
+ description: 'Add a person to the user directory. Use when the user asks to add someone.',
+ });
+ useAgentTool({
+ name: 'list_users',
+ description:
+ 'List the people in the user directory with their ids. Use to find a user before opening their page.',
+ annotations: { readOnlyHint: true },
+ execute: () => users,
});
return (
diff --git a/playground/react-pages/vite.config.ts b/playground/react-pages/vite.config.ts
index de06ddc1e1..21131aae7a 100644
--- a/playground/react-pages/vite.config.ts
+++ b/playground/react-pages/vite.config.ts
@@ -1,9 +1,10 @@
import { voidReact } from '@void/react/plugin';
+import { voidWebMcp } from '@void/webmcp/plugin';
import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- plugins: [voidPlugin(), voidReact()],
+ plugins: [voidPlugin(), voidReact(), voidWebMcp()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot', 'react-dom', 'react/jsx-dev-runtime'] },
});
diff --git a/playground/solid-pages/package.json b/playground/solid-pages/package.json
index 4aada9edd4..b2b891bea8 100644
--- a/playground/solid-pages/package.json
+++ b/playground/solid-pages/package.json
@@ -15,6 +15,7 @@
},
"devDependencies": {
"@void/solid": "workspace:*",
+ "@void/webmcp": "workspace:*",
"tsrs": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
diff --git a/playground/solid-pages/pages/users/index.tsx b/playground/solid-pages/pages/users/index.tsx
index 301975cc4a..f00b6a281c 100644
--- a/playground/solid-pages/pages/users/index.tsx
+++ b/playground/solid-pages/pages/users/index.tsx
@@ -1,11 +1,20 @@
import { Link, Form, useForm } from '@void/solid';
+import { useAgentTool, useFormTool } from '@void/webmcp/solid';
import { For, Show } from 'solid-js';
import type { Props } from './index.server.ts';
export default function UsersPage(props: Props) {
- const form = useForm('/users', {
- name: '',
- email: '',
+ const form = useForm('/users', { name: '', email: '' });
+ useFormTool(form, {
+ name: 'add_user',
+ description: 'Add a person to the user directory. Use when the user asks to add someone.',
+ });
+ useAgentTool({
+ name: 'list_users',
+ description:
+ 'List the people in the user directory with their ids. Use to find a user before opening their page.',
+ annotations: { readOnlyHint: true },
+ execute: () => props.users,
});
return (
diff --git a/playground/solid-pages/vite.config.ts b/playground/solid-pages/vite.config.ts
index bd458d2565..64ea6a66be 100644
--- a/playground/solid-pages/vite.config.ts
+++ b/playground/solid-pages/vite.config.ts
@@ -1,9 +1,10 @@
import { voidSolid } from '@void/solid/plugin';
+import { voidWebMcp } from '@void/webmcp/plugin';
import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- plugins: [voidPlugin(), voidSolid()],
+ plugins: [voidPlugin(), voidSolid(), voidWebMcp()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot'] },
});
diff --git a/playground/svelte-pages/package.json b/playground/svelte-pages/package.json
index 208922f515..6639d86e07 100644
--- a/playground/svelte-pages/package.json
+++ b/playground/svelte-pages/package.json
@@ -15,6 +15,7 @@
},
"devDependencies": {
"@void/svelte": "workspace:*",
+ "@void/webmcp": "workspace:*",
"tsrs": "catalog:",
"typescript": "catalog:",
"vite": "catalog:",
diff --git a/playground/svelte-pages/pages/users/index.svelte b/playground/svelte-pages/pages/users/index.svelte
index d195635349..3fbc9f8425 100644
--- a/playground/svelte-pages/pages/users/index.svelte
+++ b/playground/svelte-pages/pages/users/index.svelte
@@ -1,12 +1,21 @@
diff --git a/playground/vue-pages/vite.config.ts b/playground/vue-pages/vite.config.ts
index 39ec3e1abe..d557743b63 100644
--- a/playground/vue-pages/vite.config.ts
+++ b/playground/vue-pages/vite.config.ts
@@ -1,9 +1,10 @@
import { voidVue } from '@void/vue/plugin';
+import { voidWebMcp } from '@void/webmcp/plugin';
import { defineConfig } from 'vite-plus';
import { voidPlugin } from 'void';
export default defineConfig({
- plugins: [voidPlugin(), voidVue()],
+ plugins: [voidPlugin(), voidVue(), voidWebMcp()],
// stabilize dev server start for tests
optimizeDeps: { include: ['valibot'] },
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 65ebe33fc7..113cd42128 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1026,6 +1026,51 @@ importers:
specifier: 'catalog:'
version: 3.5.45(typescript@7.0.2)
+ packages/webmcp:
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 26.6.6
+ '@types/react':
+ specifier: ^19.3.0
+ version: 19.3.0
+ '@types/react-dom':
+ specifier: ^19.3.0
+ version: 19.3.0(@types/react@19.3.0)
+ happy-dom:
+ specifier: 'catalog:'
+ version: 21.0.4
+ react:
+ specifier: 'catalog:'
+ version: 19.3.1
+ react-dom:
+ specifier: 'catalog:'
+ version: 19.3.1(react@19.3.1)
+ solid-js:
+ specifier: 'catalog:'
+ version: 1.9.19
+ svelte:
+ specifier: 'catalog:'
+ version: 5.57.3
+ tsrs:
+ specifier: 'catalog:'
+ version: 7.1.0-beta.tsrs2
+ vite:
+ specifier: 'catalog:'
+ version: '@voidzero-dev/vite-plus-core@8.3.8000(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.104.1)(sass@1.104.1)(terser@5.51.2)(tsx@4.23.15)(typescript@7.0.2)(yaml@2.9.1)'
+ vite-plus:
+ specifier: 'catalog:'
+ version: 1.7.0(@astrojs/compiler-rs@0.5.3)(@types/node@26.6.6)(@vitest/browser-preview@5.1.0)(@vitest/ui@5.1.0)(@voidzero-dev/vite-plus-core@8.3.8000(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.104.1)(sass@1.104.1)(terser@5.51.2)(tsx@4.23.15)(typescript@7.0.2)(yaml@2.9.1))(esbuild@0.28.2)(happy-dom@21.0.4)(jiti@2.7.0)(playwright@1.65.1)(sass-embedded@1.104.1)(sass@1.104.1)(svelte@5.57.3)(terser@5.51.2)(tsx@4.23.15)(typescript@7.0.2)(vitest@5.1.0)(yaml@2.9.1)
+ void:
+ specifier: workspace:*
+ version: link:../void
+ vue:
+ specifier: 'catalog:'
+ version: 3.5.45(typescript@7.0.2)
+ zod:
+ specifier: ^4.6.7
+ version: 4.6.7
+
platform:
devDependencies:
'@void/platform':
@@ -1807,6 +1852,9 @@ importers:
'@void/react':
specifier: workspace:*
version: link:../../packages/react
+ '@void/webmcp':
+ specifier: workspace:*
+ version: link:../../packages/webmcp
tsrs:
specifier: 'catalog:'
version: 7.1.0-beta.tsrs2
@@ -1906,6 +1954,9 @@ importers:
'@void/solid':
specifier: workspace:*
version: link:../../packages/solid
+ '@void/webmcp':
+ specifier: workspace:*
+ version: link:../../packages/webmcp
tsrs:
specifier: 'catalog:'
version: 7.1.0-beta.tsrs2
@@ -2033,6 +2084,9 @@ importers:
'@void/svelte':
specifier: workspace:*
version: link:../../packages/svelte
+ '@void/webmcp':
+ specifier: workspace:*
+ version: link:../../packages/webmcp
tsrs:
specifier: 'catalog:'
version: 7.1.0-beta.tsrs2
@@ -2203,6 +2257,9 @@ importers:
'@void/vue':
specifier: workspace:*
version: link:../../packages/vue
+ '@void/webmcp':
+ specifier: workspace:*
+ version: link:../../packages/webmcp
tsrs:
specifier: 'catalog:'
version: 7.1.0-beta.tsrs2
diff --git a/test/pages-browser.ts b/test/pages-browser.ts
index ff0897c7f8..5854b36df7 100644
--- a/test/pages-browser.ts
+++ b/test/pages-browser.ts
@@ -8,7 +8,10 @@ export function launchPagesBrowser(): Promise {
return webkit.launch();
}
if (browser === 'chromium') {
- return chromium.launch({ args: ['--disable-features=BackForwardCache'] });
+ // WebMCP is behind a flag in Chromium.
+ return chromium.launch({
+ args: ['--disable-features=BackForwardCache', '--enable-features=WebMCP'],
+ });
}
throw new Error(`Unsupported VOID_TEST_BROWSER: ${browser}`);
}
diff --git a/test/pages-client-contract.ts b/test/pages-client-contract.ts
index bd4e971a9f..511119a2d1 100644
--- a/test/pages-client-contract.ts
+++ b/test/pages-client-contract.ts
@@ -6,6 +6,7 @@ import {
deserializePageData,
serializePageData,
} from '../packages/void/src/pages/serialize.ts';
+import { registerSharedWebMcpTests } from './pages-webmcp-contract.ts';
type TestWindow = Window & {
__SPA_MARKER?: boolean;
@@ -488,6 +489,8 @@ export function registerSharedClientTests({
return;
}
+ registerSharedWebMcpTests({ getBase, newPage, waitForHydration });
+
it('restores document scroll after reload', async ({ expect }) => {
const page = await newPage();
try {
diff --git a/test/pages-webmcp-contract.ts b/test/pages-webmcp-contract.ts
new file mode 100644
index 0000000000..f317f43c73
--- /dev/null
+++ b/test/pages-webmcp-contract.ts
@@ -0,0 +1,143 @@
+import type { Page } from 'playwright';
+import { expect, it } from 'vite-plus/test';
+
+type ToolSummary = {
+ name: string;
+ description: string;
+ inputSchema: unknown;
+ annotations: unknown;
+};
+
+type ToolCall = { ok: true; result: unknown } | { ok: false; error: string };
+
+type TestModelContext = {
+ getTools(): Promise>;
+ executeTool(tool: ToolSummary, input: object): Promise;
+};
+
+async function waitForToolNames(page: Page, expected: ReadonlyArray, present = true) {
+ await page.waitForFunction(
+ async ({ expected, present }) => {
+ const context = (document as unknown as { modelContext: TestModelContext }).modelContext;
+ const names = new Set((await context.getTools()).map((tool) => tool.name));
+ return expected.every((name) => names.has(name) === present);
+ },
+ { expected, present },
+ { polling: 50 },
+ );
+}
+
+function listTools(page: Page): Promise> {
+ return page.evaluate(async () => {
+ const context = (document as unknown as { modelContext: TestModelContext }).modelContext;
+ return (await context.getTools()).map(({ name, description, inputSchema, annotations }) => ({
+ name,
+ description,
+ inputSchema,
+ annotations,
+ }));
+ });
+}
+
+function callTool(page: Page, name: string, input: object = {}): Promise {
+ return page.evaluate(
+ async ({ name, input }) => {
+ const context = (document as unknown as { modelContext: TestModelContext }).modelContext;
+ const tool = (await context.getTools()).find((candidate) => candidate.name === name);
+ if (!tool) {
+ return { ok: false as const, error: `Tool "${name}" is not registered.` };
+ }
+ const response = JSON.parse(await context.executeTool(tool, input)) as {
+ content: Array<{ type: string; text?: string }>;
+ isError?: boolean;
+ };
+ const text = response.content
+ .map((item) => (item.type === 'text' ? (item.text ?? '') : ''))
+ .join('');
+ if (response.isError) {
+ return { ok: false as const, error: text };
+ }
+ try {
+ return { ok: true as const, result: JSON.parse(text) as unknown };
+ } catch {
+ return { ok: true as const, result: text };
+ }
+ },
+ { name, input },
+ );
+}
+
+/**
+ * The users page of each Pages playground offers `add_user` (`useFormTool()`), `list_users`
+ * (`useAgentTool()`) and the `navigate` tool from `voidWebMcp()`. Only Chromium has WebMCP.
+ */
+export function registerSharedWebMcpTests({
+ getBase,
+ newPage,
+ waitForHydration,
+}: {
+ getBase: () => string;
+ newPage: () => Promise;
+ waitForHydration: (page: Page) => Promise;
+}): void {
+ it('offers forms, components and pages as WebMCP tools', { concurrent: false }, async () => {
+ const page = await newPage();
+ const base = getBase();
+ const id = crypto.randomUUID();
+ const name = `Agent Erin ${id}`;
+ try {
+ await page.goto(base + '/users');
+ await waitForHydration(page);
+ const supported = await page.evaluate(() => 'modelContext' in document);
+ if ((process.env.VOID_TEST_BROWSER ?? 'chromium') === 'chromium') {
+ expect(supported).toBe(true);
+ }
+ if (!supported) {
+ return;
+ }
+ await waitForToolNames(page, ['add_user', 'list_users', 'navigate']);
+
+ const tools = await listTools(page);
+ expect(tools.find((tool) => tool.name === 'add_user')).toMatchObject({
+ inputSchema: {
+ type: 'object',
+ properties: { name: { type: 'string' }, email: { type: 'string' } },
+ },
+ });
+ expect(tools.find((tool) => tool.name === 'navigate')).toMatchObject({
+ annotations: { readOnlyHint: true },
+ });
+ const navigate = tools.find((tool) => tool.name === 'navigate');
+ expect(JSON.stringify(navigate?.inputSchema)).toContain('/users/[id]');
+
+ const listed = await callTool(page, 'list_users');
+ expect(listed.ok && listed.result).toContainEqual({
+ id: 1,
+ name: 'Alice',
+ email: 'alice@example.com',
+ });
+
+ const invalid = await callTool(page, 'add_user', { name: '', email: '' });
+ expect(invalid.ok).toBe(false);
+ expect(!invalid.ok && invalid.error).toContain('Name is required');
+ await page.waitForFunction(() => document.body.textContent?.includes('Email is required'));
+
+ const added = await callTool(page, 'add_user', { name, email: `erin-${id}@example.com` });
+ expect(added).toEqual({ ok: true, result: { status: 'submitted', url: '/users' } });
+ await page.waitForFunction((value) => document.body.textContent?.includes(value), name);
+ expect(await page.textContent('body')).not.toContain('Name is required');
+
+ const opened = await callTool(page, 'navigate', { path: '/users/1' });
+ expect(opened.ok && opened.result).toMatchObject({ url: '/users/1' });
+ expect(page.url()).toBe(base + '/users/1');
+ await page.getByRole('heading', { name: 'Alice' }).waitFor();
+ await waitForToolNames(page, ['add_user', 'list_users'], false);
+
+ const outside = await callTool(page, 'navigate', { path: 'https://example.com/' });
+ expect(outside.ok).toBe(false);
+ expect(!outside.ok && outside.error).toContain('No page matches "https://example.com/"');
+ } finally {
+ await page.context().close();
+ }
+ });
+}