@dudko.dev/agent-web 0.0.27 → 0.0.29
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/README.md +39 -1
- package/dist/agent-web.js +111 -98
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-V7COB2EA.js → chunk-CPSDKXO6.js} +5 -2
- package/dist/chunk-CPSDKXO6.js.map +1 -0
- package/dist/index.cjs +496 -63
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +349 -24
- package/dist/index.d.ts +349 -24
- package/dist/index.js +490 -63
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +3 -1
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.js +1 -1
- package/dist/types-DwSMj_Xs.d.cts +21 -0
- package/dist/types-DwSMj_Xs.d.ts +21 -0
- package/dist/webmcp.cjs +208 -0
- package/dist/webmcp.cjs.map +1 -0
- package/dist/webmcp.d.cts +131 -0
- package/dist/webmcp.d.ts +131 -0
- package/dist/webmcp.js +179 -0
- package/dist/webmcp.js.map +1 -0
- package/package.json +19 -9
- package/dist/chunk-V7COB2EA.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webmcp/index.ts"],"sourcesContent":["import { asSchema, jsonSchema, tool, type Tool, type ToolSet } from 'ai'\nimport type { AgentTool, AgentToolSet } from '../tools/types.js'\n\n/**\n * WebMCP — the browser's tool API for pages (https://webmachinelearning.github.io/webmcp/).\n *\n * A page registers named, typed tools with `document.modelContext.registerTool(tool, { signal })`\n * and a browser's agent (Chrome's origin trial, Edge, an extension, an in-page agent) can discover\n * and call them. This module bridges that API and an agent's `ToolSet`, in both directions:\n *\n * - {@link registerWebMcpTools} PUBLISHES a ToolSet to the page's model context, so the tools\n * an in-page agent uses can also be driven by any agent of the browser — one definition, two\n * consumers.\n * - {@link connectWebMcp} CONSUMES the tools a page has registered (its own, or another\n * script's) as an agent ToolSet.\n *\n * Browser-only, no extra dependency, and a no-op where the browser has no WebMCP. Two API\n * generations are handled: the current one on `document.modelContext` (registration returns a\n * promise, a tool is withdrawn by aborting its signal) and Chrome's early preview on\n * `navigator.modelContext` (`unregisterTool(name)`).\n */\n\n/** What WebMCP registers: a tool a browser agent can call. */\nexport interface WebMcpToolDefinition {\n name: string\n title: string\n description: string\n inputSchema: Record<string, unknown>\n annotations: { readOnlyHint: boolean; consequentialHint?: boolean }\n execute: (input: Record<string, unknown>, options?: { signal?: AbortSignal }) => Promise<unknown>\n}\n\n/** What a page's `getTools()` returns for one tool. */\nexport interface RegisteredWebMcpTool {\n name: string\n description?: string\n /** The specification stringifies it; an object is accepted too. */\n inputSchema?: string | Record<string, unknown>\n annotations?: { readOnlyHint?: boolean }\n}\n\n/** The parts of `ModelContext` this module uses. */\nexport interface ModelContextLike {\n registerTool: (tool: WebMcpToolDefinition, options?: { signal?: AbortSignal }) => unknown\n unregisterTool?: (name: string) => unknown\n getTools?: (options?: unknown) => Promise<RegisteredWebMcpTool[]>\n executeTool?: (\n tool: RegisteredWebMcpTool,\n input?: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n ) => Promise<unknown>\n addEventListener?: (type: string, listener: () => void) => void\n removeEventListener?: (type: string, listener: () => void) => void\n}\n\n/** The page's model context, wherever this browser puts it; undefined when there is none. */\nexport const findModelContext = (\n doc: { modelContext?: unknown } | undefined = typeof document !== 'undefined'\n ? (document as unknown as { modelContext?: unknown })\n : undefined,\n): ModelContextLike | undefined => {\n const nav =\n typeof navigator !== 'undefined' ? (navigator as { modelContext?: unknown }) : undefined\n return [doc?.modelContext, nav?.modelContext].find(\n (c): c is ModelContextLike =>\n !!c && typeof (c as { registerTool?: unknown }).registerTool === 'function',\n )\n}\n\nexport const isWebMcpAvailable = (): boolean => findModelContext() !== undefined\n\nexport interface WebMcpPublishOptions {\n /**\n * Prepended to every tool name. WebMCP tools of a page share one namespace with whatever else\n * the page (or an extension) registers, so a prefix such as `myapp_` avoids collisions. Names may\n * contain ASCII letters, digits, `_`, `-` and `.`, at most 128 characters.\n */\n prefix?: string\n /** Publish only these tools (by their name in the ToolSet). */\n only?: string[]\n /** Never publish these tools. */\n except?: string[]\n /** Tools whose effect is significant or hard to reverse: annotated `consequentialHint`. */\n consequential?: string[]\n /** Register on this context instead of the page's. */\n context?: ModelContextLike\n /** Aborting withdraws every tool this call registered. */\n signal?: AbortSignal\n}\n\nexport interface WebMcpRegistration {\n /** The tool names that were registered. */\n names: string[]\n /** Withdraw the tools. Safe to call twice. */\n unregister: () => void\n}\n\nconst NAME = /^[A-Za-z0-9_.-]{1,128}$/\n\n/** A tool's result in the shape WebMCP clients read: text content, structured results as JSON. */\nconst asContent = (result: unknown) => ({\n // JSON.stringify(undefined) is undefined, not a string — and a tool that does its work and\n // returns nothing is the common case (a clear, a save), so without this the result WebMCP\n // publishes has `text: undefined` in it and is not a valid text content part.\n content: [\n { type: 'text', text: typeof result === 'string' ? result : (JSON.stringify(result) ?? '') },\n ],\n})\n\n/** AI SDK 7 lets a tool's description depend on the run's context; WebMCP needs a plain string. */\nconst describe = (t: Tool): string => {\n const d = t.description as unknown\n return typeof d === 'function'\n ? String((d as (o: { context: undefined }) => string)({ context: undefined }))\n : (d as string) || ''\n}\n\nconst inputSchemaOf = async (t: Tool): Promise<Record<string, unknown>> => {\n if (!t.inputSchema) return { type: 'object', properties: {} }\n const schema = (await asSchema(t.inputSchema as never).jsonSchema) as Record<string, unknown>\n const { $schema: _ignored, ...rest } = schema\n return rest\n}\n\n/**\n * The WebMCP definitions of a ToolSet, without registering them. A tool without an `execute`\n * (the model's side of a client tool) is left out, as are names WebMCP does not allow.\n */\nexport const toWebMcpTools = async (\n tools: ToolSet,\n options: Pick<WebMcpPublishOptions, 'prefix' | 'only' | 'except' | 'consequential'> = {},\n): Promise<WebMcpToolDefinition[]> => {\n const out: WebMcpToolDefinition[] = []\n for (const [key, t] of Object.entries(tools)) {\n if (options.only && !options.only.includes(key)) continue\n if (options.except?.includes(key)) continue\n const name = `${options.prefix ?? ''}${key}`\n if (!NAME.test(name) || typeof t.execute !== 'function') continue\n const execute = t.execute\n // A dynamic description is a function this module calls with no run context, and a schema can\n // refuse to convert. Either throwing would abandon every tool after it in the loop — including\n // the ones that are fine — so one bad tool is dropped the same way an unpublishable name is.\n let description: string\n let inputSchema: Record<string, unknown>\n try {\n description = describe(t) || key\n inputSchema = await inputSchemaOf(t)\n } catch {\n continue\n }\n out.push({\n name,\n title: key.replace(/[_-]+/g, ' '),\n description,\n inputSchema,\n annotations: {\n readOnlyHint: (t as AgentTool).readOnly === true,\n ...(options.consequential?.includes(key) ? { consequentialHint: true } : {}),\n },\n // WebMCP calls execute with a signal; the SDK's tools want the SDK's call options.\n execute: async (input, opts) =>\n asContent(\n await (execute as (i: unknown, o: unknown) => unknown)(input, {\n toolCallId: `webmcp-${name}`,\n messages: [],\n abortSignal: opts?.signal,\n context: undefined,\n }),\n ),\n })\n }\n return out\n}\n\n/**\n * Publish a ToolSet to the page's WebMCP model context. Resolves to undefined where the browser\n * has no WebMCP. A tool the browser refuses (a name already taken, a permissions policy) is\n * skipped, not thrown, and never leaves an unhandled rejection.\n *\n * @example\n * const reg = await registerWebMcpTools(editorTools, { prefix: 'editor_', signal })\n * // later: reg?.unregister()\n */\nexport const registerWebMcpTools = async (\n tools: ToolSet,\n options: WebMcpPublishOptions = {},\n): Promise<WebMcpRegistration | undefined> => {\n const context = options.context ?? findModelContext()\n if (!context) return undefined\n const controller = new AbortController()\n const names: string[] = []\n for (const def of await toWebMcpTools(tools, options)) {\n try {\n const result = context.registerTool(def, { signal: controller.signal })\n // current API: a promise that rejects for a duplicate name or a refused policy\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n ;(result as Promise<unknown>).catch(() => undefined)\n }\n names.push(def.name)\n } catch {\n /* skip this tool */\n }\n }\n let done = false\n const unregister = () => {\n if (done) return\n done = true\n controller.abort()\n // the early-preview API has no signal: withdraw by name\n if (typeof context.unregisterTool === 'function') {\n for (const name of names) {\n try {\n context.unregisterTool(name)\n } catch {\n /* already gone */\n }\n }\n }\n }\n options.signal?.addEventListener('abort', unregister, { once: true })\n if (options.signal?.aborted) unregister()\n return { names, unregister }\n}\n\nexport interface ConnectWebMcpOptions {\n /** Read tools from this context instead of the page's. */\n context?: ModelContextLike\n /** Skip tools whose name this returns false for (e.g. the ones the page itself publishes from this agent's ToolSet). */\n filter?: (tool: RegisteredWebMcpTool) => boolean\n /** Called when the page's tool list changes (`toolchange`); `refresh()` has already run. */\n onToolsChanged?: (tools: AgentToolSet) => void\n}\n\nexport interface ConnectedWebMcp {\n /** The page's tools as an agent ToolSet. Mutated in place by `refresh()`, so an agent that holds it sees changes. */\n tools: AgentToolSet\n /** Read the page's tool list again. */\n refresh: () => Promise<void>\n /** Stop listening for changes. */\n close: () => void\n}\n\n// WebMCP's namespace is wider than a provider's: the spec allows `.` and up to 128 characters\n// (see NAME above), while providers take ^[a-zA-Z0-9_-]{1,64}$ and reject the WHOLE request when a\n// tool name breaks it — so one page tool named \"editor.clear\" would fail every run of an agent that\n// merged this set, not just that one call. The sibling MCP connector maps names for the same\n// reason; dispatch is unaffected because executeTool is handed the page's own tool object.\nconst PROVIDER_MAX_NAME = 64\nconst toProviderName = (name: string, taken: Record<string, unknown>): string => {\n const base = name.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, PROVIDER_MAX_NAME) || 'tool'\n if (!Object.hasOwn(taken, base)) return base\n // Suffix rather than drop: two page tools that map onto one key would otherwise make the second\n // disappear from the model's view, which is a silent capability loss.\n for (let n = 2; n < 100; n++) {\n const suffix = `_${n}`\n const candidate = base.slice(0, PROVIDER_MAX_NAME - suffix.length) + suffix\n if (!Object.hasOwn(taken, candidate)) return candidate\n }\n return ''\n}\n\nconst parseSchema = (s: RegisteredWebMcpTool['inputSchema']): Record<string, unknown> => {\n if (!s) return { type: 'object', properties: {} }\n if (typeof s !== 'string') return s\n try {\n const parsed = JSON.parse(s)\n return parsed && typeof parsed === 'object' ? parsed : { type: 'object', properties: {} }\n } catch {\n return { type: 'object', properties: {} }\n }\n}\n\n/** A WebMCP result is stringified JSON text, or MCP-style content; hand the model something readable. */\nconst readResult = (raw: unknown): unknown => {\n if (typeof raw !== 'string') return raw\n try {\n const parsed = JSON.parse(raw)\n const content = (parsed as { content?: { type?: string; text?: string }[] })?.content\n if (Array.isArray(content) && content.every((c) => c?.type === 'text')) {\n const text = content.map((c) => c.text ?? '').join('\\n')\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n }\n return parsed\n } catch {\n return raw\n }\n}\n\n/**\n * Use the tools a page has registered as an agent's tools: `getTools()` once, then\n * `executeTool()` for each call. Resolves to undefined where the browser has no WebMCP (or no\n * `getTools`).\n *\n * @example\n * const web = await connectWebMcp()\n * const agent = await createAgent({ model, tools: { ...myTools, ...web?.tools } })\n */\nexport const connectWebMcp = async (\n options: ConnectWebMcpOptions = {},\n): Promise<ConnectedWebMcp | undefined> => {\n const context = options.context ?? findModelContext()\n if (\n !context ||\n typeof context.getTools !== 'function' ||\n typeof context.executeTool !== 'function'\n ) {\n return undefined\n }\n const tools: AgentToolSet = {}\n const refresh = async () => {\n const registered = await context.getTools!()\n for (const key of Object.keys(tools)) delete tools[key]\n for (const rt of registered) {\n if (options.filter && !options.filter(rt)) continue\n const t = tool({\n description: rt.description || rt.name,\n inputSchema: jsonSchema<Record<string, unknown>>(parseSchema(rt.inputSchema) as never),\n execute: async (input, opts) =>\n readResult(await context.executeTool!(rt, input, { signal: opts?.abortSignal })),\n }) as AgentTool\n if (rt.annotations?.readOnlyHint) t.readOnly = true\n const key = toProviderName(rt.name, tools)\n if (key) tools[key] = t\n }\n }\n await refresh()\n const onChange = () => {\n // A rejected refresh here has nobody to catch it: the page's `toolchange` fired, not us. The\n // module avoids unhandled rejections on the register side too.\n void refresh()\n .then(() => options.onToolsChanged?.(tools))\n .catch(() => undefined)\n }\n context.addEventListener?.('toolchange', onChange)\n return {\n tools,\n refresh,\n close: () => context.removeEventListener?.('toolchange', onChange),\n }\n}\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AM,QAAQ,iBAAiB,KAAK,CAAC,EAC1C,MAAM,MAAM,MAAS;AAAA,EAC1B;AACA,UAAQ,mBAAmB,cAAc,QAAQ;AACjD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,MAAM,QAAQ,sBAAsB,cAAc,QAAQ;AAAA,EACnE;AACF;","names":[]}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { ToolSet } from 'ai';
|
|
2
|
+
import { AgentToolSet } from './index.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* WebMCP — the browser's tool API for pages (https://webmachinelearning.github.io/webmcp/).
|
|
6
|
+
*
|
|
7
|
+
* A page registers named, typed tools with `document.modelContext.registerTool(tool, { signal })`
|
|
8
|
+
* and a browser's agent (Chrome's origin trial, Edge, an extension, an in-page agent) can discover
|
|
9
|
+
* and call them. This module bridges that API and an agent's `ToolSet`, in both directions:
|
|
10
|
+
*
|
|
11
|
+
* - {@link registerWebMcpTools} PUBLISHES a ToolSet to the page's model context, so the tools
|
|
12
|
+
* an in-page agent uses can also be driven by any agent of the browser — one definition, two
|
|
13
|
+
* consumers.
|
|
14
|
+
* - {@link connectWebMcp} CONSUMES the tools a page has registered (its own, or another
|
|
15
|
+
* script's) as an agent ToolSet.
|
|
16
|
+
*
|
|
17
|
+
* Browser-only, no extra dependency, and a no-op where the browser has no WebMCP. Two API
|
|
18
|
+
* generations are handled: the current one on `document.modelContext` (registration returns a
|
|
19
|
+
* promise, a tool is withdrawn by aborting its signal) and Chrome's early preview on
|
|
20
|
+
* `navigator.modelContext` (`unregisterTool(name)`).
|
|
21
|
+
*/
|
|
22
|
+
/** What WebMCP registers: a tool a browser agent can call. */
|
|
23
|
+
interface WebMcpToolDefinition {
|
|
24
|
+
name: string;
|
|
25
|
+
title: string;
|
|
26
|
+
description: string;
|
|
27
|
+
inputSchema: Record<string, unknown>;
|
|
28
|
+
annotations: {
|
|
29
|
+
readOnlyHint: boolean;
|
|
30
|
+
consequentialHint?: boolean;
|
|
31
|
+
};
|
|
32
|
+
execute: (input: Record<string, unknown>, options?: {
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
}) => Promise<unknown>;
|
|
35
|
+
}
|
|
36
|
+
/** What a page's `getTools()` returns for one tool. */
|
|
37
|
+
interface RegisteredWebMcpTool {
|
|
38
|
+
name: string;
|
|
39
|
+
description?: string;
|
|
40
|
+
/** The specification stringifies it; an object is accepted too. */
|
|
41
|
+
inputSchema?: string | Record<string, unknown>;
|
|
42
|
+
annotations?: {
|
|
43
|
+
readOnlyHint?: boolean;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** The parts of `ModelContext` this module uses. */
|
|
47
|
+
interface ModelContextLike {
|
|
48
|
+
registerTool: (tool: WebMcpToolDefinition, options?: {
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
}) => unknown;
|
|
51
|
+
unregisterTool?: (name: string) => unknown;
|
|
52
|
+
getTools?: (options?: unknown) => Promise<RegisteredWebMcpTool[]>;
|
|
53
|
+
executeTool?: (tool: RegisteredWebMcpTool, input?: Record<string, unknown>, options?: {
|
|
54
|
+
signal?: AbortSignal;
|
|
55
|
+
}) => Promise<unknown>;
|
|
56
|
+
addEventListener?: (type: string, listener: () => void) => void;
|
|
57
|
+
removeEventListener?: (type: string, listener: () => void) => void;
|
|
58
|
+
}
|
|
59
|
+
/** The page's model context, wherever this browser puts it; undefined when there is none. */
|
|
60
|
+
declare const findModelContext: (doc?: {
|
|
61
|
+
modelContext?: unknown;
|
|
62
|
+
} | undefined) => ModelContextLike | undefined;
|
|
63
|
+
declare const isWebMcpAvailable: () => boolean;
|
|
64
|
+
interface WebMcpPublishOptions {
|
|
65
|
+
/**
|
|
66
|
+
* Prepended to every tool name. WebMCP tools of a page share one namespace with whatever else
|
|
67
|
+
* the page (or an extension) registers, so a prefix such as `myapp_` avoids collisions. Names may
|
|
68
|
+
* contain ASCII letters, digits, `_`, `-` and `.`, at most 128 characters.
|
|
69
|
+
*/
|
|
70
|
+
prefix?: string;
|
|
71
|
+
/** Publish only these tools (by their name in the ToolSet). */
|
|
72
|
+
only?: string[];
|
|
73
|
+
/** Never publish these tools. */
|
|
74
|
+
except?: string[];
|
|
75
|
+
/** Tools whose effect is significant or hard to reverse: annotated `consequentialHint`. */
|
|
76
|
+
consequential?: string[];
|
|
77
|
+
/** Register on this context instead of the page's. */
|
|
78
|
+
context?: ModelContextLike;
|
|
79
|
+
/** Aborting withdraws every tool this call registered. */
|
|
80
|
+
signal?: AbortSignal;
|
|
81
|
+
}
|
|
82
|
+
interface WebMcpRegistration {
|
|
83
|
+
/** The tool names that were registered. */
|
|
84
|
+
names: string[];
|
|
85
|
+
/** Withdraw the tools. Safe to call twice. */
|
|
86
|
+
unregister: () => void;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The WebMCP definitions of a ToolSet, without registering them. A tool without an `execute`
|
|
90
|
+
* (the model's side of a client tool) is left out, as are names WebMCP does not allow.
|
|
91
|
+
*/
|
|
92
|
+
declare const toWebMcpTools: (tools: ToolSet, options?: Pick<WebMcpPublishOptions, "prefix" | "only" | "except" | "consequential">) => Promise<WebMcpToolDefinition[]>;
|
|
93
|
+
/**
|
|
94
|
+
* Publish a ToolSet to the page's WebMCP model context. Resolves to undefined where the browser
|
|
95
|
+
* has no WebMCP. A tool the browser refuses (a name already taken, a permissions policy) is
|
|
96
|
+
* skipped, not thrown, and never leaves an unhandled rejection.
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* const reg = await registerWebMcpTools(editorTools, { prefix: 'editor_', signal })
|
|
100
|
+
* // later: reg?.unregister()
|
|
101
|
+
*/
|
|
102
|
+
declare const registerWebMcpTools: (tools: ToolSet, options?: WebMcpPublishOptions) => Promise<WebMcpRegistration | undefined>;
|
|
103
|
+
interface ConnectWebMcpOptions {
|
|
104
|
+
/** Read tools from this context instead of the page's. */
|
|
105
|
+
context?: ModelContextLike;
|
|
106
|
+
/** Skip tools whose name this returns false for (e.g. the ones the page itself publishes from this agent's ToolSet). */
|
|
107
|
+
filter?: (tool: RegisteredWebMcpTool) => boolean;
|
|
108
|
+
/** Called when the page's tool list changes (`toolchange`); `refresh()` has already run. */
|
|
109
|
+
onToolsChanged?: (tools: AgentToolSet) => void;
|
|
110
|
+
}
|
|
111
|
+
interface ConnectedWebMcp {
|
|
112
|
+
/** The page's tools as an agent ToolSet. Mutated in place by `refresh()`, so an agent that holds it sees changes. */
|
|
113
|
+
tools: AgentToolSet;
|
|
114
|
+
/** Read the page's tool list again. */
|
|
115
|
+
refresh: () => Promise<void>;
|
|
116
|
+
/** Stop listening for changes. */
|
|
117
|
+
close: () => void;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Use the tools a page has registered as an agent's tools: `getTools()` once, then
|
|
121
|
+
* `executeTool()` for each call. Resolves to undefined where the browser has no WebMCP (or no
|
|
122
|
+
* `getTools`).
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* const web = await connectWebMcp()
|
|
126
|
+
* const agent = await createAgent({ model, tools: { ...myTools, ...web?.tools } })
|
|
127
|
+
*/
|
|
128
|
+
declare const connectWebMcp: (options?: ConnectWebMcpOptions) => Promise<ConnectedWebMcp | undefined>;
|
|
129
|
+
|
|
130
|
+
export { connectWebMcp, findModelContext, isWebMcpAvailable, registerWebMcpTools, toWebMcpTools };
|
|
131
|
+
export type { ConnectWebMcpOptions, ConnectedWebMcp, ModelContextLike, RegisteredWebMcpTool, WebMcpPublishOptions, WebMcpRegistration, WebMcpToolDefinition };
|
package/dist/webmcp.d.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { ToolSet } from 'ai';
|
|
2
|
+
import { AgentToolSet } from './index.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* WebMCP — the browser's tool API for pages (https://webmachinelearning.github.io/webmcp/).
|
|
6
|
+
*
|
|
7
|
+
* A page registers named, typed tools with `document.modelContext.registerTool(tool, { signal })`
|
|
8
|
+
* and a browser's agent (Chrome's origin trial, Edge, an extension, an in-page agent) can discover
|
|
9
|
+
* and call them. This module bridges that API and an agent's `ToolSet`, in both directions:
|
|
10
|
+
*
|
|
11
|
+
* - {@link registerWebMcpTools} PUBLISHES a ToolSet to the page's model context, so the tools
|
|
12
|
+
* an in-page agent uses can also be driven by any agent of the browser — one definition, two
|
|
13
|
+
* consumers.
|
|
14
|
+
* - {@link connectWebMcp} CONSUMES the tools a page has registered (its own, or another
|
|
15
|
+
* script's) as an agent ToolSet.
|
|
16
|
+
*
|
|
17
|
+
* Browser-only, no extra dependency, and a no-op where the browser has no WebMCP. Two API
|
|
18
|
+
* generations are handled: the current one on `document.modelContext` (registration returns a
|
|
19
|
+
* promise, a tool is withdrawn by aborting its signal) and Chrome's early preview on
|
|
20
|
+
* `navigator.modelContext` (`unregisterTool(name)`).
|
|
21
|
+
*/
|
|
22
|
+
/** What WebMCP registers: a tool a browser agent can call. */
|
|
23
|
+
interface WebMcpToolDefinition {
|
|
24
|
+
name: string;
|
|
25
|
+
title: string;
|
|
26
|
+
description: string;
|
|
27
|
+
inputSchema: Record<string, unknown>;
|
|
28
|
+
annotations: {
|
|
29
|
+
readOnlyHint: boolean;
|
|
30
|
+
consequentialHint?: boolean;
|
|
31
|
+
};
|
|
32
|
+
execute: (input: Record<string, unknown>, options?: {
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
}) => Promise<unknown>;
|
|
35
|
+
}
|
|
36
|
+
/** What a page's `getTools()` returns for one tool. */
|
|
37
|
+
interface RegisteredWebMcpTool {
|
|
38
|
+
name: string;
|
|
39
|
+
description?: string;
|
|
40
|
+
/** The specification stringifies it; an object is accepted too. */
|
|
41
|
+
inputSchema?: string | Record<string, unknown>;
|
|
42
|
+
annotations?: {
|
|
43
|
+
readOnlyHint?: boolean;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** The parts of `ModelContext` this module uses. */
|
|
47
|
+
interface ModelContextLike {
|
|
48
|
+
registerTool: (tool: WebMcpToolDefinition, options?: {
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
}) => unknown;
|
|
51
|
+
unregisterTool?: (name: string) => unknown;
|
|
52
|
+
getTools?: (options?: unknown) => Promise<RegisteredWebMcpTool[]>;
|
|
53
|
+
executeTool?: (tool: RegisteredWebMcpTool, input?: Record<string, unknown>, options?: {
|
|
54
|
+
signal?: AbortSignal;
|
|
55
|
+
}) => Promise<unknown>;
|
|
56
|
+
addEventListener?: (type: string, listener: () => void) => void;
|
|
57
|
+
removeEventListener?: (type: string, listener: () => void) => void;
|
|
58
|
+
}
|
|
59
|
+
/** The page's model context, wherever this browser puts it; undefined when there is none. */
|
|
60
|
+
declare const findModelContext: (doc?: {
|
|
61
|
+
modelContext?: unknown;
|
|
62
|
+
} | undefined) => ModelContextLike | undefined;
|
|
63
|
+
declare const isWebMcpAvailable: () => boolean;
|
|
64
|
+
interface WebMcpPublishOptions {
|
|
65
|
+
/**
|
|
66
|
+
* Prepended to every tool name. WebMCP tools of a page share one namespace with whatever else
|
|
67
|
+
* the page (or an extension) registers, so a prefix such as `myapp_` avoids collisions. Names may
|
|
68
|
+
* contain ASCII letters, digits, `_`, `-` and `.`, at most 128 characters.
|
|
69
|
+
*/
|
|
70
|
+
prefix?: string;
|
|
71
|
+
/** Publish only these tools (by their name in the ToolSet). */
|
|
72
|
+
only?: string[];
|
|
73
|
+
/** Never publish these tools. */
|
|
74
|
+
except?: string[];
|
|
75
|
+
/** Tools whose effect is significant or hard to reverse: annotated `consequentialHint`. */
|
|
76
|
+
consequential?: string[];
|
|
77
|
+
/** Register on this context instead of the page's. */
|
|
78
|
+
context?: ModelContextLike;
|
|
79
|
+
/** Aborting withdraws every tool this call registered. */
|
|
80
|
+
signal?: AbortSignal;
|
|
81
|
+
}
|
|
82
|
+
interface WebMcpRegistration {
|
|
83
|
+
/** The tool names that were registered. */
|
|
84
|
+
names: string[];
|
|
85
|
+
/** Withdraw the tools. Safe to call twice. */
|
|
86
|
+
unregister: () => void;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The WebMCP definitions of a ToolSet, without registering them. A tool without an `execute`
|
|
90
|
+
* (the model's side of a client tool) is left out, as are names WebMCP does not allow.
|
|
91
|
+
*/
|
|
92
|
+
declare const toWebMcpTools: (tools: ToolSet, options?: Pick<WebMcpPublishOptions, "prefix" | "only" | "except" | "consequential">) => Promise<WebMcpToolDefinition[]>;
|
|
93
|
+
/**
|
|
94
|
+
* Publish a ToolSet to the page's WebMCP model context. Resolves to undefined where the browser
|
|
95
|
+
* has no WebMCP. A tool the browser refuses (a name already taken, a permissions policy) is
|
|
96
|
+
* skipped, not thrown, and never leaves an unhandled rejection.
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* const reg = await registerWebMcpTools(editorTools, { prefix: 'editor_', signal })
|
|
100
|
+
* // later: reg?.unregister()
|
|
101
|
+
*/
|
|
102
|
+
declare const registerWebMcpTools: (tools: ToolSet, options?: WebMcpPublishOptions) => Promise<WebMcpRegistration | undefined>;
|
|
103
|
+
interface ConnectWebMcpOptions {
|
|
104
|
+
/** Read tools from this context instead of the page's. */
|
|
105
|
+
context?: ModelContextLike;
|
|
106
|
+
/** Skip tools whose name this returns false for (e.g. the ones the page itself publishes from this agent's ToolSet). */
|
|
107
|
+
filter?: (tool: RegisteredWebMcpTool) => boolean;
|
|
108
|
+
/** Called when the page's tool list changes (`toolchange`); `refresh()` has already run. */
|
|
109
|
+
onToolsChanged?: (tools: AgentToolSet) => void;
|
|
110
|
+
}
|
|
111
|
+
interface ConnectedWebMcp {
|
|
112
|
+
/** The page's tools as an agent ToolSet. Mutated in place by `refresh()`, so an agent that holds it sees changes. */
|
|
113
|
+
tools: AgentToolSet;
|
|
114
|
+
/** Read the page's tool list again. */
|
|
115
|
+
refresh: () => Promise<void>;
|
|
116
|
+
/** Stop listening for changes. */
|
|
117
|
+
close: () => void;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Use the tools a page has registered as an agent's tools: `getTools()` once, then
|
|
121
|
+
* `executeTool()` for each call. Resolves to undefined where the browser has no WebMCP (or no
|
|
122
|
+
* `getTools`).
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* const web = await connectWebMcp()
|
|
126
|
+
* const agent = await createAgent({ model, tools: { ...myTools, ...web?.tools } })
|
|
127
|
+
*/
|
|
128
|
+
declare const connectWebMcp: (options?: ConnectWebMcpOptions) => Promise<ConnectedWebMcp | undefined>;
|
|
129
|
+
|
|
130
|
+
export { connectWebMcp, findModelContext, isWebMcpAvailable, registerWebMcpTools, toWebMcpTools };
|
|
131
|
+
export type { ConnectWebMcpOptions, ConnectedWebMcp, ModelContextLike, RegisteredWebMcpTool, WebMcpPublishOptions, WebMcpRegistration, WebMcpToolDefinition };
|
package/dist/webmcp.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// src/webmcp/index.ts
|
|
2
|
+
import { asSchema, jsonSchema, tool } from "ai";
|
|
3
|
+
var findModelContext = (doc = typeof document !== "undefined" ? document : void 0) => {
|
|
4
|
+
const nav = typeof navigator !== "undefined" ? navigator : void 0;
|
|
5
|
+
return [doc?.modelContext, nav?.modelContext].find(
|
|
6
|
+
(c) => !!c && typeof c.registerTool === "function"
|
|
7
|
+
);
|
|
8
|
+
};
|
|
9
|
+
var isWebMcpAvailable = () => findModelContext() !== void 0;
|
|
10
|
+
var NAME = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
11
|
+
var asContent = (result) => ({
|
|
12
|
+
// JSON.stringify(undefined) is undefined, not a string — and a tool that does its work and
|
|
13
|
+
// returns nothing is the common case (a clear, a save), so without this the result WebMCP
|
|
14
|
+
// publishes has `text: undefined` in it and is not a valid text content part.
|
|
15
|
+
content: [
|
|
16
|
+
{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result) ?? "" }
|
|
17
|
+
]
|
|
18
|
+
});
|
|
19
|
+
var describe = (t) => {
|
|
20
|
+
const d = t.description;
|
|
21
|
+
return typeof d === "function" ? String(d({ context: void 0 })) : d || "";
|
|
22
|
+
};
|
|
23
|
+
var inputSchemaOf = async (t) => {
|
|
24
|
+
if (!t.inputSchema) return { type: "object", properties: {} };
|
|
25
|
+
const schema = await asSchema(t.inputSchema).jsonSchema;
|
|
26
|
+
const { $schema: _ignored, ...rest } = schema;
|
|
27
|
+
return rest;
|
|
28
|
+
};
|
|
29
|
+
var toWebMcpTools = async (tools, options = {}) => {
|
|
30
|
+
const out = [];
|
|
31
|
+
for (const [key, t] of Object.entries(tools)) {
|
|
32
|
+
if (options.only && !options.only.includes(key)) continue;
|
|
33
|
+
if (options.except?.includes(key)) continue;
|
|
34
|
+
const name = `${options.prefix ?? ""}${key}`;
|
|
35
|
+
if (!NAME.test(name) || typeof t.execute !== "function") continue;
|
|
36
|
+
const execute = t.execute;
|
|
37
|
+
let description;
|
|
38
|
+
let inputSchema;
|
|
39
|
+
try {
|
|
40
|
+
description = describe(t) || key;
|
|
41
|
+
inputSchema = await inputSchemaOf(t);
|
|
42
|
+
} catch {
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
out.push({
|
|
46
|
+
name,
|
|
47
|
+
title: key.replace(/[_-]+/g, " "),
|
|
48
|
+
description,
|
|
49
|
+
inputSchema,
|
|
50
|
+
annotations: {
|
|
51
|
+
readOnlyHint: t.readOnly === true,
|
|
52
|
+
...options.consequential?.includes(key) ? { consequentialHint: true } : {}
|
|
53
|
+
},
|
|
54
|
+
// WebMCP calls execute with a signal; the SDK's tools want the SDK's call options.
|
|
55
|
+
execute: async (input, opts) => asContent(
|
|
56
|
+
await execute(input, {
|
|
57
|
+
toolCallId: `webmcp-${name}`,
|
|
58
|
+
messages: [],
|
|
59
|
+
abortSignal: opts?.signal,
|
|
60
|
+
context: void 0
|
|
61
|
+
})
|
|
62
|
+
)
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
};
|
|
67
|
+
var registerWebMcpTools = async (tools, options = {}) => {
|
|
68
|
+
const context = options.context ?? findModelContext();
|
|
69
|
+
if (!context) return void 0;
|
|
70
|
+
const controller = new AbortController();
|
|
71
|
+
const names = [];
|
|
72
|
+
for (const def of await toWebMcpTools(tools, options)) {
|
|
73
|
+
try {
|
|
74
|
+
const result = context.registerTool(def, { signal: controller.signal });
|
|
75
|
+
if (result && typeof result.then === "function") {
|
|
76
|
+
;
|
|
77
|
+
result.catch(() => void 0);
|
|
78
|
+
}
|
|
79
|
+
names.push(def.name);
|
|
80
|
+
} catch {
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
let done = false;
|
|
84
|
+
const unregister = () => {
|
|
85
|
+
if (done) return;
|
|
86
|
+
done = true;
|
|
87
|
+
controller.abort();
|
|
88
|
+
if (typeof context.unregisterTool === "function") {
|
|
89
|
+
for (const name of names) {
|
|
90
|
+
try {
|
|
91
|
+
context.unregisterTool(name);
|
|
92
|
+
} catch {
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
options.signal?.addEventListener("abort", unregister, { once: true });
|
|
98
|
+
if (options.signal?.aborted) unregister();
|
|
99
|
+
return { names, unregister };
|
|
100
|
+
};
|
|
101
|
+
var PROVIDER_MAX_NAME = 64;
|
|
102
|
+
var toProviderName = (name, taken) => {
|
|
103
|
+
const base = name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, PROVIDER_MAX_NAME) || "tool";
|
|
104
|
+
if (!Object.hasOwn(taken, base)) return base;
|
|
105
|
+
for (let n = 2; n < 100; n++) {
|
|
106
|
+
const suffix = `_${n}`;
|
|
107
|
+
const candidate = base.slice(0, PROVIDER_MAX_NAME - suffix.length) + suffix;
|
|
108
|
+
if (!Object.hasOwn(taken, candidate)) return candidate;
|
|
109
|
+
}
|
|
110
|
+
return "";
|
|
111
|
+
};
|
|
112
|
+
var parseSchema = (s) => {
|
|
113
|
+
if (!s) return { type: "object", properties: {} };
|
|
114
|
+
if (typeof s !== "string") return s;
|
|
115
|
+
try {
|
|
116
|
+
const parsed = JSON.parse(s);
|
|
117
|
+
return parsed && typeof parsed === "object" ? parsed : { type: "object", properties: {} };
|
|
118
|
+
} catch {
|
|
119
|
+
return { type: "object", properties: {} };
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
var readResult = (raw) => {
|
|
123
|
+
if (typeof raw !== "string") return raw;
|
|
124
|
+
try {
|
|
125
|
+
const parsed = JSON.parse(raw);
|
|
126
|
+
const content = parsed?.content;
|
|
127
|
+
if (Array.isArray(content) && content.every((c) => c?.type === "text")) {
|
|
128
|
+
const text = content.map((c) => c.text ?? "").join("\n");
|
|
129
|
+
try {
|
|
130
|
+
return JSON.parse(text);
|
|
131
|
+
} catch {
|
|
132
|
+
return text;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return parsed;
|
|
136
|
+
} catch {
|
|
137
|
+
return raw;
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
var connectWebMcp = async (options = {}) => {
|
|
141
|
+
const context = options.context ?? findModelContext();
|
|
142
|
+
if (!context || typeof context.getTools !== "function" || typeof context.executeTool !== "function") {
|
|
143
|
+
return void 0;
|
|
144
|
+
}
|
|
145
|
+
const tools = {};
|
|
146
|
+
const refresh = async () => {
|
|
147
|
+
const registered = await context.getTools();
|
|
148
|
+
for (const key of Object.keys(tools)) delete tools[key];
|
|
149
|
+
for (const rt of registered) {
|
|
150
|
+
if (options.filter && !options.filter(rt)) continue;
|
|
151
|
+
const t = tool({
|
|
152
|
+
description: rt.description || rt.name,
|
|
153
|
+
inputSchema: jsonSchema(parseSchema(rt.inputSchema)),
|
|
154
|
+
execute: async (input, opts) => readResult(await context.executeTool(rt, input, { signal: opts?.abortSignal }))
|
|
155
|
+
});
|
|
156
|
+
if (rt.annotations?.readOnlyHint) t.readOnly = true;
|
|
157
|
+
const key = toProviderName(rt.name, tools);
|
|
158
|
+
if (key) tools[key] = t;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
await refresh();
|
|
162
|
+
const onChange = () => {
|
|
163
|
+
void refresh().then(() => options.onToolsChanged?.(tools)).catch(() => void 0);
|
|
164
|
+
};
|
|
165
|
+
context.addEventListener?.("toolchange", onChange);
|
|
166
|
+
return {
|
|
167
|
+
tools,
|
|
168
|
+
refresh,
|
|
169
|
+
close: () => context.removeEventListener?.("toolchange", onChange)
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
export {
|
|
173
|
+
connectWebMcp,
|
|
174
|
+
findModelContext,
|
|
175
|
+
isWebMcpAvailable,
|
|
176
|
+
registerWebMcpTools,
|
|
177
|
+
toWebMcpTools
|
|
178
|
+
};
|
|
179
|
+
//# sourceMappingURL=webmcp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webmcp/index.ts"],"sourcesContent":["import { asSchema, jsonSchema, tool, type Tool, type ToolSet } from 'ai'\nimport type { AgentTool, AgentToolSet } from '../tools/types.js'\n\n/**\n * WebMCP — the browser's tool API for pages (https://webmachinelearning.github.io/webmcp/).\n *\n * A page registers named, typed tools with `document.modelContext.registerTool(tool, { signal })`\n * and a browser's agent (Chrome's origin trial, Edge, an extension, an in-page agent) can discover\n * and call them. This module bridges that API and an agent's `ToolSet`, in both directions:\n *\n * - {@link registerWebMcpTools} PUBLISHES a ToolSet to the page's model context, so the tools\n * an in-page agent uses can also be driven by any agent of the browser — one definition, two\n * consumers.\n * - {@link connectWebMcp} CONSUMES the tools a page has registered (its own, or another\n * script's) as an agent ToolSet.\n *\n * Browser-only, no extra dependency, and a no-op where the browser has no WebMCP. Two API\n * generations are handled: the current one on `document.modelContext` (registration returns a\n * promise, a tool is withdrawn by aborting its signal) and Chrome's early preview on\n * `navigator.modelContext` (`unregisterTool(name)`).\n */\n\n/** What WebMCP registers: a tool a browser agent can call. */\nexport interface WebMcpToolDefinition {\n name: string\n title: string\n description: string\n inputSchema: Record<string, unknown>\n annotations: { readOnlyHint: boolean; consequentialHint?: boolean }\n execute: (input: Record<string, unknown>, options?: { signal?: AbortSignal }) => Promise<unknown>\n}\n\n/** What a page's `getTools()` returns for one tool. */\nexport interface RegisteredWebMcpTool {\n name: string\n description?: string\n /** The specification stringifies it; an object is accepted too. */\n inputSchema?: string | Record<string, unknown>\n annotations?: { readOnlyHint?: boolean }\n}\n\n/** The parts of `ModelContext` this module uses. */\nexport interface ModelContextLike {\n registerTool: (tool: WebMcpToolDefinition, options?: { signal?: AbortSignal }) => unknown\n unregisterTool?: (name: string) => unknown\n getTools?: (options?: unknown) => Promise<RegisteredWebMcpTool[]>\n executeTool?: (\n tool: RegisteredWebMcpTool,\n input?: Record<string, unknown>,\n options?: { signal?: AbortSignal },\n ) => Promise<unknown>\n addEventListener?: (type: string, listener: () => void) => void\n removeEventListener?: (type: string, listener: () => void) => void\n}\n\n/** The page's model context, wherever this browser puts it; undefined when there is none. */\nexport const findModelContext = (\n doc: { modelContext?: unknown } | undefined = typeof document !== 'undefined'\n ? (document as unknown as { modelContext?: unknown })\n : undefined,\n): ModelContextLike | undefined => {\n const nav =\n typeof navigator !== 'undefined' ? (navigator as { modelContext?: unknown }) : undefined\n return [doc?.modelContext, nav?.modelContext].find(\n (c): c is ModelContextLike =>\n !!c && typeof (c as { registerTool?: unknown }).registerTool === 'function',\n )\n}\n\nexport const isWebMcpAvailable = (): boolean => findModelContext() !== undefined\n\nexport interface WebMcpPublishOptions {\n /**\n * Prepended to every tool name. WebMCP tools of a page share one namespace with whatever else\n * the page (or an extension) registers, so a prefix such as `myapp_` avoids collisions. Names may\n * contain ASCII letters, digits, `_`, `-` and `.`, at most 128 characters.\n */\n prefix?: string\n /** Publish only these tools (by their name in the ToolSet). */\n only?: string[]\n /** Never publish these tools. */\n except?: string[]\n /** Tools whose effect is significant or hard to reverse: annotated `consequentialHint`. */\n consequential?: string[]\n /** Register on this context instead of the page's. */\n context?: ModelContextLike\n /** Aborting withdraws every tool this call registered. */\n signal?: AbortSignal\n}\n\nexport interface WebMcpRegistration {\n /** The tool names that were registered. */\n names: string[]\n /** Withdraw the tools. Safe to call twice. */\n unregister: () => void\n}\n\nconst NAME = /^[A-Za-z0-9_.-]{1,128}$/\n\n/** A tool's result in the shape WebMCP clients read: text content, structured results as JSON. */\nconst asContent = (result: unknown) => ({\n // JSON.stringify(undefined) is undefined, not a string — and a tool that does its work and\n // returns nothing is the common case (a clear, a save), so without this the result WebMCP\n // publishes has `text: undefined` in it and is not a valid text content part.\n content: [\n { type: 'text', text: typeof result === 'string' ? result : (JSON.stringify(result) ?? '') },\n ],\n})\n\n/** AI SDK 7 lets a tool's description depend on the run's context; WebMCP needs a plain string. */\nconst describe = (t: Tool): string => {\n const d = t.description as unknown\n return typeof d === 'function'\n ? String((d as (o: { context: undefined }) => string)({ context: undefined }))\n : (d as string) || ''\n}\n\nconst inputSchemaOf = async (t: Tool): Promise<Record<string, unknown>> => {\n if (!t.inputSchema) return { type: 'object', properties: {} }\n const schema = (await asSchema(t.inputSchema as never).jsonSchema) as Record<string, unknown>\n const { $schema: _ignored, ...rest } = schema\n return rest\n}\n\n/**\n * The WebMCP definitions of a ToolSet, without registering them. A tool without an `execute`\n * (the model's side of a client tool) is left out, as are names WebMCP does not allow.\n */\nexport const toWebMcpTools = async (\n tools: ToolSet,\n options: Pick<WebMcpPublishOptions, 'prefix' | 'only' | 'except' | 'consequential'> = {},\n): Promise<WebMcpToolDefinition[]> => {\n const out: WebMcpToolDefinition[] = []\n for (const [key, t] of Object.entries(tools)) {\n if (options.only && !options.only.includes(key)) continue\n if (options.except?.includes(key)) continue\n const name = `${options.prefix ?? ''}${key}`\n if (!NAME.test(name) || typeof t.execute !== 'function') continue\n const execute = t.execute\n // A dynamic description is a function this module calls with no run context, and a schema can\n // refuse to convert. Either throwing would abandon every tool after it in the loop — including\n // the ones that are fine — so one bad tool is dropped the same way an unpublishable name is.\n let description: string\n let inputSchema: Record<string, unknown>\n try {\n description = describe(t) || key\n inputSchema = await inputSchemaOf(t)\n } catch {\n continue\n }\n out.push({\n name,\n title: key.replace(/[_-]+/g, ' '),\n description,\n inputSchema,\n annotations: {\n readOnlyHint: (t as AgentTool).readOnly === true,\n ...(options.consequential?.includes(key) ? { consequentialHint: true } : {}),\n },\n // WebMCP calls execute with a signal; the SDK's tools want the SDK's call options.\n execute: async (input, opts) =>\n asContent(\n await (execute as (i: unknown, o: unknown) => unknown)(input, {\n toolCallId: `webmcp-${name}`,\n messages: [],\n abortSignal: opts?.signal,\n context: undefined,\n }),\n ),\n })\n }\n return out\n}\n\n/**\n * Publish a ToolSet to the page's WebMCP model context. Resolves to undefined where the browser\n * has no WebMCP. A tool the browser refuses (a name already taken, a permissions policy) is\n * skipped, not thrown, and never leaves an unhandled rejection.\n *\n * @example\n * const reg = await registerWebMcpTools(editorTools, { prefix: 'editor_', signal })\n * // later: reg?.unregister()\n */\nexport const registerWebMcpTools = async (\n tools: ToolSet,\n options: WebMcpPublishOptions = {},\n): Promise<WebMcpRegistration | undefined> => {\n const context = options.context ?? findModelContext()\n if (!context) return undefined\n const controller = new AbortController()\n const names: string[] = []\n for (const def of await toWebMcpTools(tools, options)) {\n try {\n const result = context.registerTool(def, { signal: controller.signal })\n // current API: a promise that rejects for a duplicate name or a refused policy\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n ;(result as Promise<unknown>).catch(() => undefined)\n }\n names.push(def.name)\n } catch {\n /* skip this tool */\n }\n }\n let done = false\n const unregister = () => {\n if (done) return\n done = true\n controller.abort()\n // the early-preview API has no signal: withdraw by name\n if (typeof context.unregisterTool === 'function') {\n for (const name of names) {\n try {\n context.unregisterTool(name)\n } catch {\n /* already gone */\n }\n }\n }\n }\n options.signal?.addEventListener('abort', unregister, { once: true })\n if (options.signal?.aborted) unregister()\n return { names, unregister }\n}\n\nexport interface ConnectWebMcpOptions {\n /** Read tools from this context instead of the page's. */\n context?: ModelContextLike\n /** Skip tools whose name this returns false for (e.g. the ones the page itself publishes from this agent's ToolSet). */\n filter?: (tool: RegisteredWebMcpTool) => boolean\n /** Called when the page's tool list changes (`toolchange`); `refresh()` has already run. */\n onToolsChanged?: (tools: AgentToolSet) => void\n}\n\nexport interface ConnectedWebMcp {\n /** The page's tools as an agent ToolSet. Mutated in place by `refresh()`, so an agent that holds it sees changes. */\n tools: AgentToolSet\n /** Read the page's tool list again. */\n refresh: () => Promise<void>\n /** Stop listening for changes. */\n close: () => void\n}\n\n// WebMCP's namespace is wider than a provider's: the spec allows `.` and up to 128 characters\n// (see NAME above), while providers take ^[a-zA-Z0-9_-]{1,64}$ and reject the WHOLE request when a\n// tool name breaks it — so one page tool named \"editor.clear\" would fail every run of an agent that\n// merged this set, not just that one call. The sibling MCP connector maps names for the same\n// reason; dispatch is unaffected because executeTool is handed the page's own tool object.\nconst PROVIDER_MAX_NAME = 64\nconst toProviderName = (name: string, taken: Record<string, unknown>): string => {\n const base = name.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, PROVIDER_MAX_NAME) || 'tool'\n if (!Object.hasOwn(taken, base)) return base\n // Suffix rather than drop: two page tools that map onto one key would otherwise make the second\n // disappear from the model's view, which is a silent capability loss.\n for (let n = 2; n < 100; n++) {\n const suffix = `_${n}`\n const candidate = base.slice(0, PROVIDER_MAX_NAME - suffix.length) + suffix\n if (!Object.hasOwn(taken, candidate)) return candidate\n }\n return ''\n}\n\nconst parseSchema = (s: RegisteredWebMcpTool['inputSchema']): Record<string, unknown> => {\n if (!s) return { type: 'object', properties: {} }\n if (typeof s !== 'string') return s\n try {\n const parsed = JSON.parse(s)\n return parsed && typeof parsed === 'object' ? parsed : { type: 'object', properties: {} }\n } catch {\n return { type: 'object', properties: {} }\n }\n}\n\n/** A WebMCP result is stringified JSON text, or MCP-style content; hand the model something readable. */\nconst readResult = (raw: unknown): unknown => {\n if (typeof raw !== 'string') return raw\n try {\n const parsed = JSON.parse(raw)\n const content = (parsed as { content?: { type?: string; text?: string }[] })?.content\n if (Array.isArray(content) && content.every((c) => c?.type === 'text')) {\n const text = content.map((c) => c.text ?? '').join('\\n')\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n }\n return parsed\n } catch {\n return raw\n }\n}\n\n/**\n * Use the tools a page has registered as an agent's tools: `getTools()` once, then\n * `executeTool()` for each call. Resolves to undefined where the browser has no WebMCP (or no\n * `getTools`).\n *\n * @example\n * const web = await connectWebMcp()\n * const agent = await createAgent({ model, tools: { ...myTools, ...web?.tools } })\n */\nexport const connectWebMcp = async (\n options: ConnectWebMcpOptions = {},\n): Promise<ConnectedWebMcp | undefined> => {\n const context = options.context ?? findModelContext()\n if (\n !context ||\n typeof context.getTools !== 'function' ||\n typeof context.executeTool !== 'function'\n ) {\n return undefined\n }\n const tools: AgentToolSet = {}\n const refresh = async () => {\n const registered = await context.getTools!()\n for (const key of Object.keys(tools)) delete tools[key]\n for (const rt of registered) {\n if (options.filter && !options.filter(rt)) continue\n const t = tool({\n description: rt.description || rt.name,\n inputSchema: jsonSchema<Record<string, unknown>>(parseSchema(rt.inputSchema) as never),\n execute: async (input, opts) =>\n readResult(await context.executeTool!(rt, input, { signal: opts?.abortSignal })),\n }) as AgentTool\n if (rt.annotations?.readOnlyHint) t.readOnly = true\n const key = toProviderName(rt.name, tools)\n if (key) tools[key] = t\n }\n }\n await refresh()\n const onChange = () => {\n // A rejected refresh here has nobody to catch it: the page's `toolchange` fired, not us. The\n // module avoids unhandled rejections on the register side too.\n void refresh()\n .then(() => options.onToolsChanged?.(tools))\n .catch(() => undefined)\n }\n context.addEventListener?.('toolchange', onChange)\n return {\n tools,\n refresh,\n close: () => context.removeEventListener?.('toolchange', onChange),\n }\n}\n"],"mappings":";AAAA,SAAS,UAAU,YAAY,YAAqC;AAwD7D,IAAM,mBAAmB,CAC9B,MAA8C,OAAO,aAAa,cAC7D,WACD,WAC6B;AACjC,QAAM,MACJ,OAAO,cAAc,cAAe,YAA2C;AACjF,SAAO,CAAC,KAAK,cAAc,KAAK,YAAY,EAAE;AAAA,IAC5C,CAAC,MACC,CAAC,CAAC,KAAK,OAAQ,EAAiC,iBAAi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
3
|
+
"version": "0.0.29",
|
|
4
4
|
"description": "Headless, configurable in-browser LLM agent on the Vercel AI SDK: multi-provider bring-your-own-key (OpenAI, Anthropic, Google, xAI, DeepSeek, gateway, openai-compatible) AND local WebGPU/WebLLM, native + prompted tool-calling, structured output, an encrypted IndexedDB token vault, and a plan → execute → replan → synthesize loop. UI-agnostic.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -30,6 +30,16 @@
|
|
|
30
30
|
"default": "./dist/mcp.cjs"
|
|
31
31
|
}
|
|
32
32
|
},
|
|
33
|
+
"./webmcp": {
|
|
34
|
+
"import": {
|
|
35
|
+
"types": "./dist/webmcp.d.ts",
|
|
36
|
+
"default": "./dist/webmcp.js"
|
|
37
|
+
},
|
|
38
|
+
"require": {
|
|
39
|
+
"types": "./dist/webmcp.d.cts",
|
|
40
|
+
"default": "./dist/webmcp.cjs"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
33
43
|
"./bundle": {
|
|
34
44
|
"types": "./dist/index.d.ts",
|
|
35
45
|
"import": "./dist/agent-web.js"
|
|
@@ -125,7 +135,7 @@
|
|
|
125
135
|
"node": ">=18"
|
|
126
136
|
},
|
|
127
137
|
"dependencies": {
|
|
128
|
-
"ai": "^7.0.
|
|
138
|
+
"ai": "^7.0.165",
|
|
129
139
|
"idb": "^8.0.4",
|
|
130
140
|
"zod": "^4.6.7"
|
|
131
141
|
},
|
|
@@ -174,18 +184,18 @@
|
|
|
174
184
|
}
|
|
175
185
|
},
|
|
176
186
|
"devDependencies": {
|
|
177
|
-
"@ai-sdk/anthropic": "^4.0.
|
|
178
|
-
"@ai-sdk/deepseek": "^3.0.
|
|
179
|
-
"@ai-sdk/google": "^4.0.
|
|
180
|
-
"@ai-sdk/openai": "^4.0.
|
|
181
|
-
"@ai-sdk/openai-compatible": "^3.0.
|
|
182
|
-
"@ai-sdk/xai": "^5.0.
|
|
187
|
+
"@ai-sdk/anthropic": "^4.0.99",
|
|
188
|
+
"@ai-sdk/deepseek": "^3.0.81",
|
|
189
|
+
"@ai-sdk/google": "^4.0.114",
|
|
190
|
+
"@ai-sdk/openai": "^4.0.111",
|
|
191
|
+
"@ai-sdk/openai-compatible": "^3.0.87",
|
|
192
|
+
"@ai-sdk/xai": "^5.0.40",
|
|
183
193
|
"@browser-ai/core": "^3.0.4",
|
|
184
194
|
"@browser-ai/web-llm": "^3.0.4",
|
|
185
195
|
"@mlc-ai/web-llm": "^0.2.87",
|
|
186
196
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
187
197
|
"@types/node": "^22.9.0",
|
|
188
|
-
"fake-indexeddb": "^6.2.
|
|
198
|
+
"fake-indexeddb": "^6.2.8",
|
|
189
199
|
"prettier": "^3.9.10",
|
|
190
200
|
"tsup": "^9.0.0",
|
|
191
201
|
"typescript": "^6.0.3"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/storage/db.ts","../src/secrets/crypto.ts","../src/secrets/vault.ts"],"sourcesContent":["import { openDB, type IDBPDatabase } from 'idb'\n\nexport interface AgentWebDBOptions {\n /** Database name (default 'agent-web'). Use a distinct name to isolate apps. */\n dbName?: string\n}\n\nexport const KEYS_STORE = 'keys'\nexport const SECRETS_STORE = 'secrets'\nexport const SESSIONS_STORE = 'sessions'\nexport const FILES_STORE = 'files'\n\n// v1: keys, secrets, sessions. v2: + files (the virtual file system).\nconst DB_VERSION = 2\n\nlet cache = new Map<string, Promise<IDBPDatabase>>()\n\n/**\n * The single owner of the IndexedDB database. Every persistent store — the\n * non-extractable crypto key, encrypted secrets, and session transcripts —\n * lives under ONE database name + version. Centralising `openDB` here prevents\n * the classic bug where two modules open the same DB name with different store\n * sets and the second call throws a VersionError.\n */\nexport const openAgentWebDB = (opts: AgentWebDBOptions = {}): Promise<IDBPDatabase> => {\n const name = opts.dbName ?? 'agent-web'\n let p = cache.get(name)\n if (!p) {\n p = openDB(name, DB_VERSION, {\n upgrade(db) {\n // Idempotent by store: an existing v1 database gains only what it lacks.\n if (!db.objectStoreNames.contains(KEYS_STORE)) db.createObjectStore(KEYS_STORE)\n if (!db.objectStoreNames.contains(SECRETS_STORE)) db.createObjectStore(SECRETS_STORE)\n if (!db.objectStoreNames.contains(SESSIONS_STORE)) db.createObjectStore(SESSIONS_STORE)\n if (!db.objectStoreNames.contains(FILES_STORE)) db.createObjectStore(FILES_STORE)\n },\n })\n cache.set(name, p)\n // A failed open (private mode, storage denied) must not stay cached, or\n // every later call would replay the same rejection forever.\n p.catch(() => {\n if (cache.get(name) === p) cache.delete(name)\n })\n }\n return p\n}\n\n/** Test hook: drop cached connections so a fresh (e.g. fake-indexeddb) DB is opened. */\nexport const _resetDBCache = (): void => {\n cache = new Map()\n}\n","import { KEYS_STORE, openAgentWebDB } from '../storage/db.js'\n\nconst KEY_ID = 'vault-key-v1'\n\nconst webcrypto = (): Crypto => {\n const c = (globalThis as { crypto?: Crypto }).crypto\n if (!c?.subtle || !c.getRandomValues) {\n throw new Error('WebCrypto (crypto.subtle) is unavailable in this environment')\n }\n return c\n}\n\nconst loadOrCreateKey = async (dbName?: string): Promise<CryptoKey> => {\n const db = await openAgentWebDB({ dbName })\n const existing = (await db.get(KEYS_STORE, KEY_ID)) as CryptoKey | undefined\n if (existing) return existing\n const key = await webcrypto().subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n /* extractable */ false,\n ['encrypt', 'decrypt'],\n )\n // Double-check inside one readwrite transaction: another tab may have created\n // a key while ours was generating. Losing that race and overwriting would\n // leave the other tab's secrets permanently undecryptable.\n const tx = db.transaction(KEYS_STORE, 'readwrite')\n const winner = (await tx.store.get(KEY_ID)) as CryptoKey | undefined\n if (winner) {\n await tx.done\n return winner\n }\n await tx.store.put(key, KEY_ID)\n await tx.done\n return key\n}\n\nconst keyCache = new Map<string, Promise<CryptoKey>>()\n\n/**\n * Fetch (or lazily create) the vault's AES-GCM key. The key is generated\n * NON-EXTRACTABLE and stored as a live `CryptoKey` in IndexedDB — a CryptoKey\n * is structured-cloneable, so it persists across reloads WITHOUT its raw bytes\n * ever being exposed to JavaScript. Not even in-page script can read it out; it\n * can only be used to encrypt / decrypt. That is what makes at-rest storage of\n * the secrets meaningful (see IndexedDBVault's threat model).\n *\n * Concurrent callers share one in-flight promise per DB, and creation is\n * double-checked in a single IDB transaction, so two racing writers can never\n * end up encrypting under different keys.\n */\nexport const getOrCreateVaultKey = (dbName?: string): Promise<CryptoKey> => {\n const cacheKey = dbName ?? 'agent-web'\n let p = keyCache.get(cacheKey)\n if (!p) {\n p = loadOrCreateKey(dbName)\n keyCache.set(cacheKey, p)\n p.catch(() => {\n if (keyCache.get(cacheKey) === p) keyCache.delete(cacheKey)\n })\n }\n return p\n}\n\nexport interface EncryptedBlob {\n /** 96-bit random IV, fresh per write. */\n iv: Uint8Array\n ciphertext: ArrayBuffer\n}\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\n/** Encrypt a JSON-serialisable value with a fresh 96-bit IV (AES-GCM). */\nexport const encryptJSON = async (key: CryptoKey, value: unknown): Promise<EncryptedBlob> => {\n const c = webcrypto()\n const iv = c.getRandomValues(new Uint8Array(12))\n const data = textEncoder.encode(JSON.stringify(value))\n const ciphertext = await c.subtle.encrypt({ name: 'AES-GCM', iv }, key, data)\n return { iv, ciphertext }\n}\n\n/** Decrypt a blob produced by encryptJSON. Throws if the key or blob don't match. */\nexport const decryptJSON = async <T = unknown>(key: CryptoKey, blob: EncryptedBlob): Promise<T> => {\n // Copy the IV into a fresh ArrayBuffer-backed view: after a round-trip through\n // IndexedDB its element buffer is typed as ArrayBufferLike, which no longer\n // satisfies BufferSource under TS's stricter typed-array generics.\n const iv = new Uint8Array(blob.iv)\n const plain = await webcrypto().subtle.decrypt({ name: 'AES-GCM', iv }, key, blob.ciphertext)\n return JSON.parse(textDecoder.decode(plain)) as T\n}\n","import { openAgentWebDB, SECRETS_STORE } from '../storage/db.js'\nimport { decryptJSON, encryptJSON, getOrCreateVaultKey, type EncryptedBlob } from './crypto.js'\n\nexport interface VaultOptions {\n /** Database name, forwarded to the shared IDB owner (default 'agent-web'). */\n dbName?: string\n}\n\n/**\n * Encrypted key/value secret store backed by IndexedDB. Values are encrypted at\n * rest with the non-extractable AES-GCM vault key (see crypto.ts).\n *\n * ── THREAT MODEL (read before shipping any app-owned key to a browser) ──\n * This vault PROTECTS secrets **at rest** — an IndexedDB / disk dump yields\n * only ciphertext — and against **casual DevTools inspection** — no plaintext\n * key is stored, and the AES key cannot be exported even by in-page script.\n *\n * It does **NOT** defend against **active XSS on your origin**: any script that\n * already runs on the page can call `getSecret()`, or use the live `CryptoKey`\n * to decrypt. Browser storage is not a secrets manager.\n *\n * Therefore this vault is for the **end user's OWN key on their OWN device**\n * (bring-your-own-key). A shared, app-owned key must NEVER reach the client —\n * put it behind a server proxy (`ProviderModelSpec.baseURL`) or the Vercel AI\n * Gateway instead.\n */\nexport class IndexedDBVault {\n private readonly dbName?: string\n\n constructor(opts: VaultOptions = {}) {\n this.dbName = opts.dbName\n }\n\n private key(): Promise<CryptoKey> {\n return getOrCreateVaultKey(this.dbName)\n }\n\n /** Encrypt and store a secret string under `id`. */\n async setSecret(id: string, value: string): Promise<void> {\n const blob = await encryptJSON(await this.key(), value)\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.put(SECRETS_STORE, blob, id)\n }\n\n /** Fetch and decrypt a secret, or undefined if absent. */\n async getSecret(id: string): Promise<string | undefined> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n const blob = (await db.get(SECRETS_STORE, id)) as EncryptedBlob | undefined\n if (!blob) return undefined\n return decryptJSON<string>(await this.key(), blob)\n }\n\n async deleteSecret(id: string): Promise<void> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.delete(SECRETS_STORE, id)\n }\n\n async listSecretIds(): Promise<string[]> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n return (await db.getAllKeys(SECRETS_STORE)).map(String)\n }\n}\n"],"mappings":";AAAA,SAAS,cAAiC;AAOnC,IAA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