@frontmcp/plugin-webmcp 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ # @frontmcp/plugin-webmcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Expose the tools of a FrontMCP server that runs **in the page** to in-browser agents through
4
+ [WebMCP](https://webmachinelearning.github.io/webmcp/) (`document.modelContext`). Agents such as
5
+ Gemini in Chrome, the Model Context Tool Inspector extension, and DevTools' WebMCP panel can then
6
+ discover and call them.
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ npm install @frontmcp/plugin-webmcp
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```typescript
17
+ import { WebMcpPlugin } from '@frontmcp/plugin-webmcp';
18
+ import { create } from '@frontmcp/sdk';
19
+
20
+ const server = await create({
21
+ info: { name: 'shop', version: '1.0.0' },
22
+ tools: [SearchProducts, AddToCart],
23
+ plugins: [WebMcpPlugin.init({ prefix: 'shop.' })],
24
+ });
25
+ ```
26
+
27
+ Install the plugin with `WebMcpPlugin.init()` (with or without options).
28
+
29
+ Once the server is ready, every tool it lists on the `'webmcp'` surface is registered with
30
+ `document.modelContext.registerTool()`:
31
+
32
+ - **Kept in sync.** Tools added or removed later, including tools added with `server.registerTool()`
33
+ and React's `useDynamicTool`, are registered or unregistered as they change.
34
+ - **Cleaned up.** Every tool is unregistered when `server.dispose()` runs.
35
+
36
+ An agent's call runs the server's `tools:call-tool` flow, so hooks, authorities, quota and
37
+ `availableWhen` apply to it as they do to any MCP client.
38
+
39
+ ## Options
40
+
41
+ | Option | Type | Default | Description |
42
+ | -------------- | ---------------------------------------------- | ------------------------- | ------------------------------------------------------------------ |
43
+ | `prefix` | `string` | `''` | Prepended to every exposed tool name, e.g. `'shop.'`. |
44
+ | `include` | `(tool) => boolean` | all | Decides which listed tools are exposed. |
45
+ | `exposedTo` | `string[]` | — | Other origins (e.g. an iframe's parent) the tools are offered to. |
46
+ | `authContext` | `DirectAuthContext \| () => DirectAuthContext` | anonymous `webmcp` caller | Who the server sees calling. A function is resolved on every call. |
47
+ | `modelContext` | `ModelContext` | `document.modelContext` | The context to register with: a polyfill, or a test double. |
48
+
49
+ ## Choosing which tools agents see
50
+
51
+ Tools are listed through the `'webmcp'` call surface, so `availableWhen` decides per tool:
52
+
53
+ ```typescript
54
+ @Tool({ name: 'checkout', availableWhen: { surface: ['webmcp'] } }) // in-browser agents only
55
+ @Tool({ name: 'admin_reset', availableWhen: { surface: ['mcp'] } }) // never exposed through WebMCP
56
+ ```
57
+
58
+ ## How tools are translated
59
+
60
+ - **Names.** Names become WebMCP-valid. Characters outside `[A-Za-z0-9_.-]` become `_` (so
61
+ `app:tool` becomes `app_tool`), names are cut to 128 characters, and collisions get `_2`, `_3`, …
62
+ - **Annotations.** MCP's `readOnlyHint` maps to `readOnlyHint`. An explicit `destructiveHint: true`
63
+ maps to `consequentialHint`, and an explicit `openWorldHint: true` to `untrustedContentHint`.
64
+ - **Results.** A call resolves to `{ content, structuredContent? }`, without `_meta`.
65
+ - **Errors.** An error result (`isError`), or an error from the server, rejects with its message.
66
+
67
+ ## Browser support
68
+
69
+ WebMCP is in origin trial in Chrome and Edge (Chrome 149+). For local development, enable
70
+ `chrome://flags/#enable-webmcp-testing`.
71
+
72
+ Where `document.modelContext` is missing, the plugin does nothing; `isWebMcpSupported()` tells you
73
+ up front. To support other browsers, load a polyfill that installs `document.modelContext` before
74
+ creating the server, such as [`@mcp-b/global`](https://github.com/WebMCP-org/npm-packages) (which
75
+ also bridges the page's tools to the MCP-B browser extension), or pass one as `modelContext`.
76
+
77
+ WebMCP exposes tools only: resources and prompts stay MCP-only.
package/esm/index.mjs ADDED
@@ -0,0 +1,329 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __decorateClass = (decorators, target, key, kind) => {
4
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
+ if (decorator = decorators[i])
7
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
+ if (kind && result) __defProp(target, key, result);
9
+ return result;
10
+ };
11
+
12
+ // plugins/plugin-webmcp/src/webmcp.plugin.ts
13
+ import { DynamicPlugin, Plugin, ScopeEntry } from "@frontmcp/sdk";
14
+
15
+ // plugins/plugin-webmcp/src/webmcp.bridge.ts
16
+ import {
17
+ FlowControl,
18
+ InternalMcpError
19
+ } from "@frontmcp/sdk";
20
+ import { randomUUID, runRequestExclusive } from "@frontmcp/utils";
21
+ var MAX_WEBMCP_NAME_LENGTH = 128;
22
+ var INVALID_NAME_CHARACTERS = /[^A-Za-z0-9_.-]/g;
23
+ function resolveDocumentModelContext() {
24
+ const modelContext = globalThis.document?.modelContext;
25
+ return typeof modelContext === "object" && modelContext !== null && typeof modelContext.registerTool === "function" ? modelContext : void 0;
26
+ }
27
+ function isWebMcpSupported() {
28
+ return resolveDocumentModelContext() !== void 0;
29
+ }
30
+ function toWebMcpToolName(name) {
31
+ const cleaned = name.replace(INVALID_NAME_CHARACTERS, "_").slice(0, MAX_WEBMCP_NAME_LENGTH);
32
+ return cleaned.length > 0 ? cleaned : "_";
33
+ }
34
+ function uniqueName(base, taken) {
35
+ if (!taken.has(base)) return base;
36
+ for (let n = 2; ; n++) {
37
+ const suffix = `_${n}`;
38
+ const candidate = base.slice(0, MAX_WEBMCP_NAME_LENGTH - suffix.length) + suffix;
39
+ if (!taken.has(candidate)) return candidate;
40
+ }
41
+ }
42
+ function toWebMcpAnnotations(annotations) {
43
+ const hints = {};
44
+ if (annotations?.readOnlyHint === true) hints.readOnlyHint = true;
45
+ if (annotations?.destructiveHint === true) hints.consequentialHint = true;
46
+ if (annotations?.openWorldHint === true) hints.untrustedContentHint = true;
47
+ return Object.keys(hints).length > 0 ? hints : void 0;
48
+ }
49
+ function textOf(content) {
50
+ return (content ?? []).map((block) => block.type === "text" ? block.text : "").filter((text) => text.length > 0).join("\n");
51
+ }
52
+ function errorBehindFlowControl(error) {
53
+ if (!(error instanceof FlowControl)) return error;
54
+ const original = error.originalError;
55
+ if (error.type === "fail" && original !== void 0) return original;
56
+ return new InternalMcpError(`Flow ended with: ${error.type}`);
57
+ }
58
+ function toAgentError(error) {
59
+ const failure = errorBehindFlowControl(error);
60
+ const publicMessage = failure?.getPublicMessage;
61
+ if (typeof publicMessage === "function") return new Error(publicMessage.call(failure));
62
+ return failure instanceof Error ? failure : new Error(String(failure));
63
+ }
64
+ function isRecord(value) {
65
+ return typeof value === "object" && value !== null && !Array.isArray(value);
66
+ }
67
+ var WebMcpBridge = class {
68
+ constructor(scope, options) {
69
+ this.scope = scope;
70
+ this.options = options;
71
+ this.logger = scope.logger.child("webmcp");
72
+ }
73
+ scope;
74
+ options;
75
+ logger;
76
+ sessionId = `webmcp:${randomUUID()}`;
77
+ registrations = /* @__PURE__ */ new Map();
78
+ /** Registrations the ModelContext refused, by name, so the same refusal is reported once. */
79
+ refused = /* @__PURE__ */ new Map();
80
+ modelContext;
81
+ unsubscribe;
82
+ started = false;
83
+ stopped = false;
84
+ /** A registry change arrived that no sync has picked up yet. */
85
+ pending = false;
86
+ /** The scheduled or running sync loop. */
87
+ run;
88
+ /** WebMCP names of the tools currently registered with the ModelContext. */
89
+ get registeredToolNames() {
90
+ return [...this.registrations.keys()];
91
+ }
92
+ /**
93
+ * Find the ModelContext and keep it in sync with the server's tools. Without one (Node, a browser
94
+ * without WebMCP and no polyfill) the bridge does nothing.
95
+ */
96
+ start() {
97
+ if (this.started || this.stopped) return;
98
+ this.started = true;
99
+ const modelContext = this.options.modelContext ?? resolveDocumentModelContext();
100
+ if (!modelContext) {
101
+ this.logger.debug("WebMCP is not available here (no document.modelContext); tools are not exposed");
102
+ return;
103
+ }
104
+ this.modelContext = modelContext;
105
+ this.unsubscribe = this.scope.tools.subscribe({ immediate: true }, () => this.refresh());
106
+ }
107
+ /**
108
+ * Re-list the server's tools and update the registrations. The bridge does this on every tool
109
+ * registry change; call it when something else changes what the caller may see, such as the
110
+ * `authContext` a function option returns.
111
+ */
112
+ refresh() {
113
+ if (!this.modelContext || this.stopped) return;
114
+ this.pending = true;
115
+ this.run ??= this.drain();
116
+ }
117
+ /** Resolves once no sync is scheduled or running. */
118
+ async whenIdle() {
119
+ while (this.run) await this.run;
120
+ }
121
+ /** Unregister every tool and stop following the registry. Calling it again does nothing. */
122
+ stop() {
123
+ if (this.stopped) return;
124
+ this.stopped = true;
125
+ this.unsubscribe?.();
126
+ this.unsubscribe = void 0;
127
+ for (const registration of this.registrations.values()) registration.controller.abort();
128
+ this.registrations.clear();
129
+ }
130
+ /** Sync until no change is pending. Starts a microtask later, so a burst of changes syncs once. */
131
+ async drain() {
132
+ await Promise.resolve();
133
+ try {
134
+ while (this.pending && !this.stopped) {
135
+ this.pending = false;
136
+ try {
137
+ await this.sync();
138
+ } catch (error) {
139
+ this.logger.warn(`WebMCP sync failed: ${toAgentError(error).message}`);
140
+ }
141
+ }
142
+ } finally {
143
+ this.run = void 0;
144
+ }
145
+ }
146
+ async sync() {
147
+ const desired = this.desiredTools(await this.listTools());
148
+ if (this.stopped) return;
149
+ for (const [name, registration] of this.registrations) {
150
+ if (desired.get(name)?.fingerprint === registration.fingerprint) continue;
151
+ registration.controller.abort();
152
+ this.registrations.delete(name);
153
+ }
154
+ for (const [name, tool] of desired) {
155
+ if (this.registrations.has(name) || this.stopped) continue;
156
+ await this.register(name, tool);
157
+ }
158
+ }
159
+ /** The server's tools as the `'webmcp'` surface sees them, every page of them. */
160
+ async listTools() {
161
+ const tools = [];
162
+ const authInfo = await this.authInfo();
163
+ let cursor;
164
+ do {
165
+ const request = { method: "tools/list", params: cursor === void 0 ? {} : { cursor } };
166
+ const page = await this.exclusive(
167
+ () => this.scope.runFlowForOutput("tools:list-tools", { request, ctx: { authInfo, surface: "webmcp" } })
168
+ );
169
+ tools.push(...page.tools);
170
+ cursor = page.nextCursor;
171
+ } while (cursor);
172
+ return tools;
173
+ }
174
+ desiredTools(listed) {
175
+ const desired = /* @__PURE__ */ new Map();
176
+ for (const tool of listed) {
177
+ if (this.options.include && !this.options.include(tool)) continue;
178
+ const name = uniqueName(toWebMcpToolName(this.options.prefix + tool.name), new Set(desired.keys()));
179
+ const title = tool.title ?? tool.annotations?.title;
180
+ const annotations = toWebMcpAnnotations(tool.annotations);
181
+ const descriptor = {
182
+ name,
183
+ ...title && { title },
184
+ description: tool.description || title || tool.name,
185
+ inputSchema: tool.inputSchema,
186
+ ...annotations && { annotations }
187
+ };
188
+ desired.set(name, { mcpName: tool.name, descriptor, fingerprint: JSON.stringify([tool.name, descriptor]) });
189
+ }
190
+ return desired;
191
+ }
192
+ async register(name, tool) {
193
+ const modelContext = this.modelContext;
194
+ const controller = new AbortController();
195
+ this.registrations.set(name, { mcpName: tool.mcpName, fingerprint: tool.fingerprint, controller });
196
+ try {
197
+ await modelContext.registerTool(
198
+ { ...tool.descriptor, execute: (input, options) => this.execute(tool.mcpName, input, options) },
199
+ { signal: controller.signal, ...this.options.exposedTo && { exposedTo: this.options.exposedTo } }
200
+ );
201
+ this.refused.delete(name);
202
+ } catch (error) {
203
+ if (this.registrations.get(name)?.controller === controller) this.registrations.delete(name);
204
+ controller.abort();
205
+ const message = `WebMCP refused tool "${name}": ${toAgentError(error).message}`;
206
+ if (this.refused.get(name) === tool.fingerprint) {
207
+ this.logger.debug(message);
208
+ } else {
209
+ this.refused.set(name, tool.fingerprint);
210
+ this.logger.warn(message);
211
+ }
212
+ }
213
+ }
214
+ /** Run one agent call through the `tools:call-tool` flow, and translate its result for WebMCP. */
215
+ async execute(mcpName, input, options) {
216
+ let result;
217
+ try {
218
+ const request = {
219
+ method: "tools/call",
220
+ params: { name: mcpName, arguments: isRecord(input) ? input : {} }
221
+ };
222
+ const ctx = {
223
+ authInfo: await this.authInfo(),
224
+ surface: "webmcp",
225
+ ...options?.signal && { signal: options.signal }
226
+ };
227
+ result = await this.exclusive(() => this.scope.runFlowForOutput("tools:call-tool", { request, ctx }));
228
+ } catch (error) {
229
+ throw toAgentError(error);
230
+ }
231
+ if (result.isError) throw new Error(textOf(result.content) || `Tool "${mcpName}" failed`);
232
+ return {
233
+ content: result.content ?? [],
234
+ ...result.structuredContent !== void 0 && { structuredContent: result.structuredContent }
235
+ };
236
+ }
237
+ /**
238
+ * Run a flow as its own request. A browser build without AsyncContext runs requests one at a
239
+ * time; this takes the turn. A flow that answers by `respond` is output, not a failure.
240
+ */
241
+ async exclusive(runFlow) {
242
+ try {
243
+ return await runRequestExclusive(runFlow);
244
+ } catch (error) {
245
+ if (error instanceof FlowControl && error.type === "respond") return error.output;
246
+ throw error;
247
+ }
248
+ }
249
+ /** The caller the flows see: the `authContext` option, or an anonymous `webmcp` caller. */
250
+ async authInfo() {
251
+ const option = this.options.authContext;
252
+ const authContext = typeof option === "function" ? await option() : option;
253
+ const user = authContext?.user;
254
+ const sub = typeof user?.sub === "string" ? user.sub : "webmcp";
255
+ const iss = typeof user?.["iss"] === "string" ? user["iss"] : "webmcp";
256
+ return {
257
+ sessionId: authContext?.sessionId ?? this.sessionId,
258
+ user: { ...user, iss, sub },
259
+ scopes: [],
260
+ clientId: sub,
261
+ ...authContext?.token !== void 0 && { token: authContext.token },
262
+ ...authContext?.extra && { extra: authContext.extra }
263
+ };
264
+ }
265
+ };
266
+
267
+ // plugins/plugin-webmcp/src/webmcp.options.ts
268
+ import { z } from "@frontmcp/lazy-zod";
269
+ function isModelContext(value) {
270
+ return typeof value === "object" && value !== null && typeof value.registerTool === "function";
271
+ }
272
+ var webMcpPluginOptionsSchema = z.object({
273
+ /**
274
+ * Prepended to every exposed tool name, e.g. `'shop.'`, so the page's tools stay apart from
275
+ * other tools on it. Names are then made WebMCP-valid (see `toWebMcpToolName`).
276
+ */
277
+ prefix: z.string().default(""),
278
+ /** Decides which listed tools are exposed. Runs after `availableWhen` and authorities. */
279
+ include: z.custom((value) => typeof value === "function").optional(),
280
+ /** Other origins (e.g. an iframe's parent) the tools are offered to, through WebMCP's `exposedTo`. */
281
+ exposedTo: z.array(z.string().min(1)).optional(),
282
+ /** Auth context the tools are listed and called with. Defaults to an anonymous `webmcp` caller. */
283
+ authContext: z.custom((value) => typeof value === "function" || typeof value === "object" && value !== null).optional(),
284
+ /** The `ModelContext` to register with. Defaults to `document.modelContext`; pass a polyfill or test double. */
285
+ modelContext: z.custom(isModelContext, { message: "modelContext must have a registerTool function" }).optional()
286
+ });
287
+
288
+ // plugins/plugin-webmcp/src/webmcp.plugin.ts
289
+ var WebMcpPlugin = class extends DynamicPlugin {
290
+ options;
291
+ constructor(options = {}) {
292
+ super();
293
+ this.options = webMcpPluginOptionsSchema.parse(options);
294
+ }
295
+ static dynamicProviders(options) {
296
+ const parsedOptions = webMcpPluginOptionsSchema.parse(options);
297
+ return [
298
+ {
299
+ name: "webmcp:bridge",
300
+ provide: WebMcpBridge,
301
+ inject: () => [ScopeEntry],
302
+ useFactory: (scope) => {
303
+ const bridge = new WebMcpBridge(scope, parsedOptions);
304
+ void scope.ready.then(
305
+ () => bridge.start(),
306
+ () => void 0
307
+ // the scope failed to start, and reports that itself
308
+ );
309
+ scope.onDispose(() => bridge.stop());
310
+ return bridge;
311
+ }
312
+ }
313
+ ];
314
+ }
315
+ };
316
+ WebMcpPlugin = __decorateClass([
317
+ Plugin({
318
+ name: "webmcp",
319
+ description: "Exposes the server's tools to in-browser agents through WebMCP (document.modelContext)"
320
+ })
321
+ ], WebMcpPlugin);
322
+ export {
323
+ WebMcpBridge,
324
+ WebMcpPlugin,
325
+ WebMcpPlugin as default,
326
+ isWebMcpSupported,
327
+ toWebMcpToolName,
328
+ webMcpPluginOptionsSchema
329
+ };
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@frontmcp/plugin-webmcp",
3
+ "version": "1.5.7",
4
+ "description": "WebMCP plugin for FrontMCP - expose an in-browser FrontMCP server's tools to browser agents through document.modelContext",
5
+ "author": "AgentFront <info@agentfront.dev>",
6
+ "license": "Apache-2.0",
7
+ "engines": {
8
+ "node": ">=24.0.0"
9
+ },
10
+ "keywords": [
11
+ "mcp",
12
+ "webmcp",
13
+ "modelcontext",
14
+ "browser",
15
+ "agents",
16
+ "plugin",
17
+ "frontmcp",
18
+ "agentfront"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/agentfront/frontmcp.git",
23
+ "directory": "plugins/plugin-webmcp"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/agentfront/frontmcp/issues"
27
+ },
28
+ "homepage": "https://github.com/agentfront/frontmcp/blob/main/plugins/plugin-webmcp/README.md",
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "type": "module",
34
+ "main": "../index.js",
35
+ "module": "./index.mjs",
36
+ "types": "../index.d.ts",
37
+ "sideEffects": false,
38
+ "exports": {
39
+ "./package.json": "../package.json",
40
+ ".": {
41
+ "require": {
42
+ "types": "../index.d.ts",
43
+ "default": "../index.js"
44
+ },
45
+ "import": {
46
+ "types": "../index.d.ts",
47
+ "default": "./index.mjs"
48
+ }
49
+ }
50
+ },
51
+ "dependencies": {
52
+ "@frontmcp/sdk": "1.5.7",
53
+ "@frontmcp/utils": "1.5.7"
54
+ },
55
+ "peerDependencies": {
56
+ "@frontmcp/lazy-zod": "1.5.7"
57
+ },
58
+ "devDependencies": {
59
+ "reflect-metadata": "^0.2.2"
60
+ }
61
+ }
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { default, default as WebMcpPlugin } from './webmcp.plugin';
2
+ export { WebMcpBridge, isWebMcpSupported, toWebMcpToolName, type WebMcpToolResult } from './webmcp.bridge';
3
+ export { webMcpPluginOptionsSchema, type WebMcpAuthContext, type WebMcpListedTool, type WebMcpPluginOptions, type WebMcpPluginOptionsInput, } from './webmcp.options';
4
+ export type { ModelContext, ModelContextRegisterToolOptions, ModelContextRegisteredTool, ModelContextTool, ModelContextToolAnnotations, ModelContextToolExecuteOptions, } from './webmcp.types';
5
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAC3G,OAAO,EACL,yBAAyB,EACzB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,wBAAwB,GAC9B,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EACV,YAAY,EACZ,+BAA+B,EAC/B,0BAA0B,EAC1B,gBAAgB,EAChB,2BAA2B,EAC3B,8BAA8B,GAC/B,MAAM,gBAAgB,CAAC"}
package/index.js ADDED
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __decorateClass = (decorators, target, key, kind) => {
20
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
22
+ if (decorator = decorators[i])
23
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
+ if (kind && result) __defProp(target, key, result);
25
+ return result;
26
+ };
27
+
28
+ // plugins/plugin-webmcp/src/index.ts
29
+ var index_exports = {};
30
+ __export(index_exports, {
31
+ WebMcpBridge: () => WebMcpBridge,
32
+ WebMcpPlugin: () => WebMcpPlugin,
33
+ default: () => WebMcpPlugin,
34
+ isWebMcpSupported: () => isWebMcpSupported,
35
+ toWebMcpToolName: () => toWebMcpToolName,
36
+ webMcpPluginOptionsSchema: () => webMcpPluginOptionsSchema
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+
40
+ // plugins/plugin-webmcp/src/webmcp.plugin.ts
41
+ var import_sdk2 = require("@frontmcp/sdk");
42
+
43
+ // plugins/plugin-webmcp/src/webmcp.bridge.ts
44
+ var import_sdk = require("@frontmcp/sdk");
45
+ var import_utils = require("@frontmcp/utils");
46
+ var MAX_WEBMCP_NAME_LENGTH = 128;
47
+ var INVALID_NAME_CHARACTERS = /[^A-Za-z0-9_.-]/g;
48
+ function resolveDocumentModelContext() {
49
+ const modelContext = globalThis.document?.modelContext;
50
+ return typeof modelContext === "object" && modelContext !== null && typeof modelContext.registerTool === "function" ? modelContext : void 0;
51
+ }
52
+ function isWebMcpSupported() {
53
+ return resolveDocumentModelContext() !== void 0;
54
+ }
55
+ function toWebMcpToolName(name) {
56
+ const cleaned = name.replace(INVALID_NAME_CHARACTERS, "_").slice(0, MAX_WEBMCP_NAME_LENGTH);
57
+ return cleaned.length > 0 ? cleaned : "_";
58
+ }
59
+ function uniqueName(base, taken) {
60
+ if (!taken.has(base)) return base;
61
+ for (let n = 2; ; n++) {
62
+ const suffix = `_${n}`;
63
+ const candidate = base.slice(0, MAX_WEBMCP_NAME_LENGTH - suffix.length) + suffix;
64
+ if (!taken.has(candidate)) return candidate;
65
+ }
66
+ }
67
+ function toWebMcpAnnotations(annotations) {
68
+ const hints = {};
69
+ if (annotations?.readOnlyHint === true) hints.readOnlyHint = true;
70
+ if (annotations?.destructiveHint === true) hints.consequentialHint = true;
71
+ if (annotations?.openWorldHint === true) hints.untrustedContentHint = true;
72
+ return Object.keys(hints).length > 0 ? hints : void 0;
73
+ }
74
+ function textOf(content) {
75
+ return (content ?? []).map((block) => block.type === "text" ? block.text : "").filter((text) => text.length > 0).join("\n");
76
+ }
77
+ function errorBehindFlowControl(error) {
78
+ if (!(error instanceof import_sdk.FlowControl)) return error;
79
+ const original = error.originalError;
80
+ if (error.type === "fail" && original !== void 0) return original;
81
+ return new import_sdk.InternalMcpError(`Flow ended with: ${error.type}`);
82
+ }
83
+ function toAgentError(error) {
84
+ const failure = errorBehindFlowControl(error);
85
+ const publicMessage = failure?.getPublicMessage;
86
+ if (typeof publicMessage === "function") return new Error(publicMessage.call(failure));
87
+ return failure instanceof Error ? failure : new Error(String(failure));
88
+ }
89
+ function isRecord(value) {
90
+ return typeof value === "object" && value !== null && !Array.isArray(value);
91
+ }
92
+ var WebMcpBridge = class {
93
+ constructor(scope, options) {
94
+ this.scope = scope;
95
+ this.options = options;
96
+ this.logger = scope.logger.child("webmcp");
97
+ }
98
+ scope;
99
+ options;
100
+ logger;
101
+ sessionId = `webmcp:${(0, import_utils.randomUUID)()}`;
102
+ registrations = /* @__PURE__ */ new Map();
103
+ /** Registrations the ModelContext refused, by name, so the same refusal is reported once. */
104
+ refused = /* @__PURE__ */ new Map();
105
+ modelContext;
106
+ unsubscribe;
107
+ started = false;
108
+ stopped = false;
109
+ /** A registry change arrived that no sync has picked up yet. */
110
+ pending = false;
111
+ /** The scheduled or running sync loop. */
112
+ run;
113
+ /** WebMCP names of the tools currently registered with the ModelContext. */
114
+ get registeredToolNames() {
115
+ return [...this.registrations.keys()];
116
+ }
117
+ /**
118
+ * Find the ModelContext and keep it in sync with the server's tools. Without one (Node, a browser
119
+ * without WebMCP and no polyfill) the bridge does nothing.
120
+ */
121
+ start() {
122
+ if (this.started || this.stopped) return;
123
+ this.started = true;
124
+ const modelContext = this.options.modelContext ?? resolveDocumentModelContext();
125
+ if (!modelContext) {
126
+ this.logger.debug("WebMCP is not available here (no document.modelContext); tools are not exposed");
127
+ return;
128
+ }
129
+ this.modelContext = modelContext;
130
+ this.unsubscribe = this.scope.tools.subscribe({ immediate: true }, () => this.refresh());
131
+ }
132
+ /**
133
+ * Re-list the server's tools and update the registrations. The bridge does this on every tool
134
+ * registry change; call it when something else changes what the caller may see, such as the
135
+ * `authContext` a function option returns.
136
+ */
137
+ refresh() {
138
+ if (!this.modelContext || this.stopped) return;
139
+ this.pending = true;
140
+ this.run ??= this.drain();
141
+ }
142
+ /** Resolves once no sync is scheduled or running. */
143
+ async whenIdle() {
144
+ while (this.run) await this.run;
145
+ }
146
+ /** Unregister every tool and stop following the registry. Calling it again does nothing. */
147
+ stop() {
148
+ if (this.stopped) return;
149
+ this.stopped = true;
150
+ this.unsubscribe?.();
151
+ this.unsubscribe = void 0;
152
+ for (const registration of this.registrations.values()) registration.controller.abort();
153
+ this.registrations.clear();
154
+ }
155
+ /** Sync until no change is pending. Starts a microtask later, so a burst of changes syncs once. */
156
+ async drain() {
157
+ await Promise.resolve();
158
+ try {
159
+ while (this.pending && !this.stopped) {
160
+ this.pending = false;
161
+ try {
162
+ await this.sync();
163
+ } catch (error) {
164
+ this.logger.warn(`WebMCP sync failed: ${toAgentError(error).message}`);
165
+ }
166
+ }
167
+ } finally {
168
+ this.run = void 0;
169
+ }
170
+ }
171
+ async sync() {
172
+ const desired = this.desiredTools(await this.listTools());
173
+ if (this.stopped) return;
174
+ for (const [name, registration] of this.registrations) {
175
+ if (desired.get(name)?.fingerprint === registration.fingerprint) continue;
176
+ registration.controller.abort();
177
+ this.registrations.delete(name);
178
+ }
179
+ for (const [name, tool] of desired) {
180
+ if (this.registrations.has(name) || this.stopped) continue;
181
+ await this.register(name, tool);
182
+ }
183
+ }
184
+ /** The server's tools as the `'webmcp'` surface sees them, every page of them. */
185
+ async listTools() {
186
+ const tools = [];
187
+ const authInfo = await this.authInfo();
188
+ let cursor;
189
+ do {
190
+ const request = { method: "tools/list", params: cursor === void 0 ? {} : { cursor } };
191
+ const page = await this.exclusive(
192
+ () => this.scope.runFlowForOutput("tools:list-tools", { request, ctx: { authInfo, surface: "webmcp" } })
193
+ );
194
+ tools.push(...page.tools);
195
+ cursor = page.nextCursor;
196
+ } while (cursor);
197
+ return tools;
198
+ }
199
+ desiredTools(listed) {
200
+ const desired = /* @__PURE__ */ new Map();
201
+ for (const tool of listed) {
202
+ if (this.options.include && !this.options.include(tool)) continue;
203
+ const name = uniqueName(toWebMcpToolName(this.options.prefix + tool.name), new Set(desired.keys()));
204
+ const title = tool.title ?? tool.annotations?.title;
205
+ const annotations = toWebMcpAnnotations(tool.annotations);
206
+ const descriptor = {
207
+ name,
208
+ ...title && { title },
209
+ description: tool.description || title || tool.name,
210
+ inputSchema: tool.inputSchema,
211
+ ...annotations && { annotations }
212
+ };
213
+ desired.set(name, { mcpName: tool.name, descriptor, fingerprint: JSON.stringify([tool.name, descriptor]) });
214
+ }
215
+ return desired;
216
+ }
217
+ async register(name, tool) {
218
+ const modelContext = this.modelContext;
219
+ const controller = new AbortController();
220
+ this.registrations.set(name, { mcpName: tool.mcpName, fingerprint: tool.fingerprint, controller });
221
+ try {
222
+ await modelContext.registerTool(
223
+ { ...tool.descriptor, execute: (input, options) => this.execute(tool.mcpName, input, options) },
224
+ { signal: controller.signal, ...this.options.exposedTo && { exposedTo: this.options.exposedTo } }
225
+ );
226
+ this.refused.delete(name);
227
+ } catch (error) {
228
+ if (this.registrations.get(name)?.controller === controller) this.registrations.delete(name);
229
+ controller.abort();
230
+ const message = `WebMCP refused tool "${name}": ${toAgentError(error).message}`;
231
+ if (this.refused.get(name) === tool.fingerprint) {
232
+ this.logger.debug(message);
233
+ } else {
234
+ this.refused.set(name, tool.fingerprint);
235
+ this.logger.warn(message);
236
+ }
237
+ }
238
+ }
239
+ /** Run one agent call through the `tools:call-tool` flow, and translate its result for WebMCP. */
240
+ async execute(mcpName, input, options) {
241
+ let result;
242
+ try {
243
+ const request = {
244
+ method: "tools/call",
245
+ params: { name: mcpName, arguments: isRecord(input) ? input : {} }
246
+ };
247
+ const ctx = {
248
+ authInfo: await this.authInfo(),
249
+ surface: "webmcp",
250
+ ...options?.signal && { signal: options.signal }
251
+ };
252
+ result = await this.exclusive(() => this.scope.runFlowForOutput("tools:call-tool", { request, ctx }));
253
+ } catch (error) {
254
+ throw toAgentError(error);
255
+ }
256
+ if (result.isError) throw new Error(textOf(result.content) || `Tool "${mcpName}" failed`);
257
+ return {
258
+ content: result.content ?? [],
259
+ ...result.structuredContent !== void 0 && { structuredContent: result.structuredContent }
260
+ };
261
+ }
262
+ /**
263
+ * Run a flow as its own request. A browser build without AsyncContext runs requests one at a
264
+ * time; this takes the turn. A flow that answers by `respond` is output, not a failure.
265
+ */
266
+ async exclusive(runFlow) {
267
+ try {
268
+ return await (0, import_utils.runRequestExclusive)(runFlow);
269
+ } catch (error) {
270
+ if (error instanceof import_sdk.FlowControl && error.type === "respond") return error.output;
271
+ throw error;
272
+ }
273
+ }
274
+ /** The caller the flows see: the `authContext` option, or an anonymous `webmcp` caller. */
275
+ async authInfo() {
276
+ const option = this.options.authContext;
277
+ const authContext = typeof option === "function" ? await option() : option;
278
+ const user = authContext?.user;
279
+ const sub = typeof user?.sub === "string" ? user.sub : "webmcp";
280
+ const iss = typeof user?.["iss"] === "string" ? user["iss"] : "webmcp";
281
+ return {
282
+ sessionId: authContext?.sessionId ?? this.sessionId,
283
+ user: { ...user, iss, sub },
284
+ scopes: [],
285
+ clientId: sub,
286
+ ...authContext?.token !== void 0 && { token: authContext.token },
287
+ ...authContext?.extra && { extra: authContext.extra }
288
+ };
289
+ }
290
+ };
291
+
292
+ // plugins/plugin-webmcp/src/webmcp.options.ts
293
+ var import_lazy_zod = require("@frontmcp/lazy-zod");
294
+ function isModelContext(value) {
295
+ return typeof value === "object" && value !== null && typeof value.registerTool === "function";
296
+ }
297
+ var webMcpPluginOptionsSchema = import_lazy_zod.z.object({
298
+ /**
299
+ * Prepended to every exposed tool name, e.g. `'shop.'`, so the page's tools stay apart from
300
+ * other tools on it. Names are then made WebMCP-valid (see `toWebMcpToolName`).
301
+ */
302
+ prefix: import_lazy_zod.z.string().default(""),
303
+ /** Decides which listed tools are exposed. Runs after `availableWhen` and authorities. */
304
+ include: import_lazy_zod.z.custom((value) => typeof value === "function").optional(),
305
+ /** Other origins (e.g. an iframe's parent) the tools are offered to, through WebMCP's `exposedTo`. */
306
+ exposedTo: import_lazy_zod.z.array(import_lazy_zod.z.string().min(1)).optional(),
307
+ /** Auth context the tools are listed and called with. Defaults to an anonymous `webmcp` caller. */
308
+ authContext: import_lazy_zod.z.custom((value) => typeof value === "function" || typeof value === "object" && value !== null).optional(),
309
+ /** The `ModelContext` to register with. Defaults to `document.modelContext`; pass a polyfill or test double. */
310
+ modelContext: import_lazy_zod.z.custom(isModelContext, { message: "modelContext must have a registerTool function" }).optional()
311
+ });
312
+
313
+ // plugins/plugin-webmcp/src/webmcp.plugin.ts
314
+ var WebMcpPlugin = class extends import_sdk2.DynamicPlugin {
315
+ options;
316
+ constructor(options = {}) {
317
+ super();
318
+ this.options = webMcpPluginOptionsSchema.parse(options);
319
+ }
320
+ static dynamicProviders(options) {
321
+ const parsedOptions = webMcpPluginOptionsSchema.parse(options);
322
+ return [
323
+ {
324
+ name: "webmcp:bridge",
325
+ provide: WebMcpBridge,
326
+ inject: () => [import_sdk2.ScopeEntry],
327
+ useFactory: (scope) => {
328
+ const bridge = new WebMcpBridge(scope, parsedOptions);
329
+ void scope.ready.then(
330
+ () => bridge.start(),
331
+ () => void 0
332
+ // the scope failed to start, and reports that itself
333
+ );
334
+ scope.onDispose(() => bridge.stop());
335
+ return bridge;
336
+ }
337
+ }
338
+ ];
339
+ }
340
+ };
341
+ WebMcpPlugin = __decorateClass([
342
+ (0, import_sdk2.Plugin)({
343
+ name: "webmcp",
344
+ description: "Exposes the server's tools to in-browser agents through WebMCP (document.modelContext)"
345
+ })
346
+ ], WebMcpPlugin);
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@frontmcp/plugin-webmcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "WebMCP plugin for FrontMCP - expose an in-browser FrontMCP server's tools to browser agents through document.modelContext",
5
+ "author": "AgentFront <info@agentfront.dev>",
6
+ "license": "Apache-2.0",
7
+ "engines": {
8
+ "node": ">=24.0.0"
9
+ },
10
+ "keywords": [
11
+ "mcp",
12
+ "webmcp",
13
+ "modelcontext",
14
+ "browser",
15
+ "agents",
16
+ "plugin",
17
+ "frontmcp",
18
+ "agentfront"
19
+ ],
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/agentfront/frontmcp.git",
23
+ "directory": "plugins/plugin-webmcp"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/agentfront/frontmcp/issues"
27
+ },
28
+ "homepage": "https://github.com/agentfront/frontmcp/blob/main/plugins/plugin-webmcp/README.md",
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "type": "commonjs",
34
+ "main": "./index.js",
35
+ "module": "./esm/index.mjs",
36
+ "types": "./index.d.ts",
37
+ "sideEffects": false,
38
+ "exports": {
39
+ "./package.json": "./package.json",
40
+ ".": {
41
+ "require": {
42
+ "types": "./index.d.ts",
43
+ "default": "./index.js"
44
+ },
45
+ "import": {
46
+ "types": "./index.d.ts",
47
+ "default": "./esm/index.mjs"
48
+ }
49
+ }
50
+ },
51
+ "dependencies": {
52
+ "@frontmcp/sdk": "1.5.7",
53
+ "@frontmcp/utils": "1.5.7"
54
+ },
55
+ "peerDependencies": {
56
+ "@frontmcp/lazy-zod": "1.5.7"
57
+ },
58
+ "devDependencies": {
59
+ "reflect-metadata": "^0.2.2"
60
+ }
61
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * WebMcpBridge - exposes a FrontMCP server's tools to in-browser agents through WebMCP.
3
+ *
4
+ * It is a transport adapter: it only translates. The tool list comes from the `tools:list-tools`
5
+ * flow and every call runs the `tools:call-tool` flow, both on the `'webmcp'` surface, so
6
+ * `availableWhen`, authorities, hooks and quota apply to an agent's calls as to any other client's.
7
+ */
8
+ import { type CallToolResult, type ScopeEntry } from '@frontmcp/sdk';
9
+ import type { WebMcpPluginOptions } from './webmcp.options';
10
+ import type { ModelContext } from './webmcp.types';
11
+ /** What a WebMCP call resolves to: the MCP result without its `_meta` (and never `isError`). */
12
+ export interface WebMcpToolResult {
13
+ content: CallToolResult['content'];
14
+ structuredContent?: CallToolResult['structuredContent'];
15
+ }
16
+ /** `document.modelContext` in a browser that implements WebMCP (or has a polyfill installed). */
17
+ export declare function resolveDocumentModelContext(): ModelContext | undefined;
18
+ /** Whether this page can register WebMCP tools (`document.modelContext.registerTool` exists). */
19
+ export declare function isWebMcpSupported(): boolean;
20
+ /** Make `name` a valid WebMCP tool name: invalid characters become `_`, cut to 128 characters. */
21
+ export declare function toWebMcpToolName(name: string): string;
22
+ export declare class WebMcpBridge {
23
+ private readonly scope;
24
+ private readonly options;
25
+ private readonly logger;
26
+ private readonly sessionId;
27
+ private readonly registrations;
28
+ /** Registrations the ModelContext refused, by name, so the same refusal is reported once. */
29
+ private readonly refused;
30
+ private modelContext?;
31
+ private unsubscribe?;
32
+ private started;
33
+ private stopped;
34
+ /** A registry change arrived that no sync has picked up yet. */
35
+ private pending;
36
+ /** The scheduled or running sync loop. */
37
+ private run?;
38
+ constructor(scope: ScopeEntry, options: WebMcpPluginOptions);
39
+ /** WebMCP names of the tools currently registered with the ModelContext. */
40
+ get registeredToolNames(): string[];
41
+ /**
42
+ * Find the ModelContext and keep it in sync with the server's tools. Without one (Node, a browser
43
+ * without WebMCP and no polyfill) the bridge does nothing.
44
+ */
45
+ start(): void;
46
+ /**
47
+ * Re-list the server's tools and update the registrations. The bridge does this on every tool
48
+ * registry change; call it when something else changes what the caller may see, such as the
49
+ * `authContext` a function option returns.
50
+ */
51
+ refresh(): void;
52
+ /** Resolves once no sync is scheduled or running. */
53
+ whenIdle(): Promise<void>;
54
+ /** Unregister every tool and stop following the registry. Calling it again does nothing. */
55
+ stop(): void;
56
+ /** Sync until no change is pending. Starts a microtask later, so a burst of changes syncs once. */
57
+ private drain;
58
+ private sync;
59
+ /** The server's tools as the `'webmcp'` surface sees them, every page of them. */
60
+ private listTools;
61
+ private desiredTools;
62
+ private register;
63
+ /** Run one agent call through the `tools:call-tool` flow, and translate its result for WebMCP. */
64
+ private execute;
65
+ /**
66
+ * Run a flow as its own request. A browser build without AsyncContext runs requests one at a
67
+ * time; this takes the turn. A flow that answers by `respond` is output, not a failure.
68
+ */
69
+ private exclusive;
70
+ /** The caller the flows see: the `authContext` option, or an anonymous `webmcp` caller. */
71
+ private authInfo;
72
+ }
73
+ //# sourceMappingURL=webmcp.bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webmcp.bridge.d.ts","sourceRoot":"","sources":["../src/webmcp.bridge.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAGL,KAAK,cAAc,EAEnB,KAAK,UAAU,EAChB,MAAM,eAAe,CAAC;AAGvB,OAAO,KAAK,EAAoB,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC9E,OAAO,KAAK,EACV,YAAY,EAIb,MAAM,gBAAgB,CAAC;AAMxB,gGAAgG;AAChG,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,cAAc,CAAC,SAAS,CAAC,CAAC;IACnC,iBAAiB,CAAC,EAAE,cAAc,CAAC,mBAAmB,CAAC,CAAC;CACzD;AA0BD,iGAAiG;AACjG,wBAAgB,2BAA2B,IAAI,YAAY,GAAG,SAAS,CAOtE;AAED,iGAAiG;AACjG,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AAED,kGAAkG;AAClG,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAGrD;AAsDD,qBAAa,YAAY;IAgBrB,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAhB1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiB;IACxC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA4B;IACtD,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAmC;IACjE,6FAA6F;IAC7F,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;IACrD,OAAO,CAAC,YAAY,CAAC,CAAe;IACpC,OAAO,CAAC,WAAW,CAAC,CAAa;IACjC,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,OAAO,CAAS;IACxB,gEAAgE;IAChE,OAAO,CAAC,OAAO,CAAS;IACxB,0CAA0C;IAC1C,OAAO,CAAC,GAAG,CAAC,CAAgB;gBAGT,KAAK,EAAE,UAAU,EACjB,OAAO,EAAE,mBAAmB;IAK/C,4EAA4E;IAC5E,IAAI,mBAAmB,IAAI,MAAM,EAAE,CAElC;IAED;;;OAGG;IACH,KAAK,IAAI,IAAI;IAab;;;;OAIG;IACH,OAAO,IAAI,IAAI;IAMf,qDAAqD;IAC/C,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAI/B,4FAA4F;IAC5F,IAAI,IAAI,IAAI;IASZ,mGAAmG;YACrF,KAAK;YAgBL,IAAI;IAgBlB,kFAAkF;YACpE,SAAS;IAevB,OAAO,CAAC,YAAY;YAmBN,QAAQ;IAwBtB,kGAAkG;YACpF,OAAO;IA2BrB;;;OAGG;YACW,SAAS;IASvB,2FAA2F;YAC7E,QAAQ;CAevB"}
@@ -0,0 +1,19 @@
1
+ import { z } from '@frontmcp/lazy-zod';
2
+ import type { DirectAuthContext, ListToolsResult } from '@frontmcp/sdk';
3
+ import type { ModelContext } from './webmcp.types';
4
+ /** A tool as the server lists it (`tools/list`), before it is exposed through WebMCP. */
5
+ export type WebMcpListedTool = ListToolsResult['tools'][number];
6
+ /** Who the server sees calling: an auth context, or a function that returns the current one. */
7
+ export type WebMcpAuthContext = DirectAuthContext | (() => DirectAuthContext | Promise<DirectAuthContext>);
8
+ export declare const webMcpPluginOptionsSchema: import("@frontmcp/lazy-zod").ZodObject<{
9
+ prefix: import("@frontmcp/lazy-zod").ZodDefault<import("@frontmcp/lazy-zod").ZodString>;
10
+ include: import("@frontmcp/lazy-zod").ZodOptional<import("zod").ZodCustom<(tool: WebMcpListedTool) => boolean, (tool: WebMcpListedTool) => boolean>>;
11
+ exposedTo: import("@frontmcp/lazy-zod").ZodOptional<import("@frontmcp/lazy-zod").ZodArray<import("@frontmcp/lazy-zod").ZodString>>;
12
+ authContext: import("@frontmcp/lazy-zod").ZodOptional<import("zod").ZodCustom<WebMcpAuthContext, WebMcpAuthContext>>;
13
+ modelContext: import("@frontmcp/lazy-zod").ZodOptional<import("zod").ZodCustom<ModelContext, ModelContext>>;
14
+ }, import("zod/v4/core").$strip>;
15
+ /** Options of `WebMcpPlugin.init()`, as the plugin holds them (defaults applied). */
16
+ export type WebMcpPluginOptions = z.output<typeof webMcpPluginOptionsSchema>;
17
+ /** Options of `WebMcpPlugin.init()`, as passed. */
18
+ export type WebMcpPluginOptionsInput = z.input<typeof webMcpPluginOptionsSchema>;
19
+ //# sourceMappingURL=webmcp.options.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webmcp.options.d.ts","sourceRoot":"","sources":["../src/webmcp.options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAC;AACvC,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAExE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,yFAAyF;AACzF,MAAM,MAAM,gBAAgB,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC;AAEhE,gGAAgG;AAChG,MAAM,MAAM,iBAAiB,GAAG,iBAAiB,GAAG,CAAC,MAAM,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC;AAM3G,eAAO,MAAM,yBAAyB;;qFAOX,gBAAgB,KAAK,OAAO,SAA5B,gBAAgB,KAAK,OAAO;;;;gCAWrD,CAAC;AAEH,qFAAqF;AACrF,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,yBAAyB,CAAC,CAAC;AAE7E,mDAAmD;AACnD,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,yBAAyB,CAAC,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { DynamicPlugin, type ProviderType } from '@frontmcp/sdk';
2
+ import { type WebMcpPluginOptions, type WebMcpPluginOptionsInput } from './webmcp.options';
3
+ /**
4
+ * Exposes the server's tools to in-browser agents through WebMCP (`document.modelContext`).
5
+ *
6
+ * Install it on a server that runs in the page, with `WebMcpPlugin.init()`:
7
+ *
8
+ * ```typescript
9
+ * const server = await create({
10
+ * info: { name: 'shop', version: '1.0.0' },
11
+ * tools: [SearchProducts, AddToCart],
12
+ * plugins: [WebMcpPlugin.init({ prefix: 'shop.' })],
13
+ * });
14
+ * ```
15
+ *
16
+ * Every tool the `'webmcp'` surface may list is registered once the server is ready, kept in sync as
17
+ * tools come and go (including tools added with `server.registerTool()`), and unregistered when the
18
+ * server is disposed. Calls run the `tools:call-tool` flow, so hooks, authorities and quota apply.
19
+ */
20
+ export default class WebMcpPlugin extends DynamicPlugin<WebMcpPluginOptions, WebMcpPluginOptionsInput> {
21
+ readonly options: WebMcpPluginOptions;
22
+ constructor(options?: WebMcpPluginOptionsInput);
23
+ static dynamicProviders(options: WebMcpPluginOptionsInput): ProviderType[];
24
+ }
25
+ //# sourceMappingURL=webmcp.plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webmcp.plugin.d.ts","sourceRoot":"","sources":["../src/webmcp.plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAsB,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;AAGrF,OAAO,EAA6B,KAAK,mBAAmB,EAAE,KAAK,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAEtH;;;;;;;;;;;;;;;;GAgBG;AAKH,MAAM,CAAC,OAAO,OAAO,YAAa,SAAQ,aAAa,CAAC,mBAAmB,EAAE,wBAAwB,CAAC;IACpG,QAAQ,CAAC,OAAO,EAAE,mBAAmB,CAAC;gBAE1B,OAAO,GAAE,wBAA6B;WAKlC,gBAAgB,CAAC,OAAO,EAAE,wBAAwB,GAAG,YAAY,EAAE;CAqBpF"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The part of the WebMCP API (`document.modelContext`) this plugin uses, per the W3C Web Machine
3
+ * Learning CG draft of 2026-09-30 (https://webmachinelearning.github.io/webmcp/).
4
+ *
5
+ * Declared here rather than taken from a types package: the API is still in origin trial and
6
+ * changes between Chrome releases, so the plugin pins the shape it was written against.
7
+ */
8
+ /** Behavioral hints an agent may use to decide how carefully to call a tool. */
9
+ export interface ModelContextToolAnnotations {
10
+ /** The tool only reads state. */
11
+ readOnlyHint?: boolean;
12
+ /** The tool's output may contain content the page does not vouch for. */
13
+ untrustedContentHint?: boolean;
14
+ /** The tool has consequences the user may want to confirm (purchases, deletions, messages). */
15
+ consequentialHint?: boolean;
16
+ }
17
+ /** What `execute` receives besides its input. */
18
+ export interface ModelContextToolExecuteOptions {
19
+ /** Aborted when the agent cancels the call. */
20
+ signal: AbortSignal;
21
+ }
22
+ /** A tool as the page registers it. */
23
+ export interface ModelContextTool {
24
+ /** 1-128 characters from `[A-Za-z0-9_.-]`, unique among the page's tools. */
25
+ name: string;
26
+ title?: string;
27
+ /** Required and non-empty. */
28
+ description: string;
29
+ /** JSON Schema of the input object. */
30
+ inputSchema?: Record<string, unknown>;
31
+ /** Runs the tool. Its result is JSON-serialized for the agent; a rejection is a failed call. */
32
+ execute(input: Record<string, unknown>, options: ModelContextToolExecuteOptions): Promise<unknown>;
33
+ annotations?: ModelContextToolAnnotations;
34
+ }
35
+ /** Options of `registerTool`. Aborting `signal` unregisters the tool. */
36
+ export interface ModelContextRegisterToolOptions {
37
+ /** Other origins (e.g. the parent of an iframe) the tool is offered to. */
38
+ exposedTo?: string[];
39
+ signal?: AbortSignal;
40
+ }
41
+ /** A tool as `getTools()` describes it. */
42
+ export interface ModelContextRegisteredTool {
43
+ name: string;
44
+ title?: string;
45
+ description: string;
46
+ inputSchema?: Record<string, unknown>;
47
+ origin?: string;
48
+ annotations?: ModelContextToolAnnotations;
49
+ }
50
+ /** `document.modelContext`. */
51
+ export interface ModelContext {
52
+ /**
53
+ * Register a tool. Rejects with `InvalidStateError` for a duplicate or invalid name, and with
54
+ * `NotAllowedError` when the `tools` permissions policy denies it.
55
+ */
56
+ registerTool(tool: ModelContextTool, options?: ModelContextRegisterToolOptions): Promise<void>;
57
+ /** The tools registered in this page (and, with `fromOrigins`, those other origins expose to it). */
58
+ getTools?(options?: {
59
+ fromOrigins?: string[];
60
+ }): Promise<ModelContextRegisteredTool[]>;
61
+ /** Run a registered tool, as an in-page agent would. Resolves to the JSON-serialized result. */
62
+ executeTool?(tool: ModelContextRegisteredTool, input?: Record<string, unknown>, options?: {
63
+ signal?: AbortSignal;
64
+ }): Promise<string | null>;
65
+ }
66
+ //# sourceMappingURL=webmcp.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"webmcp.types.d.ts","sourceRoot":"","sources":["../src/webmcp.types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,gFAAgF;AAChF,MAAM,WAAW,2BAA2B;IAC1C,iCAAiC;IACjC,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,yEAAyE;IACzE,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,+FAA+F;IAC/F,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,iDAAiD;AACjD,MAAM,WAAW,8BAA8B;IAC7C,+CAA+C;IAC/C,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,uCAAuC;AACvC,MAAM,WAAW,gBAAgB;IAC/B,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,8BAA8B;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,uCAAuC;IACvC,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,gGAAgG;IAChG,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,EAAE,8BAA8B,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACnG,WAAW,CAAC,EAAE,2BAA2B,CAAC;CAC3C;AAED,yEAAyE;AACzE,MAAM,WAAW,+BAA+B;IAC9C,2EAA2E;IAC3E,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,2CAA2C;AAC3C,MAAM,WAAW,0BAA0B;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,2BAA2B,CAAC;CAC3C;AAED,+BAA+B;AAC/B,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,YAAY,CAAC,IAAI,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,+BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/F,qGAAqG;IACrG,QAAQ,CAAC,CAAC,OAAO,CAAC,EAAE;QAAE,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,OAAO,CAAC,0BAA0B,EAAE,CAAC,CAAC;IACvF,gGAAgG;IAChG,WAAW,CAAC,CACV,IAAI,EAAE,0BAA0B,EAChC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GACjC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;CAC3B"}