@flowdrop/flowdrop 2.5.0 → 2.6.0

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/chat/commandClassifier.d.ts +17 -0
  3. package/dist/chat/commandClassifier.js +29 -0
  4. package/dist/chat/index.d.ts +1 -1
  5. package/dist/chat/index.js +1 -1
  6. package/dist/components/App.svelte +8 -0
  7. package/dist/components/BindablePortListbox.svelte +426 -0
  8. package/dist/components/BindablePortListbox.svelte.d.ts +23 -0
  9. package/dist/components/WorkflowInterfaceEditor.svelte +142 -36
  10. package/dist/components/WorkflowInterfaceEditor.svelte.d.ts +8 -0
  11. package/dist/components/WorkflowInterfaceEntryCard.svelte +537 -294
  12. package/dist/components/WorkflowInterfaceEntryCard.svelte.d.ts +6 -3
  13. package/dist/components/WorkflowInterfaceEntryComposer.svelte +331 -0
  14. package/dist/components/WorkflowInterfaceEntryComposer.svelte.d.ts +19 -0
  15. package/dist/messages/context.d.ts +6 -0
  16. package/dist/messages/context.js +8 -0
  17. package/dist/messages/defaults.d.ts +45 -2
  18. package/dist/messages/defaults.js +36 -3
  19. package/dist/messages/index.d.ts +1 -1
  20. package/dist/messages/index.js +1 -1
  21. package/dist/stores/instanceContainer.svelte.d.ts +26 -0
  22. package/dist/stores/instanceContainer.svelte.js +24 -0
  23. package/dist/stories/WebMCPFakeAgent.svelte +229 -0
  24. package/dist/stories/WebMCPFakeAgent.svelte.d.ts +10 -0
  25. package/dist/styles/base.css +4 -2
  26. package/dist/svelte-app.d.ts +20 -0
  27. package/dist/svelte-app.js +49 -1
  28. package/dist/utils/focus.d.ts +18 -0
  29. package/dist/utils/focus.js +24 -0
  30. package/dist/utils/whenWorkflowLoaded.svelte.d.ts +17 -0
  31. package/dist/utils/whenWorkflowLoaded.svelte.js +42 -0
  32. package/dist/utils/workflowInterface.d.ts +47 -3
  33. package/dist/utils/workflowInterface.js +84 -9
  34. package/dist/webmcp/WebMCP.stories.svelte +101 -0
  35. package/dist/webmcp/WebMCP.stories.svelte.d.ts +18 -0
  36. package/dist/webmcp/WebMCPConfirm.svelte +170 -0
  37. package/dist/webmcp/WebMCPConfirm.svelte.d.ts +11 -0
  38. package/dist/webmcp/descriptors.d.ts +59 -0
  39. package/dist/webmcp/descriptors.js +464 -0
  40. package/dist/webmcp/fake.d.ts +23 -0
  41. package/dist/webmcp/fake.js +42 -0
  42. package/dist/webmcp/gate.d.ts +40 -0
  43. package/dist/webmcp/gate.js +92 -0
  44. package/dist/webmcp/index.d.ts +34 -0
  45. package/dist/webmcp/index.js +31 -0
  46. package/dist/webmcp/register.d.ts +33 -0
  47. package/dist/webmcp/register.js +267 -0
  48. package/dist/webmcp/types.d.ts +166 -0
  49. package/dist/webmcp/types.js +23 -0
  50. package/dist/webmcp/validate.d.ts +32 -0
  51. package/dist/webmcp/validate.js +118 -0
  52. package/package.json +6 -1
