@flowdrop/flowdrop 2.4.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 (57) hide show
  1. package/CHANGELOG.md +49 -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/config/defaultPortConfig.js +27 -9
  16. package/dist/messages/context.d.ts +6 -0
  17. package/dist/messages/context.js +8 -0
  18. package/dist/messages/defaults.d.ts +45 -2
  19. package/dist/messages/defaults.js +36 -3
  20. package/dist/messages/index.d.ts +1 -1
  21. package/dist/messages/index.js +1 -1
  22. package/dist/openapi/v1/openapi.yaml +14 -1
  23. package/dist/schemas/v1/workflow.schema.json +9 -2
  24. package/dist/stores/instanceContainer.svelte.d.ts +26 -0
  25. package/dist/stores/instanceContainer.svelte.js +24 -0
  26. package/dist/stories/WebMCPFakeAgent.svelte +229 -0
  27. package/dist/stories/WebMCPFakeAgent.svelte.d.ts +10 -0
  28. package/dist/styles/base.css +4 -2
  29. package/dist/styles/tokens.css +20 -0
  30. package/dist/svelte-app.d.ts +20 -0
  31. package/dist/svelte-app.js +49 -1
  32. package/dist/types/index.d.ts +26 -1
  33. package/dist/utils/focus.d.ts +18 -0
  34. package/dist/utils/focus.js +24 -0
  35. package/dist/utils/whenWorkflowLoaded.svelte.d.ts +17 -0
  36. package/dist/utils/whenWorkflowLoaded.svelte.js +42 -0
  37. package/dist/utils/workflowInterface.d.ts +47 -3
  38. package/dist/utils/workflowInterface.js +84 -9
  39. package/dist/webmcp/WebMCP.stories.svelte +101 -0
  40. package/dist/webmcp/WebMCP.stories.svelte.d.ts +18 -0
  41. package/dist/webmcp/WebMCPConfirm.svelte +170 -0
  42. package/dist/webmcp/WebMCPConfirm.svelte.d.ts +11 -0
  43. package/dist/webmcp/descriptors.d.ts +59 -0
  44. package/dist/webmcp/descriptors.js +464 -0
  45. package/dist/webmcp/fake.d.ts +23 -0
  46. package/dist/webmcp/fake.js +42 -0
  47. package/dist/webmcp/gate.d.ts +40 -0
  48. package/dist/webmcp/gate.js +92 -0
  49. package/dist/webmcp/index.d.ts +34 -0
  50. package/dist/webmcp/index.js +31 -0
  51. package/dist/webmcp/register.d.ts +33 -0
  52. package/dist/webmcp/register.js +267 -0
  53. package/dist/webmcp/types.d.ts +166 -0
  54. package/dist/webmcp/types.js +23 -0
  55. package/dist/webmcp/validate.d.ts +32 -0
  56. package/dist/webmcp/validate.js +118 -0
  57. package/package.json +6 -1
