@xstate/webmcp 0.0.0-stage → 0.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +273 -2
- package/dist/declarations/src/descriptors.d.ts +17 -0
- package/dist/declarations/src/index.d.ts +4 -0
- package/dist/declarations/src/mock.d.ts +20 -0
- package/dist/declarations/src/schema.d.ts +50 -0
- package/dist/declarations/src/webmcp.d.ts +190 -0
- package/dist/xstate-webmcp.d.ts +2 -0
- package/dist/xstate-webmcp.js +563 -0
- package/package.json +37 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2015 David Khourshid
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,274 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @xstate/webmcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Expose XState actors and `@xstate/store` stores as [WebMCP](https://webmachinelearning.github.io/webmcp/) tools. Each exposed event becomes a tool whose input is the event payload. Custom tools can send several events and wait for a result.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
`@xstate/webmcp` is available in the XState source repository. It has no npm release yet. To try it from source, follow the [TodoMVC workspace example](https://github.com/statelyai/xstate/blob/next/examples/todomvc-webmcp-react/README.md#run-it).
|
|
8
|
+
|
|
9
|
+
The package has no runtime dependencies. It works with any `xstate` actor or `@xstate/store` store.
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
<!-- createWebMCP API from src/webmcp.ts -->
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createStore } from '@xstate/store';
|
|
17
|
+
import { createWebMCP } from '@xstate/webmcp';
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
|
|
20
|
+
const todoStore = createStore({
|
|
21
|
+
schemas: {
|
|
22
|
+
events: {
|
|
23
|
+
'todo.add': z
|
|
24
|
+
.object({ title: z.string().min(1) })
|
|
25
|
+
.describe('Add a todo item.'),
|
|
26
|
+
'todo.remove': z
|
|
27
|
+
.object({ id: z.number() })
|
|
28
|
+
.describe('Remove a todo item by id.')
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
context: { nextId: 0, todos: [] as { id: number; title: string }[] },
|
|
32
|
+
on: {
|
|
33
|
+
'todo.add': (context, event) => ({
|
|
34
|
+
nextId: context.nextId + 1,
|
|
35
|
+
todos: [...context.todos, { id: context.nextId, title: event.title }]
|
|
36
|
+
}),
|
|
37
|
+
'todo.remove': (context, event) => ({
|
|
38
|
+
...context,
|
|
39
|
+
todos: context.todos.filter((todo) => todo.id !== event.id)
|
|
40
|
+
})
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const webMCP = createWebMCP(todoStore, { events: ['todo.*'] });
|
|
45
|
+
const registration = webMCP.register();
|
|
46
|
+
|
|
47
|
+
// Later, for example when the component unmounts:
|
|
48
|
+
registration.unregister();
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
This registers three tools with `document.modelContext`: `todo_add`, `todo_remove`, and a read-only `get_state` tool.
|
|
52
|
+
|
|
53
|
+
## Exposing events
|
|
54
|
+
|
|
55
|
+
The `events` option is required. It lists the events agents can send:
|
|
56
|
+
|
|
57
|
+
- An exact event type: `'todo.add'`
|
|
58
|
+
- A trailing wildcard: `'todo.*'` matches `todo` and every `todo.…` event
|
|
59
|
+
- `'*'` for every event that has a schema
|
|
60
|
+
|
|
61
|
+
Wildcards expand to one tool per event. They are never registered as tool names. Use `'*'` only when every event is safe for an agent to send.
|
|
62
|
+
|
|
63
|
+
Every exposed event needs an event schema in `schemas.events`. The schema validates tool input and becomes the tool's `inputSchema`.
|
|
64
|
+
|
|
65
|
+
- Schemas that implement [Standard JSON Schema](https://standardschema.dev/json-schema) (Zod 4, Valibot, ArkType) convert automatically. For other schemas, pass a `toJSONSchema` option.
|
|
66
|
+
- The tool description comes from the schema description. For machines, a transition `description` is used when the schema has none: first a transition for the exact event, then the most specific matching wildcard transition, such as `pointer.*`. An event with neither throws an error when you call `createWebMCP`.
|
|
67
|
+
- Input that fails the schema rejects the tool call with a `WebMCPInputError`, and no event is sent.
|
|
68
|
+
|
|
69
|
+
### Tool names
|
|
70
|
+
|
|
71
|
+
Event types stay as written in your machine or store. Tool names are derived from them by the `toolName` option, which defaults to `toToolName`. It replaces `.` and any other character outside `[a-zA-Z0-9_-]` with `_`, so `checkout.confirm` becomes the tool `checkout_confirm`. Model APIs that agents forward tools to commonly reject `.` in tool names.
|
|
72
|
+
|
|
73
|
+
Pass your own `toolName` to change the mapping for every event tool:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { createWebMCP, toToolName } from '@xstate/webmcp';
|
|
77
|
+
|
|
78
|
+
createWebMCP(todoStore, {
|
|
79
|
+
events: ['todo.*'],
|
|
80
|
+
toolName: (eventType) => `send_${toToolName(eventType)}`
|
|
81
|
+
});
|
|
82
|
+
// Tools: send_todo_add, send_todo_remove, get_state
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`toolName` receives the event schema as its second argument, so a name can depend on the schema:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { createWebMCP, toToolName } from '@xstate/webmcp';
|
|
89
|
+
|
|
90
|
+
createWebMCP(todoStore, {
|
|
91
|
+
events: ['todo.*'],
|
|
92
|
+
toolName: (eventType, schema) =>
|
|
93
|
+
schema === todoStore.schemas?.events?.['todo.add']
|
|
94
|
+
? 'add_todo'
|
|
95
|
+
: toToolName(eventType)
|
|
96
|
+
});
|
|
97
|
+
// Tools: add_todo, todo_remove, get_state
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`createWebMCP` throws if two tools end up with the same name, for example when both `todo.add` and `todo_add` are exposed.
|
|
101
|
+
|
|
102
|
+
### Overrides
|
|
103
|
+
|
|
104
|
+
Use `overrides` to change the name, title, description, or annotations of an event tool:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
createWebMCP(todoStore, {
|
|
108
|
+
events: ['todo.*'],
|
|
109
|
+
prefix: 'todos',
|
|
110
|
+
overrides: {
|
|
111
|
+
'todo.remove': {
|
|
112
|
+
name: 'delete',
|
|
113
|
+
annotations: { consequentialHint: true }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
// Tools: todos_todo_add, todos_delete, todos_get_state
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
An override `name` replaces the `toolName` result and is used as written. `prefix` is prepended to every tool name, including the state tool and custom tools, as `${prefix}_${name}`. WebMCP allows tool names of 1 to 128 characters of ASCII letters, digits, `_`, `-`, or `.`.
|
|
121
|
+
|
|
122
|
+
## Tool results
|
|
123
|
+
|
|
124
|
+
Event tools return `output(snapshot)` after the event is processed. The `get_state` tool returns the same value without sending anything.
|
|
125
|
+
|
|
126
|
+
By default, `output` returns `{ status, state, output }` and leaves out `context`. Pass `output` to choose what agents can read:
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
createWebMCP(todoStore, {
|
|
130
|
+
events: ['todo.*'],
|
|
131
|
+
output: (snapshot) => ({ todos: snapshot.context.todos })
|
|
132
|
+
});
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Results are serialized to JSON, so `output` must return JSON-serializable values.
|
|
136
|
+
|
|
137
|
+
Set `stateTool: false` to omit the `get_state` tool, or pass `{ name, title, description }` to configure it.
|
|
138
|
+
|
|
139
|
+
## Machines
|
|
140
|
+
|
|
141
|
+
For machine actors, event tools follow the current state. By default (`availability: 'state'`), a tool is registered only while an active state node has a transition for its event. When the state changes, the adapter registers and unregisters tools, and the browser fires a `toolchange` event. When the machine finishes, stops, or errors, every event tool is unregistered.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
import { createActor, createMachine } from 'xstate';
|
|
145
|
+
import { createWebMCP } from '@xstate/webmcp';
|
|
146
|
+
import { z } from 'zod';
|
|
147
|
+
|
|
148
|
+
const checkoutMachine = createMachine({
|
|
149
|
+
schemas: {
|
|
150
|
+
events: {
|
|
151
|
+
'cart.add': z
|
|
152
|
+
.object({ sku: z.string() })
|
|
153
|
+
.describe('Add an item to the cart.'),
|
|
154
|
+
'checkout.start': z.object({}).describe('Start checkout.'),
|
|
155
|
+
cancel: z.object({}).describe('Cancel checkout.')
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
context: { items: [] as string[] },
|
|
159
|
+
initial: 'shopping',
|
|
160
|
+
states: {
|
|
161
|
+
shopping: {
|
|
162
|
+
on: {
|
|
163
|
+
'cart.add': ({ context, event }) => ({
|
|
164
|
+
context: { items: [...context.items, event.sku] }
|
|
165
|
+
}),
|
|
166
|
+
'checkout.start': ({ context }) =>
|
|
167
|
+
context.items.length > 0 ? { target: 'checkout' } : undefined
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
checkout: {
|
|
171
|
+
on: { cancel: { target: 'shopping' } }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
const actor = createActor(checkoutMachine).start();
|
|
177
|
+
const webMCP = createWebMCP(actor, { events: '*' });
|
|
178
|
+
|
|
179
|
+
webMCP.register();
|
|
180
|
+
// Registered: cart_add, checkout_start, get_state
|
|
181
|
+
// After checkout_start: cancel, get_state
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Before an event tool sends its event, it checks `snapshot.can(event)` with the validated payload. If a guard rejects the event, the tool call rejects with an error that lists the tools the current state accepts.
|
|
185
|
+
|
|
186
|
+
Pass `availability: 'always'` to keep every event tool registered. The `snapshot.can(event)` check still runs.
|
|
187
|
+
|
|
188
|
+
## Custom tools
|
|
189
|
+
|
|
190
|
+
Use `tools` to define tools that send several events, run async logic, or wait for a state. The `tool` helper infers the input type from `input` and types `send`, `getSnapshot`, and `waitFor` from the actor or store:
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
const webMCP = createWebMCP(actor, {
|
|
194
|
+
events: [],
|
|
195
|
+
tools: ({ tool }) => ({
|
|
196
|
+
quickCheckout: tool({
|
|
197
|
+
description: 'Add the given items and start checkout.',
|
|
198
|
+
input: z.object({ skus: z.array(z.string()).min(1) }),
|
|
199
|
+
annotations: { consequentialHint: true },
|
|
200
|
+
async execute({ skus }, { send, getSnapshot, waitFor }) {
|
|
201
|
+
if (!getSnapshot().matches('shopping')) {
|
|
202
|
+
throw new Error('Checkout has already started.');
|
|
203
|
+
}
|
|
204
|
+
for (const sku of skus) {
|
|
205
|
+
send({ type: 'cart.add', sku });
|
|
206
|
+
}
|
|
207
|
+
send({ type: 'checkout.start' });
|
|
208
|
+
const snapshot = await waitFor((s) => s.matches('checkout'));
|
|
209
|
+
return { items: snapshot.context.items };
|
|
210
|
+
}
|
|
211
|
+
})
|
|
212
|
+
})
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
webMCP.register();
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
The second argument of `execute` contains:
|
|
219
|
+
|
|
220
|
+
| Property | Description |
|
|
221
|
+
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
222
|
+
| `send` | Sends an event to the actor or store. |
|
|
223
|
+
| `getSnapshot` | Returns the current snapshot. |
|
|
224
|
+
| `waitFor` | Resolves with the first snapshot that matches a predicate. Rejects if the target errors, finishes, or stops first, or after `timeout` ms. |
|
|
225
|
+
| `signal` | An `AbortSignal` that aborts when the agent cancels the call. `waitFor` uses it by default. |
|
|
226
|
+
| `target` | The actor or store. |
|
|
227
|
+
|
|
228
|
+
Custom tools are always registered, whatever the current state.
|
|
229
|
+
|
|
230
|
+
If the agent cancels a call before input validation finishes, the tool rejects without sending an event or running `execute`. After `execute` starts, cancellation is cooperative: check `signal` or pass it to async work.
|
|
231
|
+
|
|
232
|
+
## Registration
|
|
233
|
+
|
|
234
|
+
`register()` registers the available tools and returns a registration:
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
const controller = new AbortController();
|
|
238
|
+
const registration = webMCP.register({ signal: controller.signal });
|
|
239
|
+
|
|
240
|
+
await registration.ready; // initial tools registered
|
|
241
|
+
registration.status; // 'registered' | 'unregistered' | 'unsupported'
|
|
242
|
+
|
|
243
|
+
controller.abort(); // or registration.unregister()
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
| Option | Description |
|
|
247
|
+
| -------------- | ------------------------------------------------------------------------------------------------ |
|
|
248
|
+
| `modelContext` | The model context to register with. Defaults to `document.modelContext`, then `navigator.modelContext`. |
|
|
249
|
+
| `signal` | Unregisters every tool when aborted. |
|
|
250
|
+
| `exposedTo` | Origins the tools are exposed to. |
|
|
251
|
+
| `onError` | Called when a later registration fails, such as after a state change. Defaults to `reportError`. |
|
|
252
|
+
|
|
253
|
+
When no model context exists, `status` is `'unsupported'` and nothing is registered. `ready` rejects if any initial registration fails, for example because another script registered a tool with the same name. The tools that did register are then removed and `status` becomes `'unregistered'`, so you can call `register()` again.
|
|
254
|
+
|
|
255
|
+
## Using the tools without WebMCP
|
|
256
|
+
|
|
257
|
+
`webMCP.tools` lists every tool as plain objects with `name`, `description`, `inputSchema`, and `execute`. `webMCP.getAvailableTools()` lists the tools the current state accepts. You can pass these to other tool-calling APIs, such as an MCP server or an LLM SDK.
|
|
258
|
+
|
|
259
|
+
## Testing
|
|
260
|
+
|
|
261
|
+
`createMockModelContext()` returns an in-memory model context that follows the WebMCP registration rules:
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import { createMockModelContext, createWebMCP } from '@xstate/webmcp';
|
|
265
|
+
|
|
266
|
+
const modelContext = createMockModelContext();
|
|
267
|
+
await createWebMCP(todoStore, { events: ['todo.*'] }).register({ modelContext })
|
|
268
|
+
.ready;
|
|
269
|
+
|
|
270
|
+
modelContext.getToolNames(); // ['todo_add', 'todo_remove', 'get_state']
|
|
271
|
+
await modelContext.executeTool('todo_add', { title: 'Buy milk' });
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
`executeTool` serializes the result to JSON and parses it again, like a browser does.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
type PartialEventDescriptor<TEventType extends string> = TEventType extends `${infer TLeading}.${infer TTail}` ? `${TLeading}.*` | `${TLeading}.${PartialEventDescriptor<TTail>}` : never;
|
|
2
|
+
/**
|
|
3
|
+
* An exact event type, `'*'`, or a trailing-token wildcard such as `'todo.*'`.
|
|
4
|
+
*/
|
|
5
|
+
export type EventDescriptor<TEventType extends string> = TEventType | PartialEventDescriptor<TEventType> | '*';
|
|
6
|
+
export declare function isWildcard(descriptor: string): boolean;
|
|
7
|
+
/**
|
|
8
|
+
* Returns `true` if `eventType` matches an exact, `'*'`, or trailing-token
|
|
9
|
+
* wildcard descriptor. `'todo.*'` matches `'todo'` and every `'todo.…'` event.
|
|
10
|
+
*/
|
|
11
|
+
export declare function matchesEventDescriptor(eventType: string, descriptor: string): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Expands descriptors against the known event types. Throws for an exact
|
|
14
|
+
* descriptor that names an unknown event type.
|
|
15
|
+
*/
|
|
16
|
+
export declare function resolveEventTypes(eventTypes: readonly string[], descriptors: readonly string[]): string[];
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { type EventDescriptor, matchesEventDescriptor } from "./descriptors.js";
|
|
2
|
+
export { type JSONSchema, type StandardSchemaV1, WebMCPInputError } from "./schema.js";
|
|
3
|
+
export { createWebMCP, toToolName, type WebMCP, type WebMCPEventToolOverride, type WebMCPEventType, type WebMCPModelContext, type WebMCPOptions, type WebMCPRegisterOptions, type WebMCPRegisterToolOptions, type WebMCPRegistration, type WebMCPRegistrationStatus, type WebMCPStateToolOptions, type WebMCPTarget, type WebMCPTool, type WebMCPToolAnnotations, type WebMCPToolConfig, type WebMCPToolContext, type WebMCPToolDefinition, type WebMCPToolExecuteOptions, type WebMCPToolHelpers, type WebMCPWaitForOptions } from "./webmcp.js";
|
|
4
|
+
export { createMockModelContext, type MockModelContext } from "./mock.js";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { WebMCPModelContext, WebMCPTool } from "./webmcp.js";
|
|
2
|
+
export interface MockModelContext extends WebMCPModelContext {
|
|
3
|
+
/** Currently registered tools, keyed by name. */
|
|
4
|
+
readonly tools: ReadonlyMap<string, WebMCPTool>;
|
|
5
|
+
/** Names of the currently registered tools, in registration order. */
|
|
6
|
+
getToolNames(): string[];
|
|
7
|
+
/**
|
|
8
|
+
* Runs a registered tool and returns its result after a JSON round trip, the
|
|
9
|
+
* way a browser serializes tool results.
|
|
10
|
+
*/
|
|
11
|
+
executeTool(name: string, input?: Record<string, unknown>, options?: {
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
}): Promise<unknown>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Creates an in-memory model context for tests. It follows the WebMCP
|
|
17
|
+
* registration rules: duplicate names reject, and aborting the registration
|
|
18
|
+
* signal unregisters the tool.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createMockModelContext(): MockModelContext;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** The Standard Schema interface. See https://standardschema.dev */
|
|
2
|
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
3
|
+
readonly '~standard': StandardSchemaV1.Props<Input, Output>;
|
|
4
|
+
}
|
|
5
|
+
export declare namespace StandardSchemaV1 {
|
|
6
|
+
interface Props<Input = unknown, Output = Input> {
|
|
7
|
+
readonly version: 1;
|
|
8
|
+
readonly vendor: string;
|
|
9
|
+
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
|
|
10
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
11
|
+
}
|
|
12
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
13
|
+
interface SuccessResult<Output> {
|
|
14
|
+
readonly value: Output;
|
|
15
|
+
readonly issues?: undefined;
|
|
16
|
+
}
|
|
17
|
+
interface FailureResult {
|
|
18
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
19
|
+
}
|
|
20
|
+
interface Issue {
|
|
21
|
+
readonly message: string;
|
|
22
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
23
|
+
}
|
|
24
|
+
interface PathSegment {
|
|
25
|
+
readonly key: PropertyKey;
|
|
26
|
+
}
|
|
27
|
+
interface Types<Input = unknown, Output = Input> {
|
|
28
|
+
readonly input: Input;
|
|
29
|
+
readonly output: Output;
|
|
30
|
+
}
|
|
31
|
+
type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
|
|
32
|
+
type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
|
|
33
|
+
}
|
|
34
|
+
/** A JSON Schema object. */
|
|
35
|
+
export type JSONSchema = Record<string, unknown>;
|
|
36
|
+
/**
|
|
37
|
+
* Converts a schema to an input JSON Schema, using `toJSONSchema` when given
|
|
38
|
+
* and Standard JSON Schema otherwise.
|
|
39
|
+
*/
|
|
40
|
+
export declare function getInputJSONSchema(schema: StandardSchemaV1, toJSONSchema: ((schema: StandardSchemaV1) => JSONSchema) | undefined, label: string): JSONSchema;
|
|
41
|
+
/** Thrown when tool input fails its schema. */
|
|
42
|
+
export declare class WebMCPInputError extends Error {
|
|
43
|
+
readonly toolName: string;
|
|
44
|
+
readonly issues: ReadonlyArray<StandardSchemaV1.Issue> | undefined;
|
|
45
|
+
constructor(toolName: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>);
|
|
46
|
+
}
|
|
47
|
+
/** Validates tool input and returns the schema output unchanged. */
|
|
48
|
+
export declare function validateInput(schema: StandardSchemaV1 | undefined, toolName: string, input: unknown): Promise<unknown>;
|
|
49
|
+
/** Validates an event payload, which must be an object to spread into the event. */
|
|
50
|
+
export declare function validateEventPayload(schema: StandardSchemaV1 | undefined, toolName: string, input: unknown): Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { type EventDescriptor } from "./descriptors.js";
|
|
2
|
+
import { type JSONSchema, type StandardSchemaV1 } from "./schema.js";
|
|
3
|
+
/** Hints that describe a tool's behavior to the agent. */
|
|
4
|
+
export interface WebMCPToolAnnotations {
|
|
5
|
+
/** The tool does not change state. */
|
|
6
|
+
readOnlyHint?: boolean;
|
|
7
|
+
/** The tool returns content the page does not control. */
|
|
8
|
+
untrustedContentHint?: boolean;
|
|
9
|
+
/** The tool has consequences the user may want to confirm. */
|
|
10
|
+
consequentialHint?: boolean;
|
|
11
|
+
/** The tool is for debugging only. */
|
|
12
|
+
debugging?: boolean;
|
|
13
|
+
}
|
|
14
|
+
export interface WebMCPToolExecuteOptions {
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
}
|
|
17
|
+
/** A tool in the shape `document.modelContext.registerTool(...)` accepts. */
|
|
18
|
+
export interface WebMCPTool {
|
|
19
|
+
name: string;
|
|
20
|
+
title?: string;
|
|
21
|
+
description: string;
|
|
22
|
+
inputSchema: JSONSchema;
|
|
23
|
+
annotations?: WebMCPToolAnnotations;
|
|
24
|
+
execute: (input: Record<string, unknown>, options?: WebMCPToolExecuteOptions) => Promise<unknown>;
|
|
25
|
+
}
|
|
26
|
+
export interface WebMCPRegisterToolOptions {
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
exposedTo?: string[];
|
|
29
|
+
}
|
|
30
|
+
/** The subset of the WebMCP `ModelContext` interface that tools register with. */
|
|
31
|
+
export interface WebMCPModelContext {
|
|
32
|
+
registerTool(tool: WebMCPTool, options?: WebMCPRegisterToolOptions): Promise<void> | void;
|
|
33
|
+
}
|
|
34
|
+
interface TargetSubscription {
|
|
35
|
+
unsubscribe(): void;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Anything that can receive events and report snapshots: an XState actor or an
|
|
39
|
+
* `@xstate/store` store.
|
|
40
|
+
*/
|
|
41
|
+
export interface WebMCPTarget {
|
|
42
|
+
send: (event: any) => void;
|
|
43
|
+
getSnapshot: () => any;
|
|
44
|
+
subscribe: (next: (snapshot: any) => void, error?: (error: any) => void, complete?: () => void) => TargetSubscription;
|
|
45
|
+
}
|
|
46
|
+
type EventOf<TTarget extends WebMCPTarget> = Extract<Parameters<TTarget['send']>[0], {
|
|
47
|
+
type: string;
|
|
48
|
+
}>;
|
|
49
|
+
/** Event types of `TTarget` that can be exposed as tools. */
|
|
50
|
+
export type WebMCPEventType<TTarget extends WebMCPTarget> = Exclude<EventOf<TTarget>['type'], `xstate.${string}`>;
|
|
51
|
+
type SnapshotOf<TTarget extends WebMCPTarget> = ReturnType<TTarget['getSnapshot']>;
|
|
52
|
+
export interface WebMCPWaitForOptions {
|
|
53
|
+
/** Rejects when aborted. Defaults to the tool call's signal. */
|
|
54
|
+
signal?: AbortSignal;
|
|
55
|
+
/** Rejects after this many milliseconds. */
|
|
56
|
+
timeout?: number;
|
|
57
|
+
}
|
|
58
|
+
/** Passed to the `execute` function of a custom tool. */
|
|
59
|
+
export interface WebMCPToolContext<TTarget extends WebMCPTarget> {
|
|
60
|
+
/** The actor or store the tools were created for. */
|
|
61
|
+
target: TTarget;
|
|
62
|
+
send: (event: EventOf<TTarget>) => void;
|
|
63
|
+
getSnapshot: () => SnapshotOf<TTarget>;
|
|
64
|
+
/**
|
|
65
|
+
* Resolves with the first snapshot (including the current one) that satisfies
|
|
66
|
+
* `predicate`. Rejects if the target errors, finishes or stops first.
|
|
67
|
+
*/
|
|
68
|
+
waitFor: (predicate: (snapshot: SnapshotOf<TTarget>) => boolean, options?: WebMCPWaitForOptions) => Promise<SnapshotOf<TTarget>>;
|
|
69
|
+
/** Aborted when the agent cancels the tool call. */
|
|
70
|
+
signal: AbortSignal;
|
|
71
|
+
}
|
|
72
|
+
type ToolInput<TInput extends StandardSchemaV1 | undefined> = TInput extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TInput> : Record<string, never>;
|
|
73
|
+
export interface WebMCPToolConfig<TTarget extends WebMCPTarget, TInput extends StandardSchemaV1 | undefined, TResult> {
|
|
74
|
+
title?: string;
|
|
75
|
+
description: string;
|
|
76
|
+
/** Validates the tool input. Also converted to the tool's input JSON Schema. */
|
|
77
|
+
input?: TInput;
|
|
78
|
+
annotations?: WebMCPToolAnnotations;
|
|
79
|
+
execute: (input: ToolInput<TInput>, context: WebMCPToolContext<TTarget>) => TResult | Promise<TResult>;
|
|
80
|
+
}
|
|
81
|
+
declare const toolDefinitionBrand: unique symbol;
|
|
82
|
+
/** A custom tool created with the `tool` helper. */
|
|
83
|
+
export interface WebMCPToolDefinition {
|
|
84
|
+
readonly [toolDefinitionBrand]: true;
|
|
85
|
+
}
|
|
86
|
+
export interface WebMCPToolHelpers<TTarget extends WebMCPTarget> {
|
|
87
|
+
tool: <TInput extends StandardSchemaV1 | undefined = undefined, TResult = unknown>(config: WebMCPToolConfig<TTarget, TInput, TResult>) => WebMCPToolDefinition;
|
|
88
|
+
}
|
|
89
|
+
export interface WebMCPEventToolOverride {
|
|
90
|
+
/** Tool name before the prefix is applied, used as written. */
|
|
91
|
+
name?: string;
|
|
92
|
+
title?: string;
|
|
93
|
+
/** Defaults to the event schema's description. */
|
|
94
|
+
description?: string;
|
|
95
|
+
annotations?: WebMCPToolAnnotations;
|
|
96
|
+
}
|
|
97
|
+
export interface WebMCPStateToolOptions {
|
|
98
|
+
/** Tool name before the prefix is applied. Defaults to `get_state`. */
|
|
99
|
+
name?: string;
|
|
100
|
+
title?: string;
|
|
101
|
+
description?: string;
|
|
102
|
+
}
|
|
103
|
+
export interface WebMCPOptions<TTarget extends WebMCPTarget> {
|
|
104
|
+
/**
|
|
105
|
+
* Events to expose as tools: exact event types, `'*'`, or trailing-token
|
|
106
|
+
* wildcards such as `'todo.*'`. Each exposed event needs an event schema.
|
|
107
|
+
*/
|
|
108
|
+
events: EventDescriptor<WebMCPEventType<TTarget>> | readonly EventDescriptor<WebMCPEventType<TTarget>>[];
|
|
109
|
+
/**
|
|
110
|
+
* Maps an event type and its event schema to the tool name. Defaults to
|
|
111
|
+
* `toToolName`, which turns `'checkout.confirm'` into `'checkout_confirm'`.
|
|
112
|
+
*/
|
|
113
|
+
toolName?: (eventType: WebMCPEventType<TTarget>, schema: StandardSchemaV1) => string;
|
|
114
|
+
/** Prepended to every tool name as `${prefix}_${name}`. */
|
|
115
|
+
prefix?: string;
|
|
116
|
+
/** Per-event tool names, descriptions and annotations. */
|
|
117
|
+
overrides?: {
|
|
118
|
+
[K in WebMCPEventType<TTarget>]?: WebMCPEventToolOverride;
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* Converts a snapshot to the value that event tools and the state tool
|
|
122
|
+
* return. Defaults to `{ status, state, output }` (no context).
|
|
123
|
+
*/
|
|
124
|
+
output?: (snapshot: SnapshotOf<TTarget>) => unknown;
|
|
125
|
+
/**
|
|
126
|
+
* For machine actors, `'state'` (default) registers an event tool only while
|
|
127
|
+
* the current state handles that event. `'always'` keeps every event tool
|
|
128
|
+
* registered. Has no effect on stores.
|
|
129
|
+
*/
|
|
130
|
+
availability?: 'state' | 'always';
|
|
131
|
+
/** Adds a read-only tool that returns `output(snapshot)`. Defaults to `true`. */
|
|
132
|
+
stateTool?: boolean | WebMCPStateToolOptions;
|
|
133
|
+
/** Custom tools, keyed by tool name. */
|
|
134
|
+
tools?: (helpers: WebMCPToolHelpers<TTarget>) => Record<string, WebMCPToolDefinition>;
|
|
135
|
+
/** Converts schemas that do not implement Standard JSON Schema. */
|
|
136
|
+
toJSONSchema?: (schema: StandardSchemaV1) => JSONSchema;
|
|
137
|
+
}
|
|
138
|
+
export interface WebMCPRegisterOptions {
|
|
139
|
+
/** Defaults to `document.modelContext`, then `navigator.modelContext`. */
|
|
140
|
+
modelContext?: WebMCPModelContext;
|
|
141
|
+
/** Unregisters every tool when aborted. */
|
|
142
|
+
signal?: AbortSignal;
|
|
143
|
+
/** Origins the tools are exposed to. */
|
|
144
|
+
exposedTo?: string[];
|
|
145
|
+
/**
|
|
146
|
+
* Called when registering a tool fails after `ready` has settled. Defaults to
|
|
147
|
+
* `reportError`.
|
|
148
|
+
*/
|
|
149
|
+
onError?: (error: unknown, tool: WebMCPTool) => void;
|
|
150
|
+
}
|
|
151
|
+
export type WebMCPRegistrationStatus = 'registered' | 'unregistered' | 'unsupported';
|
|
152
|
+
export interface WebMCPRegistration {
|
|
153
|
+
/** `'unsupported'` when no model context is available. */
|
|
154
|
+
readonly status: WebMCPRegistrationStatus;
|
|
155
|
+
/** Settles when the initially available tools have registered. */
|
|
156
|
+
readonly ready: Promise<void>;
|
|
157
|
+
/** Unregisters every tool and stops tracking state. */
|
|
158
|
+
unregister(): void;
|
|
159
|
+
}
|
|
160
|
+
export interface WebMCP {
|
|
161
|
+
/** Every tool, including event tools unavailable in the current state. */
|
|
162
|
+
readonly tools: readonly WebMCPTool[];
|
|
163
|
+
/** Tools available in the current state. */
|
|
164
|
+
getAvailableTools(): WebMCPTool[];
|
|
165
|
+
/** Registers the available tools with the browser's model context. */
|
|
166
|
+
register(options?: WebMCPRegisterOptions): WebMCPRegistration;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Converts an event type to a tool name by replacing `.` and other characters
|
|
170
|
+
* outside `[a-zA-Z0-9_-]` with `_`: `'checkout.confirm'` becomes
|
|
171
|
+
* `'checkout_confirm'`. Model APIs that agents forward tools to commonly reject
|
|
172
|
+
* other characters in tool names.
|
|
173
|
+
*/
|
|
174
|
+
export declare function toToolName(eventType: string): string;
|
|
175
|
+
/**
|
|
176
|
+
* Creates WebMCP tools from an XState actor or an `@xstate/store` store. Each
|
|
177
|
+
* exposed event becomes a tool whose input is the event payload; custom tools
|
|
178
|
+
* can send several events and wait for results.
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
*
|
|
182
|
+
* ```ts
|
|
183
|
+
* const webMCP = createWebMCP(store, { events: ['todo.*'] });
|
|
184
|
+
* const registration = webMCP.register();
|
|
185
|
+
* // later
|
|
186
|
+
* registration.unregister();
|
|
187
|
+
* ```
|
|
188
|
+
*/
|
|
189
|
+
export declare function createWebMCP<TTarget extends WebMCPTarget>(target: TTarget, options: WebMCPOptions<TTarget>): WebMCP;
|
|
190
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export * from "./declarations/src/index.js";
|
|
2
|
+
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoieHN0YXRlLXdlYm1jcC5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi9kZWNsYXJhdGlvbnMvc3JjL2luZGV4LmQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEifQ==
|
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An exact event type, `'*'`, or a trailing-token wildcard such as `'todo.*'`.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
function isWildcard(descriptor) {
|
|
6
|
+
return descriptor === '*' || descriptor.endsWith('.*');
|
|
7
|
+
}
|
|
8
|
+
function assertValidDescriptor(descriptor) {
|
|
9
|
+
const valid = descriptor === '*' || !descriptor.includes('*') || descriptor.endsWith('.*') && !descriptor.slice(0, -2).includes('*');
|
|
10
|
+
if (!valid) {
|
|
11
|
+
throw new Error(`Invalid event descriptor "${descriptor}". Wildcards must be the entire descriptor or the final token.`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Returns `true` if `eventType` matches an exact, `'*'`, or trailing-token
|
|
17
|
+
* wildcard descriptor. `'todo.*'` matches `'todo'` and every `'todo.…'` event.
|
|
18
|
+
*/
|
|
19
|
+
function matchesEventDescriptor(eventType, descriptor) {
|
|
20
|
+
if (descriptor === eventType || descriptor === '*') {
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
if (!descriptor.endsWith('.*')) {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
const prefixTokens = descriptor.slice(0, -2).split('.');
|
|
27
|
+
const eventTokens = eventType.split('.');
|
|
28
|
+
return prefixTokens.every((token, index) => token === eventTokens[index]);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Expands descriptors against the known event types. Throws for an exact
|
|
33
|
+
* descriptor that names an unknown event type.
|
|
34
|
+
*/
|
|
35
|
+
function resolveEventTypes(eventTypes, descriptors) {
|
|
36
|
+
for (const descriptor of descriptors) {
|
|
37
|
+
assertValidDescriptor(descriptor);
|
|
38
|
+
if (!isWildcard(descriptor) && !eventTypes.includes(descriptor)) {
|
|
39
|
+
throw new Error(`Cannot expose event "${descriptor}": it has no event schema. Add a schema for it in \`schemas.events\`.`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return eventTypes.filter(eventType => descriptors.some(descriptor => matchesEventDescriptor(eventType, descriptor)));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The Standard Schema interface. See https://standardschema.dev */
|
|
46
|
+
|
|
47
|
+
// oxlint-disable-next-line typescript/no-namespace -- mirrors the Standard Schema spec
|
|
48
|
+
|
|
49
|
+
/** A JSON Schema object. */
|
|
50
|
+
|
|
51
|
+
function isPromiseLike(value) {
|
|
52
|
+
return !!value && typeof value.then === 'function';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Converts a schema to an input JSON Schema, using `toJSONSchema` when given
|
|
57
|
+
* and Standard JSON Schema otherwise.
|
|
58
|
+
*/
|
|
59
|
+
function getInputJSONSchema(schema, toJSONSchema, label) {
|
|
60
|
+
if (toJSONSchema) {
|
|
61
|
+
return toJSONSchema(schema);
|
|
62
|
+
}
|
|
63
|
+
const jsonSchema = schema['~standard'].jsonSchema;
|
|
64
|
+
if (jsonSchema?.input) {
|
|
65
|
+
const {
|
|
66
|
+
$schema: _,
|
|
67
|
+
...rest
|
|
68
|
+
} = jsonSchema.input({
|
|
69
|
+
target: 'draft-07'
|
|
70
|
+
});
|
|
71
|
+
return rest;
|
|
72
|
+
}
|
|
73
|
+
throw new Error(`The schema for ${label} does not implement Standard JSON Schema. Pass a \`toJSONSchema\` option to convert it.`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Thrown when tool input fails its schema. */
|
|
77
|
+
class WebMCPInputError extends Error {
|
|
78
|
+
constructor(toolName, issues) {
|
|
79
|
+
super(`Invalid input for tool "${toolName}"${issues?.length ? `: ${issues.map(issue => issue.path?.length ? `${issue.path.map(segment => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${issue.message}` : issue.message).join('; ')}` : ''}`);
|
|
80
|
+
this.toolName = void 0;
|
|
81
|
+
this.issues = void 0;
|
|
82
|
+
this.name = 'WebMCPInputError';
|
|
83
|
+
this.toolName = toolName;
|
|
84
|
+
this.issues = issues;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Validates tool input and returns the schema output unchanged. */
|
|
89
|
+
async function validateInput(schema, toolName, input) {
|
|
90
|
+
if (!schema) {
|
|
91
|
+
return input ?? {};
|
|
92
|
+
}
|
|
93
|
+
const result = schema['~standard'].validate(input ?? {});
|
|
94
|
+
const validated = isPromiseLike(result) ? await result : result;
|
|
95
|
+
if (validated.issues) {
|
|
96
|
+
throw new WebMCPInputError(toolName, validated.issues);
|
|
97
|
+
}
|
|
98
|
+
return validated.value;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Validates an event payload, which must be an object to spread into the event. */
|
|
102
|
+
async function validateEventPayload(schema, toolName, input) {
|
|
103
|
+
const value = await validateInput(schema, toolName, input);
|
|
104
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
105
|
+
throw new WebMCPInputError(toolName, [{
|
|
106
|
+
message: 'Expected an object.'
|
|
107
|
+
}]);
|
|
108
|
+
}
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Hints that describe a tool's behavior to the agent. */
|
|
113
|
+
|
|
114
|
+
/** A tool in the shape `document.modelContext.registerTool(...)` accepts. */
|
|
115
|
+
|
|
116
|
+
/** The subset of the WebMCP `ModelContext` interface that tools register with. */
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Anything that can receive events and report snapshots: an XState actor or an
|
|
120
|
+
* `@xstate/store` store.
|
|
121
|
+
*/
|
|
122
|
+
|
|
123
|
+
/** Event types of `TTarget` that can be exposed as tools. */
|
|
124
|
+
|
|
125
|
+
/** Passed to the `execute` function of a custom tool. */
|
|
126
|
+
|
|
127
|
+
/** A custom tool created with the `tool` helper. */
|
|
128
|
+
|
|
129
|
+
const EMPTY_INPUT_SCHEMA = {
|
|
130
|
+
type: 'object',
|
|
131
|
+
properties: {}
|
|
132
|
+
};
|
|
133
|
+
function isMachineSnapshot(snapshot) {
|
|
134
|
+
return !!snapshot && Array.isArray(snapshot.nodes) && typeof snapshot.can === 'function';
|
|
135
|
+
}
|
|
136
|
+
function getEventSchemas(target) {
|
|
137
|
+
const source = target;
|
|
138
|
+
return source.schemas?.events ?? source.logic?.schemas?.events ?? {};
|
|
139
|
+
}
|
|
140
|
+
function getTransitionDescription(target, eventType) {
|
|
141
|
+
const machine = target.logic;
|
|
142
|
+
if (!(machine?.idMap instanceof Map)) {
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Exact transitions first, then matching wildcards, most specific first.
|
|
147
|
+
const candidates = [];
|
|
148
|
+
for (const node of machine.idMap.values()) {
|
|
149
|
+
for (const [descriptor, transitions] of node.transitions ?? []) {
|
|
150
|
+
const description = transitions.find(transition => transition.description)?.description;
|
|
151
|
+
if (description && matchesEventDescriptor(eventType, descriptor)) {
|
|
152
|
+
candidates.push({
|
|
153
|
+
rank: descriptor === eventType ? Infinity : descriptor.length,
|
|
154
|
+
description
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return candidates.sort((a, b) => b.rank - a.rank)[0]?.description;
|
|
160
|
+
}
|
|
161
|
+
function defaultOutput(snapshot) {
|
|
162
|
+
return {
|
|
163
|
+
status: snapshot.status,
|
|
164
|
+
...(snapshot.value !== undefined ? {
|
|
165
|
+
state: snapshot.value
|
|
166
|
+
} : {}),
|
|
167
|
+
...(snapshot.output !== undefined ? {
|
|
168
|
+
output: snapshot.output
|
|
169
|
+
} : {})
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function toError(error) {
|
|
173
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
174
|
+
}
|
|
175
|
+
function getDefaultModelContext() {
|
|
176
|
+
const global = globalThis;
|
|
177
|
+
return global.document?.modelContext ?? global.navigator?.modelContext;
|
|
178
|
+
}
|
|
179
|
+
function defaultOnError(error) {
|
|
180
|
+
const report = globalThis.reportError;
|
|
181
|
+
if (report) {
|
|
182
|
+
report(error);
|
|
183
|
+
} else {
|
|
184
|
+
console.error(error);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function waitForSnapshot(target, predicate, options) {
|
|
188
|
+
return new Promise((resolve, reject) => {
|
|
189
|
+
const {
|
|
190
|
+
signal,
|
|
191
|
+
timeout
|
|
192
|
+
} = options;
|
|
193
|
+
if (signal?.aborted) {
|
|
194
|
+
reject(toError(signal.reason));
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
let done = false;
|
|
198
|
+
// Assigned after `finish` is defined, which may run during `subscribe`.
|
|
199
|
+
const subscriptionRef = {};
|
|
200
|
+
let timer;
|
|
201
|
+
const finish = settle => {
|
|
202
|
+
if (done) {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
done = true;
|
|
206
|
+
subscriptionRef.current?.unsubscribe();
|
|
207
|
+
clearTimeout(timer);
|
|
208
|
+
signal?.removeEventListener('abort', onAbort);
|
|
209
|
+
settle();
|
|
210
|
+
};
|
|
211
|
+
const check = snapshot => {
|
|
212
|
+
let matches;
|
|
213
|
+
try {
|
|
214
|
+
matches = predicate(snapshot);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
finish(() => reject(toError(error)));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (matches) {
|
|
220
|
+
finish(() => resolve(snapshot));
|
|
221
|
+
} else if (snapshot.status === 'error') {
|
|
222
|
+
finish(() => reject(toError(snapshot.error)));
|
|
223
|
+
} else if (snapshot.status === 'done' || snapshot.status === 'stopped') {
|
|
224
|
+
finish(() => reject(new Error(`The target reached status "${snapshot.status}" before the condition was met.`)));
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
const onAbort = () => finish(() => reject(toError(signal.reason)));
|
|
228
|
+
signal?.addEventListener('abort', onAbort, {
|
|
229
|
+
once: true
|
|
230
|
+
});
|
|
231
|
+
if (timeout !== undefined) {
|
|
232
|
+
timer = setTimeout(() => finish(() => reject(new Error(`waitFor timed out after ${timeout}ms.`))), timeout);
|
|
233
|
+
}
|
|
234
|
+
const subscription = target.subscribe(snapshot => check(snapshot), error => finish(() => reject(toError(error))),
|
|
235
|
+
// A stopped actor completes without publishing its final snapshot.
|
|
236
|
+
() => {
|
|
237
|
+
check(target.getSnapshot());
|
|
238
|
+
finish(() => reject(new Error('The target stopped before the condition was met.')));
|
|
239
|
+
});
|
|
240
|
+
subscriptionRef.current = subscription;
|
|
241
|
+
if (done) {
|
|
242
|
+
subscription.unsubscribe();
|
|
243
|
+
} else {
|
|
244
|
+
check(target.getSnapshot());
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Converts an event type to a tool name by replacing `.` and other characters
|
|
251
|
+
* outside `[a-zA-Z0-9_-]` with `_`: `'checkout.confirm'` becomes
|
|
252
|
+
* `'checkout_confirm'`. Model APIs that agents forward tools to commonly reject
|
|
253
|
+
* other characters in tool names.
|
|
254
|
+
*/
|
|
255
|
+
function toToolName(eventType) {
|
|
256
|
+
return eventType.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
257
|
+
}
|
|
258
|
+
function assertValidToolName(name) {
|
|
259
|
+
if (!/^[a-zA-Z0-9_.-]{1,128}$/.test(name)) {
|
|
260
|
+
throw new Error(`Invalid tool name "${name}". Names must be 1-128 characters made of ASCII letters, digits, "_", "-" or ".".`);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Creates WebMCP tools from an XState actor or an `@xstate/store` store. Each
|
|
266
|
+
* exposed event becomes a tool whose input is the event payload; custom tools
|
|
267
|
+
* can send several events and wait for results.
|
|
268
|
+
*
|
|
269
|
+
* @example
|
|
270
|
+
*
|
|
271
|
+
* ```ts
|
|
272
|
+
* const webMCP = createWebMCP(store, { events: ['todo.*'] });
|
|
273
|
+
* const registration = webMCP.register();
|
|
274
|
+
* // later
|
|
275
|
+
* registration.unregister();
|
|
276
|
+
* ```
|
|
277
|
+
*/
|
|
278
|
+
function createWebMCP(target, options) {
|
|
279
|
+
const schemas = getEventSchemas(target);
|
|
280
|
+
const descriptors = typeof options.events === 'string' ? [options.events] : options.events;
|
|
281
|
+
const eventTypes = resolveEventTypes(Object.keys(schemas).filter(eventType => !isWildcard(eventType)), descriptors);
|
|
282
|
+
const tracksState = (options.availability ?? 'state') === 'state' && isMachineSnapshot(target.getSnapshot());
|
|
283
|
+
const output = options.output ?? defaultOutput;
|
|
284
|
+
const overrides = options.overrides ?? {};
|
|
285
|
+
const names = new Map();
|
|
286
|
+
const mapToolName = options.toolName ?? toToolName;
|
|
287
|
+
const entries = [];
|
|
288
|
+
const toolName = (name, source) => {
|
|
289
|
+
const fullName = options.prefix ? `${options.prefix}_${name}` : name;
|
|
290
|
+
assertValidToolName(fullName);
|
|
291
|
+
const existing = names.get(fullName);
|
|
292
|
+
if (existing) {
|
|
293
|
+
throw new Error(`Duplicate tool name "${fullName}" for ${existing} and ${source}.`);
|
|
294
|
+
}
|
|
295
|
+
names.set(fullName, source);
|
|
296
|
+
return fullName;
|
|
297
|
+
};
|
|
298
|
+
const handles = (entry, snapshot) => !entry.eventType || !isMachineSnapshot(snapshot) || snapshot.status === 'active' && snapshot.nodes.some(node => node.ownEvents.some(descriptor => matchesEventDescriptor(entry.eventType, descriptor)));
|
|
299
|
+
const isAvailable = (entry, snapshot) => !tracksState || handles(entry, snapshot);
|
|
300
|
+
const getAvailableTools = () => {
|
|
301
|
+
const snapshot = target.getSnapshot();
|
|
302
|
+
return entries.filter(entry => isAvailable(entry, snapshot)).map(entry => entry.tool);
|
|
303
|
+
};
|
|
304
|
+
for (const eventType of eventTypes) {
|
|
305
|
+
const schema = schemas[eventType];
|
|
306
|
+
const override = overrides[eventType] ?? {};
|
|
307
|
+
const inputSchema = getInputJSONSchema(schema, options.toJSONSchema, `event "${eventType}"`);
|
|
308
|
+
const schemaDescription = typeof inputSchema.description === 'string' && inputSchema.description.trim() ? inputSchema.description : undefined;
|
|
309
|
+
const description = override.description ?? schemaDescription ?? getTransitionDescription(target, eventType);
|
|
310
|
+
if (!description) {
|
|
311
|
+
throw new Error(`Event "${eventType}" needs a description to become a tool. Describe its schema (for example \`z.object({...}).describe('...')\`) or set \`overrides["${eventType}"].description\`.`);
|
|
312
|
+
}
|
|
313
|
+
const name = toolName(override.name ?? mapToolName(eventType, schema), `event "${eventType}"`);
|
|
314
|
+
const title = override.title ?? (typeof inputSchema.title === 'string' ? inputSchema.title : undefined);
|
|
315
|
+
entries.push({
|
|
316
|
+
eventType,
|
|
317
|
+
tool: {
|
|
318
|
+
name,
|
|
319
|
+
...(title ? {
|
|
320
|
+
title
|
|
321
|
+
} : {}),
|
|
322
|
+
description,
|
|
323
|
+
inputSchema,
|
|
324
|
+
...(override.annotations ? {
|
|
325
|
+
annotations: override.annotations
|
|
326
|
+
} : {}),
|
|
327
|
+
async execute(input, executeOptions) {
|
|
328
|
+
const signal = executeOptions?.signal;
|
|
329
|
+
signal?.throwIfAborted();
|
|
330
|
+
const payload = await validateEventPayload(schema, name, input);
|
|
331
|
+
signal?.throwIfAborted();
|
|
332
|
+
const event = {
|
|
333
|
+
...payload,
|
|
334
|
+
type: eventType
|
|
335
|
+
};
|
|
336
|
+
const snapshot = target.getSnapshot();
|
|
337
|
+
if (isMachineSnapshot(snapshot) && !snapshot.can(event)) {
|
|
338
|
+
const available = entries.filter(entry => handles(entry, snapshot)).map(entry => entry.tool.name);
|
|
339
|
+
throw new Error(`Tool "${name}" cannot run in the current state. Available tools: ${available.length ? available.join(', ') : 'none'}.`);
|
|
340
|
+
}
|
|
341
|
+
target.send(event);
|
|
342
|
+
const next = target.getSnapshot();
|
|
343
|
+
if (next?.status === 'error') {
|
|
344
|
+
throw toError(next.error);
|
|
345
|
+
}
|
|
346
|
+
return output(next);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
if (options.stateTool !== false) {
|
|
352
|
+
const stateTool = typeof options.stateTool === 'object' ? options.stateTool : {};
|
|
353
|
+
entries.push({
|
|
354
|
+
tool: {
|
|
355
|
+
name: toolName(stateTool.name ?? 'get_state', 'the state tool'),
|
|
356
|
+
...(stateTool.title ? {
|
|
357
|
+
title: stateTool.title
|
|
358
|
+
} : {}),
|
|
359
|
+
description: stateTool.description ?? 'Get the current state.',
|
|
360
|
+
inputSchema: EMPTY_INPUT_SCHEMA,
|
|
361
|
+
annotations: {
|
|
362
|
+
readOnlyHint: true
|
|
363
|
+
},
|
|
364
|
+
execute() {
|
|
365
|
+
return Promise.resolve(output(target.getSnapshot()));
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
const configs = new WeakMap();
|
|
371
|
+
const helpers = {
|
|
372
|
+
tool: config => {
|
|
373
|
+
const definition = {};
|
|
374
|
+
configs.set(definition, config);
|
|
375
|
+
return definition;
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
for (const [key, definition] of Object.entries(options.tools?.(helpers) ?? {})) {
|
|
379
|
+
const config = configs.get(definition);
|
|
380
|
+
if (!config) {
|
|
381
|
+
throw new Error(`Custom tool "${key}" must be created with the \`tool\` helper.`);
|
|
382
|
+
}
|
|
383
|
+
const name = toolName(key, `custom tool "${key}"`);
|
|
384
|
+
const inputSchema = config.input ? getInputJSONSchema(config.input, options.toJSONSchema, `tool "${key}"`) : EMPTY_INPUT_SCHEMA;
|
|
385
|
+
entries.push({
|
|
386
|
+
tool: {
|
|
387
|
+
name,
|
|
388
|
+
...(config.title ? {
|
|
389
|
+
title: config.title
|
|
390
|
+
} : {}),
|
|
391
|
+
description: config.description,
|
|
392
|
+
inputSchema,
|
|
393
|
+
...(config.annotations ? {
|
|
394
|
+
annotations: config.annotations
|
|
395
|
+
} : {}),
|
|
396
|
+
async execute(input, executeOptions) {
|
|
397
|
+
const signal = executeOptions?.signal ?? new AbortController().signal;
|
|
398
|
+
signal.throwIfAborted();
|
|
399
|
+
const value = await validateInput(config.input, name, input);
|
|
400
|
+
signal.throwIfAborted();
|
|
401
|
+
return config.execute(value, {
|
|
402
|
+
target,
|
|
403
|
+
send: event => target.send(event),
|
|
404
|
+
getSnapshot: () => target.getSnapshot(),
|
|
405
|
+
waitFor: (predicate, waitOptions = {}) => waitForSnapshot(target, predicate, {
|
|
406
|
+
signal,
|
|
407
|
+
...waitOptions
|
|
408
|
+
}),
|
|
409
|
+
signal
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
return {
|
|
416
|
+
tools: entries.map(entry => entry.tool),
|
|
417
|
+
getAvailableTools,
|
|
418
|
+
register(registerOptions = {}) {
|
|
419
|
+
const modelContext = registerOptions.modelContext ?? getDefaultModelContext();
|
|
420
|
+
if (!modelContext) {
|
|
421
|
+
return {
|
|
422
|
+
status: 'unsupported',
|
|
423
|
+
ready: Promise.resolve(),
|
|
424
|
+
unregister() {}
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
const {
|
|
428
|
+
signal,
|
|
429
|
+
exposedTo
|
|
430
|
+
} = registerOptions;
|
|
431
|
+
const onError = registerOptions.onError ?? defaultOnError;
|
|
432
|
+
const controllers = new Map();
|
|
433
|
+
let status = 'registered';
|
|
434
|
+
let subscription;
|
|
435
|
+
const registerTool = tool => {
|
|
436
|
+
const controller = new AbortController();
|
|
437
|
+
controllers.set(tool, controller);
|
|
438
|
+
return Promise.resolve().then(() => {
|
|
439
|
+
// A state change or `unregister()` superseded this registration.
|
|
440
|
+
if (!controller.signal.aborted) {
|
|
441
|
+
return modelContext.registerTool(tool, {
|
|
442
|
+
signal: controller.signal,
|
|
443
|
+
...(exposedTo ? {
|
|
444
|
+
exposedTo
|
|
445
|
+
} : {})
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
}).catch(error => {
|
|
449
|
+
if (controller.signal.aborted) {
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
if (controllers.get(tool) === controller) {
|
|
453
|
+
controllers.delete(tool);
|
|
454
|
+
}
|
|
455
|
+
throw error;
|
|
456
|
+
});
|
|
457
|
+
};
|
|
458
|
+
const sync = snapshot => {
|
|
459
|
+
if (status !== 'registered') {
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
for (const entry of entries) {
|
|
463
|
+
const controller = controllers.get(entry.tool);
|
|
464
|
+
const available = isAvailable(entry, snapshot);
|
|
465
|
+
if (available && !controller) {
|
|
466
|
+
registerTool(entry.tool).catch(error => onError(error, entry.tool));
|
|
467
|
+
} else if (!available && controller) {
|
|
468
|
+
controller.abort();
|
|
469
|
+
controllers.delete(entry.tool);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
const unregister = () => {
|
|
474
|
+
if (status !== 'registered') {
|
|
475
|
+
return;
|
|
476
|
+
}
|
|
477
|
+
status = 'unregistered';
|
|
478
|
+
subscription?.unsubscribe();
|
|
479
|
+
signal?.removeEventListener('abort', unregister);
|
|
480
|
+
for (const controller of controllers.values()) {
|
|
481
|
+
controller.abort();
|
|
482
|
+
}
|
|
483
|
+
controllers.clear();
|
|
484
|
+
};
|
|
485
|
+
if (signal?.aborted) {
|
|
486
|
+
status = 'unregistered';
|
|
487
|
+
return {
|
|
488
|
+
status,
|
|
489
|
+
ready: Promise.resolve(),
|
|
490
|
+
unregister() {}
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
signal?.addEventListener('abort', unregister, {
|
|
494
|
+
once: true
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
// Registration is all or nothing: if a tool fails to register, remove
|
|
498
|
+
// the others so a retry does not collide with them.
|
|
499
|
+
const ready = Promise.all(getAvailableTools().map(registerTool)).then(() => {}, error => {
|
|
500
|
+
unregister();
|
|
501
|
+
throw error;
|
|
502
|
+
});
|
|
503
|
+
if (tracksState) {
|
|
504
|
+
const syncCurrent = () => sync(target.getSnapshot());
|
|
505
|
+
subscription = target.subscribe(sync, syncCurrent, syncCurrent);
|
|
506
|
+
}
|
|
507
|
+
return {
|
|
508
|
+
get status() {
|
|
509
|
+
return status;
|
|
510
|
+
},
|
|
511
|
+
ready,
|
|
512
|
+
unregister
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Creates an in-memory model context for tests. It follows the WebMCP
|
|
520
|
+
* registration rules: duplicate names reject, and aborting the registration
|
|
521
|
+
* signal unregisters the tool.
|
|
522
|
+
*/
|
|
523
|
+
function createMockModelContext() {
|
|
524
|
+
const tools = new Map();
|
|
525
|
+
return {
|
|
526
|
+
tools,
|
|
527
|
+
registerTool(tool, options) {
|
|
528
|
+
// Like the browser, reject registration with an already-aborted signal.
|
|
529
|
+
if (options?.signal?.aborted) {
|
|
530
|
+
const reason = options.signal.reason;
|
|
531
|
+
return Promise.reject(reason instanceof Error ? reason : new Error(String(reason)));
|
|
532
|
+
}
|
|
533
|
+
if (tools.has(tool.name)) {
|
|
534
|
+
return Promise.reject(new Error(`A tool named "${tool.name}" is already registered.`));
|
|
535
|
+
}
|
|
536
|
+
tools.set(tool.name, tool);
|
|
537
|
+
options?.signal?.addEventListener('abort', () => {
|
|
538
|
+
if (tools.get(tool.name) === tool) {
|
|
539
|
+
tools.delete(tool.name);
|
|
540
|
+
}
|
|
541
|
+
}, {
|
|
542
|
+
once: true
|
|
543
|
+
});
|
|
544
|
+
return Promise.resolve();
|
|
545
|
+
},
|
|
546
|
+
getToolNames() {
|
|
547
|
+
return [...tools.keys()];
|
|
548
|
+
},
|
|
549
|
+
async executeTool(name, input = {}, options = {}) {
|
|
550
|
+
const tool = tools.get(name);
|
|
551
|
+
if (!tool) {
|
|
552
|
+
throw new Error(`No tool named "${name}" is registered.`);
|
|
553
|
+
}
|
|
554
|
+
const result = await tool.execute(input, {
|
|
555
|
+
signal: options.signal ?? new AbortController().signal
|
|
556
|
+
});
|
|
557
|
+
const serialized = JSON.stringify(result);
|
|
558
|
+
return serialized === undefined ? undefined : JSON.parse(serialized);
|
|
559
|
+
}
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
export { WebMCPInputError, createMockModelContext, createWebMCP, matchesEventDescriptor, toToolName };
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xstate/webmcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-beta.1",
|
|
4
|
+
"description": "Expose XState actors and @xstate/store stores as WebMCP tools",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"xstate",
|
|
7
|
+
"store",
|
|
8
|
+
"webmcp",
|
|
9
|
+
"mcp",
|
|
10
|
+
"ai",
|
|
11
|
+
"agent",
|
|
12
|
+
"tools"
|
|
13
|
+
],
|
|
14
|
+
"author": "David Khourshid <davidkpiano@gmail.com>",
|
|
15
|
+
"homepage": "https://github.com/statelyai/xstate/tree/next/packages/xstate-webmcp#readme",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"type": "module",
|
|
18
|
+
"sideEffects": false,
|
|
19
|
+
"exports": {
|
|
20
|
+
".": "./dist/xstate-webmcp.js",
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+ssh://git@github.com/statelyai/xstate.git"
|
|
31
|
+
},
|
|
32
|
+
"bugs": {
|
|
33
|
+
"url": "https://github.com/statelyai/xstate/issues"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"zod": "^4.4.3",
|
|
37
|
+
"@xstate/store": "^5.0.0-alpha.8",
|
|
38
|
+
"xstate": "^6.0.0-beta.8"
|
|
39
|
+
}
|
|
6
40
|
}
|