@@ -0,0 +1,464 @@
1
+ /**
2
+ * WebMCP adapter — tool descriptors.
3
+ *
4
+ * Maps the command union to `{verb, description, inputSchema, readOnly,
5
+ * toCommands}` records. Transport-free: no DOM, no Svelte, nothing from the
6
+ * runtime — so the same records can back a server-side MCP endpoint later.
7
+ *
8
+ * The schemas are written by hand next to the interfaces they mirror
9
+ * (`commands/types.ts`). Each exposed command is one record in `COMMANDS`:
10
+ * its description, its input schema, how validated arguments become the
11
+ * command, and how the command reads back to a human in the confirm dialog.
12
+ * The coverage test in `tests/unit/webmcp` asserts every literal of the
13
+ * `Command` union is either exposed here or on the explicit exclusion list,
14
+ * and that every exposed record carries all four parts, so a new DSL verb
15
+ * cannot slip through unclassified or half-described.
16
+ *
17
+ * @module webmcp/descriptors
18
+ */
19
+ import { isMutatingCommand, VIEW_COMMAND_TYPES } from '../chat/commandClassifier.js';
20
+ import { ToolArgumentError } from './types.js';
21
+ import { validateToolArgs } from './validate.js';
22
+ export { validateToolArgs };
23
+ // ============================================================================
24
+ // What is exposed
25
+ // ============================================================================
26
+ /** Command types exposed as one tool each (verb === command type). */
27
+ export const EXPOSED_COMMAND_TYPES = [
28
+ 'add_node',
29
+ 'delete_node',
30
+ 'rename_node',
31
+ 'move_node',
32
+ 'swap_node',
33
+ 'set_config',
34
+ 'get_config',
35
+ 'connect',
36
+ 'disconnect_ports',
37
+ 'disconnect_node',
38
+ 'list_nodes',
39
+ 'list_edges',
40
+ 'list_types',
41
+ 'info',
42
+ 'undo',
43
+ 'redo',
44
+ 'auto_layout',
45
+ 'beautify_layout'
46
+ ];
47
+ /**
48
+ * Command types folded into the single `view` tool (its `action` enum). The
49
+ * list itself lives in the command classifier, next to `isViewCommand`, so
50
+ * the chat panel and this adapter cannot disagree about what a view command is.
51
+ */
52
+ export { VIEW_COMMAND_TYPES };
53
+ /**
54
+ * Command types deliberately not exposed.
55
+ * - `clear` wipes the whole workflow; an agent can delete nodes one by one and
56
+ * each deletion is gated.
57
+ * - `help` describes the text DSL; the tool schemas are the help.
58
+ */
59
+ export const EXCLUDED_COMMAND_TYPES = [
60
+ 'clear',
61
+ 'help'
62
+ ];
63
+ /** Extra tool verbs that are not command types. */
64
+ export const COMPOSITE_VERBS = ['view', 'batch'];
65
+ // ============================================================================
66
+ // Schema fragments
67
+ // ============================================================================
68
+ const NODE_ID_DESCRIPTION = 'Node id in short form, e.g. "llm_node.1" — the `nodeId` values returned by list_nodes and add_node. Full ids are accepted too.';
69
+ const nodeId = (description = NODE_ID_DESCRIPTION) => ({
70
+ type: 'string',
71
+ description
72
+ });
73
+ const position = {
74
+ type: 'object',
75
+ description: 'Canvas position in pixels.',
76
+ properties: {
77
+ x: { type: 'number', description: 'Horizontal position.' },
78
+ y: { type: 'number', description: 'Vertical position.' }
79
+ },
80
+ required: ['x', 'y'],
81
+ additionalProperties: false
82
+ };
83
+ const port = (which) => ({
84
+ type: 'string',
85
+ description: `${which} port id, as listed under inputs/outputs by the info tool.`
86
+ });
87
+ const configValue = {
88
+ description: 'The new value. Strings are stored verbatim; numbers, booleans, arrays and objects are stored typed.',
89
+ anyOf: [
90
+ { type: 'string' },
91
+ { type: 'number' },
92
+ { type: 'boolean' },
93
+ { type: 'object' },
94
+ { type: 'array' }
95
+ ]
96
+ };
97
+ const object = (properties, required = []) => ({
98
+ type: 'object',
99
+ properties,
100
+ ...(required.length > 0 ? { required } : {}),
101
+ additionalProperties: false
102
+ });
103
+ const EMPTY = object({});
104
+ /**
105
+ * `SetConfigCommand.value` is the DSL's raw token: the executor parses it with
106
+ * the same rules the text DSL uses (`"…"` → string, bare `12` → number, `true`
107
+ * → boolean, `{…}`/`[…]` → JSON). JSON-encoding every typed argument routes
108
+ * each shape to the right rule, and keeps a string like `"true"` a string.
109
+ */
110
+ function encodeConfigValue(value) {
111
+ return JSON.stringify(value);
112
+ }
113
+ const q = (v) => JSON.stringify(v);
114
+ const at = (p) => `(${p.x}, ${p.y})`;
115
+ const PORT_PAIR = object({
116
+ sourceNodeId: nodeId('Node the edge starts at.'),
117
+ sourcePort: port('Output'),
118
+ targetNodeId: nodeId('Node the edge ends at.'),
119
+ targetPort: port('Input')
120
+ }, ['sourceNodeId', 'sourcePort', 'targetNodeId', 'targetPort']);
121
+ /** One record per exposed command, keyed by command type. */
122
+ const COMMANDS = {
123
+ add_node: {
124
+ description: 'Add a node of the given type to the workflow. Returns the new node id.',
125
+ inputSchema: object({
126
+ nodeTypeId: {
127
+ type: 'string',
128
+ description: 'Node type id as returned by list_types (`typeId`), e.g. "llm_node". Call list_types first.'
129
+ },
130
+ position: {
131
+ ...position,
132
+ description: 'Optional canvas position; auto-placed when omitted.'
133
+ }
134
+ }, ['nodeTypeId']),
135
+ build: (a) => ({
136
+ type: 'add_node',
137
+ nodeTypeId: a.nodeTypeId,
138
+ ...(a.position ? { position: a.position } : {})
139
+ }),
140
+ summarize: (c) => `Add node ${c.nodeTypeId}${c.position ? ` at ${at(c.position)}` : ''}`
141
+ },
142
+ delete_node: {
143
+ description: 'Delete a node and every edge attached to it.',
144
+ inputSchema: object({ nodeId: nodeId() }, ['nodeId']),
145
+ build: (a) => ({ type: 'delete_node', nodeId: a.nodeId }),
146
+ summarize: (c) => `Delete node ${c.nodeId}`
147
+ },
148
+ rename_node: {
149
+ description: 'Change the display label of a node.',
150
+ inputSchema: object({ nodeId: nodeId(), label: { type: 'string', description: 'New display label.' } }, ['nodeId', 'label']),
151
+ build: (a) => ({ type: 'rename_node', nodeId: a.nodeId, label: a.label }),
152
+ summarize: (c) => `Rename ${c.nodeId} to ${q(c.label)}`
153
+ },
154
+ move_node: {
155
+ description: 'Move a node to a canvas position.',
156
+ inputSchema: object({ nodeId: nodeId(), position }, ['nodeId', 'position']),
157
+ build: (a) => ({ type: 'move_node', nodeId: a.nodeId, position: a.position }),
158
+ summarize: (c) => `Move ${c.nodeId} to ${at(c.position)}`
159
+ },
160
+ swap_node: {
161
+ description: 'Replace a node with one of another type, keeping compatible connections and config. Reports what was dropped.',
162
+ inputSchema: object({
163
+ nodeId: nodeId('Node to replace.'),
164
+ newTypeId: {
165
+ type: 'string',
166
+ description: 'Replacement node type id (see list_types). Compatible ports and config carry over.'
167
+ }
168
+ }, ['nodeId', 'newTypeId']),
169
+ build: (a) => ({
170
+ type: 'swap_node',
171
+ nodeId: a.nodeId,
172
+ newTypeId: a.newTypeId
173
+ }),
174
+ summarize: (c) => `Swap ${c.nodeId} for a ${c.newTypeId}`
175
+ },
176
+ set_config: {
177
+ description: 'Set one configuration value on a node. Validation warnings are returned, not fatal, unless strict.',
178
+ inputSchema: object({
179
+ nodeId: nodeId(),
180
+ key: {
181
+ type: 'string',
182
+ description: 'Config key, as listed under `config` by the info tool.'
183
+ },
184
+ value: configValue,
185
+ strict: {
186
+ type: 'boolean',
187
+ description: 'When true, a value the schema rejects fails the call instead of warning.'
188
+ }
189
+ }, ['nodeId', 'key', 'value']),
190
+ build: (a) => ({
191
+ type: 'set_config',
192
+ nodeId: a.nodeId,
193
+ key: a.key,
194
+ value: encodeConfigValue(a.value),
195
+ ...(a.strict !== undefined ? { strict: a.strict } : {})
196
+ }),
197
+ summarize: (c) => `Set ${c.nodeId}.${c.key} = ${c.value}`
198
+ },
199
+ get_config: {
200
+ description: 'Read one configuration value from a node.',
201
+ inputSchema: object({ nodeId: nodeId(), key: { type: 'string', description: 'Config key to read.' } }, ['nodeId', 'key']),
202
+ build: (a) => ({ type: 'get_config', nodeId: a.nodeId, key: a.key }),
203
+ summarize: (c) => `Read ${c.nodeId}.${c.key}`
204
+ },
205
+ connect: {
206
+ description: 'Connect an output port of one node to an input port of another. Fails on type mismatch or cycle.',
207
+ inputSchema: PORT_PAIR,
208
+ build: (a) => ({
209
+ type: 'connect',
210
+ sourceNodeId: a.sourceNodeId,
211
+ sourcePort: a.sourcePort,
212
+ targetNodeId: a.targetNodeId,
213
+ targetPort: a.targetPort
214
+ }),
215
+ summarize: (c) => `Connect ${c.sourceNodeId}:${c.sourcePort} → ${c.targetNodeId}:${c.targetPort}`
216
+ },
217
+ disconnect_ports: {
218
+ description: 'Remove the edge between two specific ports.',
219
+ inputSchema: PORT_PAIR,
220
+ build: (a) => ({
221
+ type: 'disconnect_ports',
222
+ sourceNodeId: a.sourceNodeId,
223
+ sourcePort: a.sourcePort,
224
+ targetNodeId: a.targetNodeId,
225
+ targetPort: a.targetPort
226
+ }),
227
+ summarize: (c) => `Disconnect ${c.sourceNodeId}:${c.sourcePort} → ${c.targetNodeId}:${c.targetPort}`
228
+ },
229
+ disconnect_node: {
230
+ description: 'Remove every edge attached to a node.',
231
+ inputSchema: object({ nodeId: nodeId() }, ['nodeId']),
232
+ build: (a) => ({ type: 'disconnect_node', nodeId: a.nodeId }),
233
+ summarize: (c) => `Disconnect every edge of ${c.nodeId}`
234
+ },
235
+ list_nodes: {
236
+ description: 'List the nodes in the workflow with their ids, labels and types.',
237
+ inputSchema: EMPTY,
238
+ build: () => ({ type: 'list_nodes' }),
239
+ summarize: () => 'List nodes'
240
+ },
241
+ list_edges: {
242
+ description: 'List the edges in the workflow with source/target node ids and ports.',
243
+ inputSchema: EMPTY,
244
+ build: () => ({ type: 'list_edges' }),
245
+ summarize: () => 'List edges'
246
+ },
247
+ list_types: {
248
+ description: 'List the node types that can be added, with their `typeId`, name and category. Call this before add_node.',
249
+ inputSchema: EMPTY,
250
+ build: () => ({ type: 'list_types' }),
251
+ summarize: () => 'List node types'
252
+ },
253
+ info: {
254
+ description: 'Describe one node: type, position, current config, input and output ports, and connected edges.',
255
+ inputSchema: object({ nodeId: nodeId() }, ['nodeId']),
256
+ build: (a) => ({ type: 'info', nodeId: a.nodeId }),
257
+ summarize: (c) => `Describe ${c.nodeId}`
258
+ },
259
+ undo: {
260
+ description: 'Undo the last change. Each tool call that changed the workflow is one undo step.',
261
+ inputSchema: EMPTY,
262
+ build: () => ({ type: 'undo' }),
263
+ summarize: () => 'Undo'
264
+ },
265
+ redo: {
266
+ description: 'Redo the last undone change.',
267
+ inputSchema: EMPTY,
268
+ build: () => ({ type: 'redo' }),
269
+ summarize: () => 'Redo'
270
+ },
271
+ auto_layout: {
272
+ description: 'Re-arrange all nodes automatically. Moves existing nodes.',
273
+ inputSchema: object({
274
+ direction: {
275
+ type: 'string',
276
+ enum: ['horizontal', 'vertical'],
277
+ description: 'Flow direction. Default horizontal.'
278
+ }
279
+ }),
280
+ build: (a) => ({
281
+ type: 'auto_layout',
282
+ ...(a.direction ? { direction: a.direction } : {})
283
+ }),
284
+ summarize: (c) => `Auto-layout (${c.direction ?? 'horizontal'})`
285
+ },
286
+ beautify_layout: {
287
+ description: 'Tidy the layout of all nodes. Moves existing nodes.',
288
+ inputSchema: EMPTY,
289
+ build: () => ({ type: 'beautify_layout' }),
290
+ summarize: () => 'Beautify layout'
291
+ }
292
+ };
293
+ /** The record for one exposed command — for tests that check its shape. */
294
+ export function commandRecord(type) {
295
+ return COMMANDS[type];
296
+ }
297
+ // ============================================================================
298
+ // view + batch
299
+ // ============================================================================
300
+ const VIEW_ACTIONS = [
301
+ 'select_node',
302
+ 'open_config',
303
+ 'fit_view',
304
+ 'zoom_in',
305
+ 'zoom_out',
306
+ 'zoom_to',
307
+ 'pan_to',
308
+ 'reset_view'
309
+ ];
310
+ const VIEW_TO_COMMAND = {
311
+ select_node: 'select_node',
312
+ open_config: 'config_open',
313
+ fit_view: 'canvas_fit_view',
314
+ zoom_in: 'canvas_zoom_in',
315
+ zoom_out: 'canvas_zoom_out',
316
+ zoom_to: 'canvas_zoom_to',
317
+ pan_to: 'canvas_pan_to',
318
+ reset_view: 'canvas_reset_view'
319
+ };
320
+ const VIEW_SCHEMA = object({
321
+ action: {
322
+ type: 'string',
323
+ enum: VIEW_ACTIONS,
324
+ description: 'select_node / open_config need nodeId; zoom_to needs level; pan_to needs position; the rest take nothing else.'
325
+ },
326
+ nodeId: nodeId('Node for select_node and open_config.'),
327
+ level: {
328
+ type: 'number',
329
+ description: 'Zoom level for zoom_to (1 = 100%).',
330
+ minimum: 0.1,
331
+ maximum: 4
332
+ },
333
+ position: { ...position, description: 'Canvas position for pan_to.' }
334
+ }, ['action']);
335
+ function buildViewCommand(args) {
336
+ const action = args.action;
337
+ const requireArg = (key) => {
338
+ if (args[key] === undefined)
339
+ throw new ToolArgumentError(`${key} is required for action "${action}"`);
340
+ };
341
+ switch (action) {
342
+ case 'select_node':
343
+ requireArg('nodeId');
344
+ return { type: 'select_node', nodeId: args.nodeId };
345
+ case 'open_config':
346
+ requireArg('nodeId');
347
+ return { type: 'config_open', nodeId: args.nodeId };
348
+ case 'zoom_to':
349
+ requireArg('level');
350
+ return { type: 'canvas_zoom_to', level: args.level };
351
+ case 'pan_to':
352
+ requireArg('position');
353
+ return { type: 'canvas_pan_to', position: args.position };
354
+ default:
355
+ return { type: VIEW_TO_COMMAND[action] };
356
+ }
357
+ }
358
+ const BATCH_ITEM_TYPES = [...EXPOSED_COMMAND_TYPES, 'view'];
359
+ const BATCH_SCHEMA = object({
360
+ commands: {
361
+ type: 'array',
362
+ description: 'Commands to run in order. Each item is the argument object of one tool plus a `type` naming that tool (without the prefix), e.g. {"type":"add_node","nodeTypeId":"llm_node"}. Read-only items are allowed but pointless here.',
363
+ items: {
364
+ type: 'object',
365
+ properties: {
366
+ type: { type: 'string', enum: BATCH_ITEM_TYPES, description: 'Tool verb.' }
367
+ },
368
+ required: ['type'],
369
+ additionalProperties: true
370
+ }
371
+ }
372
+ }, ['commands']);
373
+ /** Build the command(s) for one tool verb from validated args. */
374
+ function commandsForVerb(verb, args, viewEnabled) {
375
+ if (verb === 'view') {
376
+ if (!viewEnabled)
377
+ throw new ToolArgumentError('view is not available in this editor');
378
+ return [buildViewCommand(validateToolArgs(VIEW_SCHEMA, args))];
379
+ }
380
+ if (EXPOSED_COMMAND_TYPES.includes(verb)) {
381
+ const record = COMMANDS[verb];
382
+ return [record.build(validateToolArgs(record.inputSchema, args))];
383
+ }
384
+ throw new ToolArgumentError(`unknown command type "${verb}"`);
385
+ }
386
+ function buildBatchCommands(args, viewEnabled) {
387
+ const items = args.commands;
388
+ if (items.length === 0)
389
+ throw new ToolArgumentError('commands must not be empty');
390
+ return items.flatMap((item, i) => {
391
+ const { type, ...rest } = item;
392
+ try {
393
+ return commandsForVerb(type, rest, viewEnabled);
394
+ }
395
+ catch (err) {
396
+ if (err instanceof ToolArgumentError) {
397
+ throw new ToolArgumentError(`commands[${i}] (${String(type)}): ${err.message}`);
398
+ }
399
+ throw err;
400
+ }
401
+ });
402
+ }
403
+ /**
404
+ * Build the descriptor list. Pure; call it as often as you like.
405
+ */
406
+ export function buildToolDescriptors(options = {}) {
407
+ const viewEnabled = options.view ?? true;
408
+ const singles = EXPOSED_COMMAND_TYPES.map((type) => {
409
+ const record = COMMANDS[type];
410
+ return {
411
+ verb: type,
412
+ description: record.description,
413
+ inputSchema: record.inputSchema,
414
+ readOnly: !isMutatingCommand(type),
415
+ toCommands: (args) => [record.build(args)]
416
+ };
417
+ });
418
+ const view = viewEnabled
419
+ ? [
420
+ {
421
+ verb: 'view',
422
+ description: 'Drive the editor view: select a node, open its config panel, or move the canvas viewport (fit, zoom, pan, reset). Changes nothing in the workflow.',
423
+ inputSchema: VIEW_SCHEMA,
424
+ // Classified as the chat panel classifies them: not in the read-only
425
+ // set, so they pass through the gate.
426
+ readOnly: false,
427
+ toCommands: (args) => [buildViewCommand(args)]
428
+ }
429
+ ]
430
+ : [];
431
+ const batch = {
432
+ verb: 'batch',
433
+ description: 'Run several commands as one transaction: all succeed or none apply, and one undo reverts them all. Prefer this over many single calls when building a flow.',
434
+ inputSchema: BATCH_SCHEMA,
435
+ readOnly: false,
436
+ toCommands: (args) => buildBatchCommands(args, viewEnabled)
437
+ };
438
+ return [...singles, ...view, batch];
439
+ }
440
+ /**
441
+ * Summaries for the commands that are not one tool each: the view actions
442
+ * (folded into `view`) and the two excluded verbs, which can still appear in
443
+ * a command list a host asks the gate about.
444
+ */
445
+ const OTHER_SUMMARIES = {
446
+ select_node: (c) => `Select ${c.nodeId}`,
447
+ config_open: (c) => `Open config of ${c.nodeId}`,
448
+ canvas_fit_view: () => 'Fit view',
449
+ canvas_zoom_in: () => 'Zoom in',
450
+ canvas_zoom_out: () => 'Zoom out',
451
+ canvas_zoom_to: (c) => `Zoom to ${c.level}`,
452
+ canvas_pan_to: (c) => `Pan to ${at(c.position)}`,
453
+ canvas_reset_view: () => 'Reset view',
454
+ clear: () => 'Clear the workflow',
455
+ help: () => 'Help'
456
+ };
457
+ /** One line describing a command for a human about to approve it. */
458
+ export function describeCommand(command) {
459
+ const type = command.type;
460
+ if (type in COMMANDS) {
461
+ return COMMANDS[type].summarize(command);
462
+ }
463
+ return OTHER_SUMMARIES[type](command);
464
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * WebMCP adapter — a fake runtime for tests and demos.
3
+ *
4
+ * Browsers without the origin trial have no `document.modelContext`, and CI
5
+ * never will. This records `registerTool` calls, honours the abort signal the
6
+ * way the spec describes, and lets a test or a storybook panel invoke a tool
7
+ * by name. Install it with `attachWebMCP(instance, { modelContext: fake })`
8
+ * or assign it to `document.modelContext` before mounting.
9
+ *
10
+ * @module webmcp/fake
11
+ */
12
+ import type { ModelContextLike, RegisteredToolDefinition, ToolResult } from './types.js';
13
+ export interface FakeModelContext extends ModelContextLike {
14
+ /** Registered tools by name, in registration order. */
15
+ readonly tools: Map<string, RegisteredToolDefinition>;
16
+ /** Invoke a tool by its full name; returns the runtime's result envelope. */
17
+ executeTool(name: string, input?: unknown): Promise<ToolResult>;
18
+ /** Invoke a tool and parse the JSON text it returns. */
19
+ call(name: string, input?: unknown): Promise<Record<string, unknown>>;
20
+ /** Fires after every register / unregister, like the spec's `toolchange`. */
21
+ onToolChange(listener: () => void): () => void;
22
+ }
23
+ export declare function createFakeModelContext(): FakeModelContext;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * WebMCP adapter — a fake runtime for tests and demos.
3
+ *
4
+ * Browsers without the origin trial have no `document.modelContext`, and CI
5
+ * never will. This records `registerTool` calls, honours the abort signal the
6
+ * way the spec describes, and lets a test or a storybook panel invoke a tool
7
+ * by name. Install it with `attachWebMCP(instance, { modelContext: fake })`
8
+ * or assign it to `document.modelContext` before mounting.
9
+ *
10
+ * @module webmcp/fake
11
+ */
12
+ export function createFakeModelContext() {
13
+ const tools = new Map();
14
+ const listeners = new Set();
15
+ const notify = () => listeners.forEach((l) => l());
16
+ return {
17
+ tools,
18
+ registerTool(tool, options) {
19
+ tools.set(tool.name, tool);
20
+ options?.signal?.addEventListener('abort', () => {
21
+ tools.delete(tool.name);
22
+ notify();
23
+ }, { once: true });
24
+ notify();
25
+ return Promise.resolve();
26
+ },
27
+ async executeTool(name, input = {}) {
28
+ const tool = tools.get(name);
29
+ if (!tool)
30
+ throw new Error(`[fake modelContext] no tool named "${name}"`);
31
+ return tool.execute(input);
32
+ },
33
+ async call(name, input = {}) {
34
+ const result = await this.executeTool(name, input);
35
+ return JSON.parse(result.content[0].text);
36
+ },
37
+ onToolChange(listener) {
38
+ listeners.add(listener);
39
+ return () => listeners.delete(listener);
40
+ }
41
+ };
42
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * WebMCP adapter — approval gate.
3
+ *
4
+ * Tool calls that would change the document pass through here before anything
5
+ * runs. The policy is the host's (`WebMCPOptions.approval`); the default is a
6
+ * confirm dialog rendered inside the page, because the WebMCP permission model
7
+ * is about which origins may *see* tools, not about whether a given call may
8
+ * change the user's document. Any agent or extension on the page can call a
9
+ * tool, so the gate must not be weaker than the chat panel's click-to-apply.
10
+ *
11
+ * @module webmcp/gate
12
+ */
13
+ import type { Command } from '../commands/types.js';
14
+ import type { MessagesOverride } from '../messages/index.js';
15
+ import type { WebMCPApproval } from './types.js';
16
+ export interface ApprovalGate {
17
+ /**
18
+ * Ask whether `commands` may run. Resolves `true` to run. Rejects with
19
+ * {@link GateBusyError} when a decision is already pending — the caller
20
+ * turns that into a `busy` tool error instead of stacking dialogs.
21
+ */
22
+ request(commands: Command[]): Promise<boolean>;
23
+ /** True while a decision is pending. */
24
+ readonly busy: boolean;
25
+ /** Dismiss any open dialog (as a rejection) and release resources. */
26
+ dispose(): void;
27
+ }
28
+ /** A second mutating call arrived while a decision was pending. */
29
+ export declare class GateBusyError extends Error {
30
+ constructor();
31
+ }
32
+ export interface CreateGateOptions {
33
+ /** Where the built-in dialog mounts. Default `document.body`. */
34
+ container?: HTMLElement;
35
+ /** Name shown in the dialog title; read at request time. */
36
+ editorName: () => string;
37
+ /** Strings for the dialog, as a partial override or a getter for one. */
38
+ messages?: MessagesOverride | (() => MessagesOverride);
39
+ }
40
+ export declare function createApprovalGate(approval: WebMCPApproval, options: CreateGateOptions): ApprovalGate;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * WebMCP adapter — approval gate.
3
+ *
4
+ * Tool calls that would change the document pass through here before anything
5
+ * runs. The policy is the host's (`WebMCPOptions.approval`); the default is a
6
+ * confirm dialog rendered inside the page, because the WebMCP permission model
7
+ * is about which origins may *see* tools, not about whether a given call may
8
+ * change the user's document. Any agent or extension on the page can call a
9
+ * tool, so the gate must not be weaker than the chat panel's click-to-apply.
10
+ *
11
+ * @module webmcp/gate
12
+ */
13
+ import { mount, unmount } from 'svelte';
14
+ import { defaultMessages, mergeMessages, messagesContext } from '../messages/index.js';
15
+ import { describeCommand } from './descriptors.js';
16
+ import WebMCPConfirm from './WebMCPConfirm.svelte';
17
+ /** A second mutating call arrived while a decision was pending. */
18
+ export class GateBusyError extends Error {
19
+ constructor() {
20
+ super('A previous change is still waiting for approval');
21
+ this.name = 'GateBusyError';
22
+ }
23
+ }
24
+ export function createApprovalGate(approval, options) {
25
+ let pending = false;
26
+ let dismiss = null;
27
+ // The dialog mounts outside any component tree, so it gets its messages
28
+ // through the same context the root component would have provided. Read
29
+ // per access so a getter-driven locale switch shows on the next dialog.
30
+ const messages = () => {
31
+ const override = options.messages;
32
+ return mergeMessages(defaultMessages, typeof override === 'function' ? override() : override);
33
+ };
34
+ async function decide(commands) {
35
+ if (approval === 'auto')
36
+ return true;
37
+ if (typeof approval === 'function')
38
+ return approval(commands);
39
+ return confirmInPage(commands);
40
+ }
41
+ function confirmInPage(commands) {
42
+ const target = options.container ?? (typeof document !== 'undefined' ? document.body : null);
43
+ if (!target) {
44
+ // No DOM to ask in: refuse rather than silently apply.
45
+ return Promise.resolve(false);
46
+ }
47
+ return new Promise((resolve) => {
48
+ let settled = false;
49
+ const host = document.createElement('div');
50
+ host.className = 'fd-webmcp-confirm-host';
51
+ target.appendChild(host);
52
+ const finish = (approved) => {
53
+ if (settled)
54
+ return;
55
+ settled = true;
56
+ dismiss = null;
57
+ void unmount(component);
58
+ host.remove();
59
+ resolve(approved);
60
+ };
61
+ const component = mount(WebMCPConfirm, {
62
+ target: host,
63
+ context: messagesContext(messages),
64
+ props: {
65
+ editorName: options.editorName(),
66
+ lines: commands.map(describeCommand),
67
+ onResolve: finish
68
+ }
69
+ });
70
+ dismiss = () => finish(false);
71
+ });
72
+ }
73
+ return {
74
+ get busy() {
75
+ return pending;
76
+ },
77
+ async request(commands) {
78
+ if (pending)
79
+ throw new GateBusyError();
80
+ pending = true;
81
+ try {
82
+ return await decide(commands);
83
+ }
84
+ finally {
85
+ pending = false;
86
+ }
87
+ },
88
+ dispose() {
89
+ dismiss?.();
90
+ }
91
+ };
92
+ }