@@ -0,0 +1,34 @@
1
+ /**
2
+ * FlowDrop WebMCP adapter — `@flowdrop/flowdrop/webmcp`
3
+ *
4
+ * Exposes the editor's typed commands as WebMCP **editor tools** that a
5
+ * browser-resident agent (Chrome's, Edge's, Brave Leo, ChatGPT Desktop, …)
6
+ * can discover on the page and call: add and connect nodes, set config, list
7
+ * and inspect, undo. Reads run at once; anything that changes the workflow
8
+ * waits for the person at the keyboard unless the host says otherwise.
9
+ *
10
+ * These are tools for *editing* a workflow in the browser. They are unrelated
11
+ * to the tools a running workflow hands to an LLM node.
12
+ *
13
+ * @module webmcp
14
+ *
15
+ * @example Svelte host
16
+ * ```ts
17
+ * import { attachWebMCP } from '@flowdrop/flowdrop/webmcp';
18
+ * const handle = attachWebMCP(app.instance, { nodeTypes });
19
+ * // later: handle?.detach() — or let instance.destroy() do it
20
+ * ```
21
+ *
22
+ * @example Vanilla / Drupal host
23
+ * ```ts
24
+ * const app = await mountFlowDropApp(el, { endpointConfig, webmcp: true });
25
+ * ```
26
+ */
27
+ export { attachWebMCP, detectModelContext, DEFAULT_PREFIX } from './register.js';
28
+ export { buildToolDescriptors, describeCommand, EXPOSED_COMMAND_TYPES, VIEW_COMMAND_TYPES, EXCLUDED_COMMAND_TYPES, COMPOSITE_VERBS } from './descriptors.js';
29
+ export type { BuildDescriptorsOptions } from './descriptors.js';
30
+ export { validateToolArgs, VALIDATOR_KEYWORDS } from './validate.js';
31
+ export { ToolArgumentError } from './types.js';
32
+ export { createFakeModelContext } from './fake.js';
33
+ export type { FakeModelContext } from './fake.js';
34
+ export type { ToolDescriptor, ToolInputSchema, ToolSchemaProperty, ToolResult, ToolExecuteOptions, RegisteredToolDefinition, RegisterToolOptions, ModelContextLike, WebMCPApproval, WebMCPOptions, WebMCPMountOptions, WebMCPHandle } from './types.js';
@@ -0,0 +1,31 @@
1
+ /**
2
+ * FlowDrop WebMCP adapter — `@flowdrop/flowdrop/webmcp`
3
+ *
4
+ * Exposes the editor's typed commands as WebMCP **editor tools** that a
5
+ * browser-resident agent (Chrome's, Edge's, Brave Leo, ChatGPT Desktop, …)
6
+ * can discover on the page and call: add and connect nodes, set config, list
7
+ * and inspect, undo. Reads run at once; anything that changes the workflow
8
+ * waits for the person at the keyboard unless the host says otherwise.
9
+ *
10
+ * These are tools for *editing* a workflow in the browser. They are unrelated
11
+ * to the tools a running workflow hands to an LLM node.
12
+ *
13
+ * @module webmcp
14
+ *
15
+ * @example Svelte host
16
+ * ```ts
17
+ * import { attachWebMCP } from '@flowdrop/flowdrop/webmcp';
18
+ * const handle = attachWebMCP(app.instance, { nodeTypes });
19
+ * // later: handle?.detach() — or let instance.destroy() do it
20
+ * ```
21
+ *
22
+ * @example Vanilla / Drupal host
23
+ * ```ts
24
+ * const app = await mountFlowDropApp(el, { endpointConfig, webmcp: true });
25
+ * ```
26
+ */
27
+ export { attachWebMCP, detectModelContext, DEFAULT_PREFIX } from './register.js';
28
+ export { buildToolDescriptors, describeCommand, EXPOSED_COMMAND_TYPES, VIEW_COMMAND_TYPES, EXCLUDED_COMMAND_TYPES, COMPOSITE_VERBS } from './descriptors.js';
29
+ export { validateToolArgs, VALIDATOR_KEYWORDS } from './validate.js';
30
+ export { ToolArgumentError } from './types.js';
31
+ export { createFakeModelContext } from './fake.js';
@@ -0,0 +1,33 @@
1
+ /**
2
+ * WebMCP adapter — registration.
3
+ *
4
+ * The only file that touches the runtime (`document.modelContext`, falling
5
+ * back to `navigator.modelContext`). Builds the descriptors, wraps each in an
6
+ * `execute` that validates → maps to commands → gates → runs one
7
+ * `executeBatch` transaction, and registers the lot under one AbortSignal so
8
+ * detaching is a single `abort()`.
9
+ *
10
+ * @module webmcp/register
11
+ */
12
+ import type { FlowDropInstance } from '../stores/instanceContainer.svelte.js';
13
+ import { type ModelContextLike, type WebMCPHandle, type WebMCPOptions } from './types.js';
14
+ export declare const DEFAULT_PREFIX = "flowdrop";
15
+ /**
16
+ * Find the WebMCP runtime on this page, or `null` when the browser has none.
17
+ * Structural: anything with a callable `registerTool` counts.
18
+ */
19
+ export declare function detectModelContext(): ModelContextLike | null;
20
+ /**
21
+ * Register the editor's commands as WebMCP tools for `instance`.
22
+ *
23
+ * Returns `null` — with no console output — when the page has no WebMCP
24
+ * runtime, so hosts can call it unconditionally. Throws when the prefix is
25
+ * already registered on this runtime (two editors on one page need distinct
26
+ * prefixes).
27
+ *
28
+ * Registration settles asynchronously: `handle.tools` lists the tools the
29
+ * runtime has accepted so far and `handle.ready` resolves when every
30
+ * registration has settled. The registration is torn down by
31
+ * `handle.detach()` or automatically when `instance.destroy()` runs.
32
+ */
33
+ export declare function attachWebMCP(instance: FlowDropInstance, options?: WebMCPOptions): WebMCPHandle | null;
@@ -0,0 +1,267 @@
1
+ /**
2
+ * WebMCP adapter — registration.
3
+ *
4
+ * The only file that touches the runtime (`document.modelContext`, falling
5
+ * back to `navigator.modelContext`). Builds the descriptors, wraps each in an
6
+ * `execute` that validates → maps to commands → gates → runs one
7
+ * `executeBatch` transaction, and registers the lot under one AbortSignal so
8
+ * detaching is a single `abort()`.
9
+ *
10
+ * @module webmcp/register
11
+ */
12
+ import { executeBatch } from '../commands/batch.js';
13
+ import { createStoreCommandContext } from '../commands/storeIntegration.svelte.js';
14
+ import { isLayoutCommand, isMutatingCommand, isViewCommand } from '../chat/commandClassifier.js';
15
+ import { getBehaviorSettings } from '../stores/settingsStore.svelte.js';
16
+ import { logger } from '../utils/logger.js';
17
+ import { buildToolDescriptors } from './descriptors.js';
18
+ import { validateToolArgs } from './validate.js';
19
+ import { createApprovalGate, GateBusyError } from './gate.js';
20
+ import { ToolArgumentError } from './types.js';
21
+ export const DEFAULT_PREFIX = 'flowdrop';
22
+ /** Wording shared with the chat panel's CommandPreview (issue #36). */
23
+ const LAYOUT_SKIPPED = 'Skipped — AI layout changes are disabled in Settings';
24
+ // ============================================================================
25
+ // Runtime detection
26
+ // ============================================================================
27
+ /**
28
+ * Find the WebMCP runtime on this page, or `null` when the browser has none.
29
+ * Structural: anything with a callable `registerTool` counts.
30
+ */
31
+ export function detectModelContext() {
32
+ if (typeof document === 'undefined')
33
+ return null;
34
+ const candidates = [
35
+ document.modelContext,
36
+ typeof navigator !== 'undefined'
37
+ ? navigator.modelContext
38
+ : undefined
39
+ ];
40
+ for (const c of candidates) {
41
+ if (c && typeof c.registerTool === 'function') {
42
+ return c;
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+ // ============================================================================
48
+ // Prefix registry (D2) — one registration per prefix per runtime
49
+ // ============================================================================
50
+ const claimedPrefixes = new WeakMap();
51
+ function claimPrefix(runtime, prefix) {
52
+ let set = claimedPrefixes.get(runtime);
53
+ if (!set) {
54
+ set = new Set();
55
+ claimedPrefixes.set(runtime, set);
56
+ }
57
+ if (set.has(prefix)) {
58
+ throw new Error(`[flowdrop] WebMCP tools with prefix "${prefix}" are already registered on this page. ` +
59
+ `Pass a distinct \`prefix\` for each editor instance.`);
60
+ }
61
+ set.add(prefix);
62
+ }
63
+ function releasePrefix(runtime, prefix) {
64
+ claimedPrefixes.get(runtime)?.delete(prefix);
65
+ }
66
+ // ============================================================================
67
+ // Result formatting
68
+ // ============================================================================
69
+ function text(payload, isError = false) {
70
+ return {
71
+ content: [{ type: 'text', text: JSON.stringify(payload) }],
72
+ ...(isError ? { isError: true } : {})
73
+ };
74
+ }
75
+ function errorResult(code, message) {
76
+ return text({ ok: false, code, error: message }, true);
77
+ }
78
+ function stripResult(result) {
79
+ if (result.ok) {
80
+ const out = { ok: true, message: result.message };
81
+ if (result.data !== undefined)
82
+ out.data = result.data;
83
+ if (result.uiActionPending)
84
+ out.uiActionPending = true;
85
+ return out;
86
+ }
87
+ return { ok: false, code: result.code, error: result.error };
88
+ }
89
+ /**
90
+ * The gate exists because any agent on the page can alter the user's
91
+ * document. A command that only moves the view — selection, a panel, the
92
+ * viewport — alters nothing the user would need to undo, so it runs unasked;
93
+ * `undo` and `redo` change the document and stay gated. A batch is gated as a
94
+ * whole when any of its items is.
95
+ */
96
+ function needsApproval(commands) {
97
+ return commands.some((c) => isMutatingCommand(c.type) && !isViewCommand(c.type));
98
+ }
99
+ // ============================================================================
100
+ // attach
101
+ // ============================================================================
102
+ /**
103
+ * Register the editor's commands as WebMCP tools for `instance`.
104
+ *
105
+ * Returns `null` — with no console output — when the page has no WebMCP
106
+ * runtime, so hosts can call it unconditionally. Throws when the prefix is
107
+ * already registered on this runtime (two editors on one page need distinct
108
+ * prefixes).
109
+ *
110
+ * Registration settles asynchronously: `handle.tools` lists the tools the
111
+ * runtime has accepted so far and `handle.ready` resolves when every
112
+ * registration has settled. The registration is torn down by
113
+ * `handle.detach()` or automatically when `instance.destroy()` runs.
114
+ */
115
+ export function attachWebMCP(instance, options = {}) {
116
+ const detected = options.modelContext ?? detectModelContext();
117
+ if (!detected)
118
+ return null;
119
+ const runtime = detected;
120
+ const prefix = options.prefix ?? DEFAULT_PREFIX;
121
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(prefix)) {
122
+ throw new Error(`[flowdrop] Invalid WebMCP prefix "${prefix}"`);
123
+ }
124
+ claimPrefix(runtime, prefix);
125
+ const nodeTypes = () => {
126
+ const source = options.nodeTypes;
127
+ if (source === undefined)
128
+ return instance.nodeTypes.current;
129
+ return typeof source === 'function' ? source() : source;
130
+ };
131
+ const editorName = () => instance.workflow.current?.name ?? instance.id;
132
+ const gate = createApprovalGate(options.approval ?? 'confirm', {
133
+ container: options.container,
134
+ editorName,
135
+ messages: options.messages
136
+ });
137
+ const controller = new AbortController();
138
+ const descriptors = buildToolDescriptors({ view: Boolean(options.onUIAction) });
139
+ const names = [];
140
+ let attached = true;
141
+ // ---- execute ------------------------------------------------------------
142
+ async function run(descriptor, input) {
143
+ if (!attached)
144
+ return errorResult('DETACHED', 'This editor is no longer available');
145
+ let commands;
146
+ try {
147
+ commands = descriptor.toCommands(validateToolArgs(descriptor.inputSchema, input));
148
+ }
149
+ catch (err) {
150
+ if (err instanceof ToolArgumentError)
151
+ return errorResult('INVALID_ARGUMENTS', err.message);
152
+ throw err;
153
+ }
154
+ // D4: honour the layout opt-out with the chat panel's wording. A skip is
155
+ // not a failure; the rest of a batch still applies.
156
+ const skipped = [];
157
+ if (!getBehaviorSettings().chatAllowLayoutChanges) {
158
+ commands = commands.filter((c) => {
159
+ if (isLayoutCommand(c.type)) {
160
+ skipped.push(c);
161
+ return false;
162
+ }
163
+ return true;
164
+ });
165
+ }
166
+ if (commands.length === 0) {
167
+ return text({
168
+ ok: true,
169
+ results: [],
170
+ skipped: skipped.map((c) => ({ type: c.type, reason: LAYOUT_SKIPPED })),
171
+ completedCount: 0,
172
+ totalCount: 0
173
+ });
174
+ }
175
+ const context = createStoreCommandContext(nodeTypes(), options.onUIAction, instance);
176
+ if (!context)
177
+ return errorResult('NO_WORKFLOW', 'No workflow is loaded in this editor');
178
+ // D3: reads and view changes run; document changes wait for the gate.
179
+ if (needsApproval(commands)) {
180
+ let approved;
181
+ try {
182
+ approved = await gate.request(commands);
183
+ }
184
+ catch (err) {
185
+ if (err instanceof GateBusyError)
186
+ return errorResult('BUSY', err.message);
187
+ throw err;
188
+ }
189
+ if (!approved)
190
+ return errorResult('REJECTED', 'The user rejected the change');
191
+ if (!attached)
192
+ return errorResult('DETACHED', 'This editor is no longer available');
193
+ }
194
+ // Every call is one transaction and one undo step, like the chat panel.
195
+ const batch = executeBatch(commands, context);
196
+ if (commands.length === 1 && descriptor.verb !== 'batch' && skipped.length === 0) {
197
+ const only = batch.results[0];
198
+ return text(stripResult(only), !only.ok);
199
+ }
200
+ return text({
201
+ ok: batch.ok,
202
+ results: batch.results.map(stripResult),
203
+ ...(skipped.length > 0
204
+ ? { skipped: skipped.map((c) => ({ type: c.type, reason: LAYOUT_SKIPPED })) }
205
+ : {}),
206
+ completedCount: batch.completedCount,
207
+ totalCount: batch.totalCount,
208
+ ...(batch.ok ? {} : { error: batch.error, rolledBack: true })
209
+ }, !batch.ok);
210
+ }
211
+ // ---- register -----------------------------------------------------------
212
+ const nameSuffix = ` Editor: "${editorName()}".`;
213
+ async function register(descriptor) {
214
+ const name = `${prefix}_${descriptor.verb}`;
215
+ const tool = {
216
+ name,
217
+ description: descriptor.description + nameSuffix,
218
+ inputSchema: descriptor.inputSchema,
219
+ annotations: { readOnlyHint: descriptor.readOnly },
220
+ execute: (input) => run(descriptor, input)
221
+ };
222
+ try {
223
+ // The spec returns a promise that rejects when the runtime refuses the
224
+ // tool; pre-spec runtimes return nothing, which `await` takes as accepted.
225
+ await runtime.registerTool(tool, { signal: controller.signal });
226
+ }
227
+ catch (err) {
228
+ logger.warn(`WebMCP: the runtime refused tool "${name}":`, err instanceof Error ? err.message : err);
229
+ return;
230
+ }
231
+ if (attached)
232
+ names.push(name);
233
+ }
234
+ const ready = Promise.all(descriptors.map(register)).then(() => undefined);
235
+ // ---- detach -------------------------------------------------------------
236
+ function detach() {
237
+ if (!attached)
238
+ return;
239
+ attached = false;
240
+ unsubscribeDestroy();
241
+ gate.dispose();
242
+ controller.abort();
243
+ if (typeof runtime.unregisterTool === 'function') {
244
+ for (const name of names) {
245
+ try {
246
+ runtime.unregisterTool(name);
247
+ }
248
+ catch {
249
+ // Pre-spec runtime quirks are not ours to surface.
250
+ }
251
+ }
252
+ }
253
+ releasePrefix(runtime, prefix);
254
+ }
255
+ // Detach when the instance goes away.
256
+ const unsubscribeDestroy = instance.onDestroy(detach);
257
+ return {
258
+ get tools() {
259
+ return names;
260
+ },
261
+ ready,
262
+ get attached() {
263
+ return attached;
264
+ },
265
+ detach
266
+ };
267
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * WebMCP adapter — types.
3
+ *
4
+ * The editor's typed command union (`commands/types.ts`) exposed as WebMCP
5
+ * "editor tools" that a browser-resident agent can discover and call. These
6
+ * are tools *for editing a workflow in the browser*; they are unrelated to the
7
+ * tools a running workflow hands to an LLM node.
8
+ *
9
+ * Spec pinned 2026-09-02 (webmachinelearning/webmcp): `document.modelContext`
10
+ * with `registerTool(tool, { signal, exposedTo })`, `execute(input, { signal })`
11
+ * returning a promise, `annotations.readOnlyHint`, and a `toolchange` event.
12
+ * The adapter feature-detects against {@link ModelContextLike} — the minimal
13
+ * structural shape it needs — and pins nothing else.
14
+ *
15
+ * @module webmcp/types
16
+ */
17
+ import type { Command, UIAction } from '../commands/types.js';
18
+ import type { NodeMetadata } from '../types/index.js';
19
+ import type { MessagesOverride } from '../messages/types.js';
20
+ /** One property of a tool's input schema. */
21
+ export interface ToolSchemaProperty {
22
+ type?: 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array';
23
+ description?: string;
24
+ enum?: readonly string[];
25
+ properties?: Record<string, ToolSchemaProperty>;
26
+ required?: readonly string[];
27
+ additionalProperties?: boolean;
28
+ items?: ToolSchemaProperty;
29
+ /** `value` in `set_config` accepts several primitive shapes. */
30
+ anyOf?: readonly ToolSchemaProperty[];
31
+ minimum?: number;
32
+ maximum?: number;
33
+ }
34
+ /** A tool's input schema: always an object with `additionalProperties: false`. */
35
+ export interface ToolInputSchema {
36
+ type: 'object';
37
+ properties: Record<string, ToolSchemaProperty>;
38
+ required?: readonly string[];
39
+ additionalProperties: false;
40
+ }
41
+ /**
42
+ * One editor tool, before registration. Pure data plus a pure mapping from
43
+ * validated arguments to the commands it runs — no DOM, no Svelte, so the same
44
+ * records can back a server-side MCP transport later.
45
+ */
46
+ export interface ToolDescriptor {
47
+ /** Verb part of the tool name; registered as `${prefix}_${verb}`. */
48
+ verb: string;
49
+ description: string;
50
+ inputSchema: ToolInputSchema;
51
+ /** True when every command the tool can produce is read-only. */
52
+ readOnly: boolean;
53
+ /**
54
+ * Map already-validated arguments to the commands to execute. Throws a
55
+ * {@link ToolArgumentError} for anything the schema validator cannot express.
56
+ */
57
+ toCommands(args: Record<string, unknown>): Command[];
58
+ }
59
+ /** Thrown by {@link ToolDescriptor.toCommands} and the argument validator. */
60
+ export declare class ToolArgumentError extends Error {
61
+ constructor(message: string);
62
+ }
63
+ /** What `execute` receives from the runtime. */
64
+ export interface ToolExecuteOptions {
65
+ signal?: AbortSignal;
66
+ }
67
+ /** The result shape we return: MCP-style content blocks with JSON in `text`. */
68
+ export interface ToolResult {
69
+ content: Array<{
70
+ type: 'text';
71
+ text: string;
72
+ }>;
73
+ /** Mirrors MCP: set when the call failed. */
74
+ isError?: boolean;
75
+ }
76
+ /** A tool as handed to `registerTool`. */
77
+ export interface RegisteredToolDefinition {
78
+ name: string;
79
+ description: string;
80
+ inputSchema: ToolInputSchema;
81
+ annotations?: {
82
+ readOnlyHint?: boolean;
83
+ untrustedContentHint?: boolean;
84
+ };
85
+ execute(input: unknown, options?: ToolExecuteOptions): Promise<ToolResult>;
86
+ }
87
+ /** Options accepted by `registerTool`. Only `signal` is ever passed. */
88
+ export interface RegisterToolOptions {
89
+ signal?: AbortSignal;
90
+ exposedTo?: string[];
91
+ }
92
+ /**
93
+ * The minimal structural type the adapter feature-detects against.
94
+ * `document.modelContext` (spec) and the earlier `navigator.modelContext`
95
+ * both satisfy it; so does the fake used in tests.
96
+ */
97
+ export interface ModelContextLike {
98
+ registerTool(tool: RegisteredToolDefinition, options?: RegisterToolOptions): unknown;
99
+ /** Pre-spec runtimes only; called when present, never relied upon. */
100
+ unregisterTool?(name: string): unknown;
101
+ }
102
+ /**
103
+ * Approval policy for mutating tools.
104
+ *
105
+ * - `'confirm'` (default): a confirm dialog rendered inside the page.
106
+ * - `'auto'`: run without asking. Only for hosts that already trust every
107
+ * agent on the page (kiosks, tests).
108
+ * - A callback receiving the commands about to run; resolve `true` to run.
109
+ */
110
+ export type WebMCPApproval = 'confirm' | 'auto' | ((commands: Command[]) => Promise<boolean>);
111
+ export interface WebMCPOptions {
112
+ /**
113
+ * Node type definitions the tools resolve `add_node` and `list_types`
114
+ * against, as an array or a getter that returns the current list. Defaults
115
+ * to the instance's own list (`instance.nodeTypes`), which the editor fills
116
+ * as its fetch lands — pass this only when the host knows better.
117
+ */
118
+ nodeTypes?: NodeMetadata[] | (() => NodeMetadata[]);
119
+ /** Tool name prefix. Default `flowdrop`. Must be unique per document. */
120
+ prefix?: string;
121
+ /** Approval policy for mutating tools. Default `'confirm'`. */
122
+ approval?: WebMCPApproval;
123
+ /**
124
+ * Handler for `view` actions (select node, open config, canvas viewport).
125
+ * When omitted the `view` tool is not registered at all — there is nothing
126
+ * it could do.
127
+ */
128
+ onUIAction?: (action: UIAction) => void;
129
+ /** Where the built-in confirm dialog mounts. Default `document.body`. */
130
+ container?: HTMLElement;
131
+ /**
132
+ * Strings for the built-in confirm dialog, in the shape of the library's
133
+ * `messages` prop: a partial override of the defaults, or a getter for one
134
+ * when an i18n library drives the locale. English when omitted.
135
+ */
136
+ messages?: MessagesOverride | (() => MessagesOverride);
137
+ /**
138
+ * Runtime override. Default: `document.modelContext`, then
139
+ * `navigator.modelContext`. Tests pass a fake here.
140
+ */
141
+ modelContext?: ModelContextLike;
142
+ }
143
+ /**
144
+ * The `webmcp` mount option of `mountFlowDropApp`. Node types default to the
145
+ * mount's `nodes` option or the ones the editor fetches; there is no UI-action
146
+ * handler on this path, so the `view` tool is not registered.
147
+ */
148
+ export type WebMCPMountOptions = Omit<WebMCPOptions, 'nodeTypes' | 'onUIAction' | 'modelContext'> & {
149
+ nodeTypes?: WebMCPOptions['nodeTypes'];
150
+ };
151
+ /** Returned by `attachWebMCP`. */
152
+ export interface WebMCPHandle {
153
+ /**
154
+ * Fully qualified names of the tools the runtime accepted. Registration is
155
+ * asynchronous in the spec, so this fills in as registrations settle; a
156
+ * tool the runtime refused is warned about once and never listed. Await
157
+ * {@link ready} for the final list.
158
+ */
159
+ readonly tools: readonly string[];
160
+ /** Resolves once every registration has settled — accepted or refused. */
161
+ readonly ready: Promise<void>;
162
+ /** False after `detach()` (or after the instance was destroyed). */
163
+ readonly attached: boolean;
164
+ /** Abort the registration, remove the tools, free the prefix. Idempotent. */
165
+ detach(): void;
166
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * WebMCP adapter — types.
3
+ *
4
+ * The editor's typed command union (`commands/types.ts`) exposed as WebMCP
5
+ * "editor tools" that a browser-resident agent can discover and call. These
6
+ * are tools *for editing a workflow in the browser*; they are unrelated to the
7
+ * tools a running workflow hands to an LLM node.
8
+ *
9
+ * Spec pinned 2026-09-02 (webmachinelearning/webmcp): `document.modelContext`
10
+ * with `registerTool(tool, { signal, exposedTo })`, `execute(input, { signal })`
11
+ * returning a promise, `annotations.readOnlyHint`, and a `toolchange` event.
12
+ * The adapter feature-detects against {@link ModelContextLike} — the minimal
13
+ * structural shape it needs — and pins nothing else.
14
+ *
15
+ * @module webmcp/types
16
+ */
17
+ /** Thrown by {@link ToolDescriptor.toCommands} and the argument validator. */
18
+ export class ToolArgumentError extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = 'ToolArgumentError';
22
+ }
23
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * WebMCP adapter — argument validation.
3
+ *
4
+ * A hand-written validator for exactly the JSON Schema subset the tool
5
+ * descriptors use. That subset is `ToolSchemaProperty` in `./types.ts`: the
6
+ * type is the contract, and this file must understand every keyword it
7
+ * declares — `VALIDATOR_KEYWORDS` lists them, and a test in
8
+ * `tests/unit/webmcp` walks every schema and fails when a schema uses a key
9
+ * this set lacks. Adding a keyword therefore means adding it in three places:
10
+ * the type, the check below, and the set. No dependency is taken for this;
11
+ * the schemas are small, hand-written, and never come from outside the
12
+ * library.
13
+ *
14
+ * The runtime is supposed to validate too. Chrome's behaviour there is not
15
+ * something to lean on yet, and validating here keeps behaviour identical
16
+ * across runtimes and against the fake used in tests.
17
+ *
18
+ * @module webmcp/validate
19
+ */
20
+ import { type ToolInputSchema, type ToolSchemaProperty } from './types.js';
21
+ /**
22
+ * Every schema keyword the validator understands. `description` is listed
23
+ * because it is a keyword schemas use, even though it needs no check.
24
+ */
25
+ export declare const VALIDATOR_KEYWORDS: ReadonlySet<keyof ToolSchemaProperty>;
26
+ /**
27
+ * Validate raw tool input against a tool's schema and return it typed as an
28
+ * argument object.
29
+ *
30
+ * @throws ToolArgumentError
31
+ */
32
+ export declare function validateToolArgs(schema: ToolInputSchema, input: unknown): Record<string, unknown>;