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, `