@mcp-b/global 0.0.0-beta-20260109203913
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1351 -0
- package/dist/index.d.ts +1061 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.iife.js +34 -0
- package/dist/index.js +1790 -0
- package/dist/index.js.map +1 -0
- package/package.json +96 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1790 @@
|
|
|
1
|
+
import { IframeChildTransport, TabServerTransport } from "@mcp-b/transports";
|
|
2
|
+
import { CallToolRequestSchema, GetPromptRequestSchema, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, Server } from "@mcp-b/webmcp-ts-sdk";
|
|
3
|
+
import { jsonSchemaToZod } from "@composio/json-schema-to-zod";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { zodToJsonSchema as zodToJsonSchema$1 } from "zod-to-json-schema";
|
|
6
|
+
|
|
7
|
+
//#region src/validation.ts
|
|
8
|
+
/**
|
|
9
|
+
* Detect if a schema is a Zod schema object (Record<string, ZodType>)
|
|
10
|
+
* or a JSON Schema object
|
|
11
|
+
*/
|
|
12
|
+
function isZodSchema(schema) {
|
|
13
|
+
if (typeof schema !== "object" || schema === null) return false;
|
|
14
|
+
if ("type" in schema && typeof schema.type === "string") return false;
|
|
15
|
+
const values = Object.values(schema);
|
|
16
|
+
if (values.length === 0) return false;
|
|
17
|
+
return values.some((val) => val instanceof z.ZodType);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Convert JSON Schema to Zod validator
|
|
21
|
+
* Uses @composio/json-schema-to-zod for conversion
|
|
22
|
+
*/
|
|
23
|
+
function jsonSchemaToZod$1(jsonSchema) {
|
|
24
|
+
try {
|
|
25
|
+
return jsonSchemaToZod(jsonSchema);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
console.warn("[Web Model Context] Failed to convert JSON Schema to Zod:", error);
|
|
28
|
+
return z.object({}).passthrough();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Convert Zod schema object to JSON Schema
|
|
33
|
+
* Uses zod-to-json-schema package for comprehensive conversion
|
|
34
|
+
*
|
|
35
|
+
* @param schema - Record of Zod type definitions (e.g., { name: z.string(), age: z.number() })
|
|
36
|
+
* @returns JSON Schema object compatible with MCP InputSchema
|
|
37
|
+
*/
|
|
38
|
+
function zodToJsonSchema(schema) {
|
|
39
|
+
const { $schema: _,...rest } = zodToJsonSchema$1(z.object(schema), {
|
|
40
|
+
$refStrategy: "none",
|
|
41
|
+
target: "jsonSchema7"
|
|
42
|
+
});
|
|
43
|
+
return rest;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Normalize a schema to both JSON Schema and Zod formats
|
|
47
|
+
* Detects which format is provided and converts to the other
|
|
48
|
+
*/
|
|
49
|
+
function normalizeSchema(schema) {
|
|
50
|
+
if (isZodSchema(schema)) return {
|
|
51
|
+
jsonSchema: zodToJsonSchema(schema),
|
|
52
|
+
zodValidator: z.object(schema)
|
|
53
|
+
};
|
|
54
|
+
const jsonSchema = schema;
|
|
55
|
+
return {
|
|
56
|
+
jsonSchema,
|
|
57
|
+
zodValidator: jsonSchemaToZod$1(jsonSchema)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Validate data with Zod schema and return formatted result
|
|
62
|
+
*/
|
|
63
|
+
function validateWithZod(data, validator) {
|
|
64
|
+
const result = validator.safeParse(data);
|
|
65
|
+
if (!result.success) return {
|
|
66
|
+
success: false,
|
|
67
|
+
error: `Validation failed:\n${result.error.errors.map((err) => ` - ${err.path.join(".") || "root"}: ${err.message}`).join("\n")}`
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
success: true,
|
|
71
|
+
data: result.data
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region src/global.ts
|
|
77
|
+
/**
|
|
78
|
+
* Marker property name used to identify polyfill implementations.
|
|
79
|
+
* This constant ensures single source of truth for the marker used in
|
|
80
|
+
* both detection (detectNativeAPI) and definition (WebModelContextTesting).
|
|
81
|
+
*/
|
|
82
|
+
const POLYFILL_MARKER_PROPERTY = "__isWebMCPPolyfill";
|
|
83
|
+
/**
|
|
84
|
+
* Detect if the native Chromium Web Model Context API is available.
|
|
85
|
+
* Checks for both navigator.modelContext and navigator.modelContextTesting,
|
|
86
|
+
* and verifies they are native implementations (not polyfills).
|
|
87
|
+
*
|
|
88
|
+
* Detection uses a marker property (`__isWebMCPPolyfill`) on the testing API
|
|
89
|
+
* to reliably distinguish polyfills from native implementations. This approach
|
|
90
|
+
* works correctly even when class names are minified in production builds.
|
|
91
|
+
*
|
|
92
|
+
* @returns Detection result with flags for native context and testing API availability
|
|
93
|
+
*/
|
|
94
|
+
function detectNativeAPI() {
|
|
95
|
+
if (typeof window === "undefined" || typeof navigator === "undefined") return {
|
|
96
|
+
hasNativeContext: false,
|
|
97
|
+
hasNativeTesting: false
|
|
98
|
+
};
|
|
99
|
+
const modelContext = navigator.modelContext;
|
|
100
|
+
const modelContextTesting = navigator.modelContextTesting;
|
|
101
|
+
if (!modelContext || !modelContextTesting) return {
|
|
102
|
+
hasNativeContext: false,
|
|
103
|
+
hasNativeTesting: false
|
|
104
|
+
};
|
|
105
|
+
if (POLYFILL_MARKER_PROPERTY in modelContextTesting && modelContextTesting[POLYFILL_MARKER_PROPERTY] === true) return {
|
|
106
|
+
hasNativeContext: false,
|
|
107
|
+
hasNativeTesting: false
|
|
108
|
+
};
|
|
109
|
+
return {
|
|
110
|
+
hasNativeContext: true,
|
|
111
|
+
hasNativeTesting: true
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Adapter that wraps the native Chromium Web Model Context API.
|
|
116
|
+
* Synchronizes tool changes from the native API to the MCP bridge,
|
|
117
|
+
* enabling MCP clients to stay in sync with the native tool registry.
|
|
118
|
+
*
|
|
119
|
+
* Key features:
|
|
120
|
+
* - Listens to native tool changes via registerToolsChangedCallback()
|
|
121
|
+
* - Syncs native tools to MCP bridge automatically
|
|
122
|
+
* - Delegates tool execution to native API
|
|
123
|
+
* - Converts native results to MCP ToolResponse format
|
|
124
|
+
*
|
|
125
|
+
* @class NativeModelContextAdapter
|
|
126
|
+
* @implements {InternalModelContext}
|
|
127
|
+
*/
|
|
128
|
+
var NativeModelContextAdapter = class {
|
|
129
|
+
nativeContext;
|
|
130
|
+
nativeTesting;
|
|
131
|
+
bridge;
|
|
132
|
+
syncInProgress = false;
|
|
133
|
+
/**
|
|
134
|
+
* Creates a new NativeModelContextAdapter.
|
|
135
|
+
*
|
|
136
|
+
* @param {MCPBridge} bridge - The MCP bridge instance
|
|
137
|
+
* @param {ModelContext} nativeContext - The native navigator.modelContext
|
|
138
|
+
* @param {ModelContextTesting} nativeTesting - The native navigator.modelContextTesting
|
|
139
|
+
*/
|
|
140
|
+
constructor(bridge, nativeContext, nativeTesting) {
|
|
141
|
+
this.bridge = bridge;
|
|
142
|
+
this.nativeContext = nativeContext;
|
|
143
|
+
this.nativeTesting = nativeTesting;
|
|
144
|
+
this.nativeTesting.registerToolsChangedCallback(() => {
|
|
145
|
+
console.log("[Native Adapter] Tool change detected from native API");
|
|
146
|
+
this.syncToolsFromNative();
|
|
147
|
+
});
|
|
148
|
+
this.syncToolsFromNative();
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Synchronizes tools from the native API to the MCP bridge.
|
|
152
|
+
* Fetches all tools from navigator.modelContextTesting.listTools()
|
|
153
|
+
* and updates the bridge's tool registry.
|
|
154
|
+
*
|
|
155
|
+
* @private
|
|
156
|
+
*/
|
|
157
|
+
syncToolsFromNative() {
|
|
158
|
+
if (this.syncInProgress) return;
|
|
159
|
+
this.syncInProgress = true;
|
|
160
|
+
try {
|
|
161
|
+
const nativeTools = this.nativeTesting.listTools();
|
|
162
|
+
console.log(`[Native Adapter] Syncing ${nativeTools.length} tools from native API`);
|
|
163
|
+
this.bridge.tools.clear();
|
|
164
|
+
for (const toolInfo of nativeTools) try {
|
|
165
|
+
const inputSchema = JSON.parse(toolInfo.inputSchema);
|
|
166
|
+
const validatedTool = {
|
|
167
|
+
name: toolInfo.name,
|
|
168
|
+
description: toolInfo.description,
|
|
169
|
+
inputSchema,
|
|
170
|
+
execute: async (args) => {
|
|
171
|
+
const result = await this.nativeTesting.executeTool(toolInfo.name, JSON.stringify(args));
|
|
172
|
+
return this.convertToToolResponse(result);
|
|
173
|
+
},
|
|
174
|
+
inputValidator: jsonSchemaToZod$1(inputSchema)
|
|
175
|
+
};
|
|
176
|
+
this.bridge.tools.set(toolInfo.name, validatedTool);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
console.error(`[Native Adapter] Failed to sync tool "${toolInfo.name}":`, error);
|
|
179
|
+
}
|
|
180
|
+
this.notifyMCPServers();
|
|
181
|
+
} finally {
|
|
182
|
+
this.syncInProgress = false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Converts native API result to MCP ToolResponse format.
|
|
187
|
+
* Native API returns simplified values (string, number, object, etc.)
|
|
188
|
+
* which need to be wrapped in the MCP CallToolResult format.
|
|
189
|
+
*
|
|
190
|
+
* @param {unknown} result - The result from native executeTool()
|
|
191
|
+
* @returns {ToolResponse} Formatted MCP ToolResponse
|
|
192
|
+
* @private
|
|
193
|
+
*/
|
|
194
|
+
convertToToolResponse(result) {
|
|
195
|
+
if (typeof result === "string") return { content: [{
|
|
196
|
+
type: "text",
|
|
197
|
+
text: result
|
|
198
|
+
}] };
|
|
199
|
+
if (result === void 0 || result === null) return { content: [{
|
|
200
|
+
type: "text",
|
|
201
|
+
text: ""
|
|
202
|
+
}] };
|
|
203
|
+
if (typeof result === "object") return {
|
|
204
|
+
content: [{
|
|
205
|
+
type: "text",
|
|
206
|
+
text: JSON.stringify(result, null, 2)
|
|
207
|
+
}],
|
|
208
|
+
structuredContent: result
|
|
209
|
+
};
|
|
210
|
+
return { content: [{
|
|
211
|
+
type: "text",
|
|
212
|
+
text: String(result)
|
|
213
|
+
}] };
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Notifies all connected MCP servers that the tools list has changed.
|
|
217
|
+
*
|
|
218
|
+
* @private
|
|
219
|
+
*/
|
|
220
|
+
notifyMCPServers() {
|
|
221
|
+
if (this.bridge.tabServer?.notification) this.bridge.tabServer.notification({
|
|
222
|
+
method: "notifications/tools/list_changed",
|
|
223
|
+
params: {}
|
|
224
|
+
});
|
|
225
|
+
if (this.bridge.iframeServer?.notification) this.bridge.iframeServer.notification({
|
|
226
|
+
method: "notifications/tools/list_changed",
|
|
227
|
+
params: {}
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Provides context (tools) to AI models via the native API.
|
|
232
|
+
* Delegates to navigator.modelContext.provideContext().
|
|
233
|
+
* Tool change callback will fire and trigger sync automatically.
|
|
234
|
+
*
|
|
235
|
+
* @param {ModelContextInput} context - Context containing tools to register
|
|
236
|
+
*/
|
|
237
|
+
provideContext(context) {
|
|
238
|
+
console.log("[Native Adapter] Delegating provideContext to native API");
|
|
239
|
+
this.nativeContext.provideContext(context);
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Registers a single tool dynamically via the native API.
|
|
243
|
+
* Delegates to navigator.modelContext.registerTool().
|
|
244
|
+
* Tool change callback will fire and trigger sync automatically.
|
|
245
|
+
*
|
|
246
|
+
* @param {ToolDescriptor} tool - The tool descriptor to register
|
|
247
|
+
* @returns {{unregister: () => void}} Object with unregister function
|
|
248
|
+
*/
|
|
249
|
+
registerTool(tool) {
|
|
250
|
+
console.log(`[Native Adapter] Delegating registerTool("${tool.name}") to native API`);
|
|
251
|
+
return this.nativeContext.registerTool(tool);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Unregisters a tool by name via the native API.
|
|
255
|
+
* Delegates to navigator.modelContext.unregisterTool().
|
|
256
|
+
*
|
|
257
|
+
* @param {string} name - Name of the tool to unregister
|
|
258
|
+
*/
|
|
259
|
+
unregisterTool(name) {
|
|
260
|
+
console.log(`[Native Adapter] Delegating unregisterTool("${name}") to native API`);
|
|
261
|
+
this.nativeContext.unregisterTool(name);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Clears all registered tools via the native API.
|
|
265
|
+
* Delegates to navigator.modelContext.clearContext().
|
|
266
|
+
*/
|
|
267
|
+
clearContext() {
|
|
268
|
+
console.log("[Native Adapter] Delegating clearContext to native API");
|
|
269
|
+
this.nativeContext.clearContext();
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Executes a tool via the native API.
|
|
273
|
+
* Delegates to navigator.modelContextTesting.executeTool() with JSON string args.
|
|
274
|
+
*
|
|
275
|
+
* @param {string} toolName - Name of the tool to execute
|
|
276
|
+
* @param {Record<string, unknown>} args - Arguments to pass to the tool
|
|
277
|
+
* @returns {Promise<ToolResponse>} The tool's response in MCP format
|
|
278
|
+
* @internal
|
|
279
|
+
*/
|
|
280
|
+
async executeTool(toolName, args) {
|
|
281
|
+
console.log(`[Native Adapter] Executing tool "${toolName}" via native API`);
|
|
282
|
+
try {
|
|
283
|
+
const result = await this.nativeTesting.executeTool(toolName, JSON.stringify(args));
|
|
284
|
+
return this.convertToToolResponse(result);
|
|
285
|
+
} catch (error) {
|
|
286
|
+
console.error(`[Native Adapter] Error executing tool "${toolName}":`, error);
|
|
287
|
+
return {
|
|
288
|
+
content: [{
|
|
289
|
+
type: "text",
|
|
290
|
+
text: `Error: ${error instanceof Error ? error.message : String(error)}`
|
|
291
|
+
}],
|
|
292
|
+
isError: true
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Lists all registered tools from the MCP bridge.
|
|
298
|
+
* Returns tools synced from the native API.
|
|
299
|
+
*
|
|
300
|
+
* @returns {Array<{name: string, description: string, inputSchema: InputSchema}>} Array of tool descriptors
|
|
301
|
+
*/
|
|
302
|
+
listTools() {
|
|
303
|
+
return Array.from(this.bridge.tools.values()).map((tool) => ({
|
|
304
|
+
name: tool.name,
|
|
305
|
+
description: tool.description,
|
|
306
|
+
inputSchema: tool.inputSchema,
|
|
307
|
+
...tool.outputSchema && { outputSchema: tool.outputSchema },
|
|
308
|
+
...tool.annotations && { annotations: tool.annotations }
|
|
309
|
+
}));
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Registers a resource dynamically.
|
|
313
|
+
* Note: Native Chromium API does not yet support resources.
|
|
314
|
+
* This is a polyfill-only feature.
|
|
315
|
+
*/
|
|
316
|
+
registerResource(_resource) {
|
|
317
|
+
console.warn("[Native Adapter] registerResource is not supported by native API");
|
|
318
|
+
return { unregister: () => {} };
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Unregisters a resource by URI.
|
|
322
|
+
* Note: Native Chromium API does not yet support resources.
|
|
323
|
+
*/
|
|
324
|
+
unregisterResource(_uri) {
|
|
325
|
+
console.warn("[Native Adapter] unregisterResource is not supported by native API");
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Lists all registered resources.
|
|
329
|
+
* Note: Native Chromium API does not yet support resources.
|
|
330
|
+
*/
|
|
331
|
+
listResources() {
|
|
332
|
+
return [];
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Lists all resource templates.
|
|
336
|
+
* Note: Native Chromium API does not yet support resources.
|
|
337
|
+
*/
|
|
338
|
+
listResourceTemplates() {
|
|
339
|
+
return [];
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Reads a resource by URI.
|
|
343
|
+
* Note: Native Chromium API does not yet support resources.
|
|
344
|
+
* @internal
|
|
345
|
+
*/
|
|
346
|
+
async readResource(_uri) {
|
|
347
|
+
throw new Error("[Native Adapter] readResource is not supported by native API");
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Registers a prompt dynamically.
|
|
351
|
+
* Note: Native Chromium API does not yet support prompts.
|
|
352
|
+
* This is a polyfill-only feature.
|
|
353
|
+
*/
|
|
354
|
+
registerPrompt(_prompt) {
|
|
355
|
+
console.warn("[Native Adapter] registerPrompt is not supported by native API");
|
|
356
|
+
return { unregister: () => {} };
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Unregisters a prompt by name.
|
|
360
|
+
* Note: Native Chromium API does not yet support prompts.
|
|
361
|
+
*/
|
|
362
|
+
unregisterPrompt(_name) {
|
|
363
|
+
console.warn("[Native Adapter] unregisterPrompt is not supported by native API");
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Lists all registered prompts.
|
|
367
|
+
* Note: Native Chromium API does not yet support prompts.
|
|
368
|
+
*/
|
|
369
|
+
listPrompts() {
|
|
370
|
+
return [];
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Gets a prompt with arguments.
|
|
374
|
+
* Note: Native Chromium API does not yet support prompts.
|
|
375
|
+
* @internal
|
|
376
|
+
*/
|
|
377
|
+
async getPrompt(_name, _args) {
|
|
378
|
+
throw new Error("[Native Adapter] getPrompt is not supported by native API");
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Adds an event listener for tool call events.
|
|
382
|
+
* Delegates to the native API's addEventListener.
|
|
383
|
+
*
|
|
384
|
+
* @param {'toolcall'} type - Event type
|
|
385
|
+
* @param {(event: ToolCallEvent) => void | Promise<void>} listener - Event handler
|
|
386
|
+
* @param {boolean | AddEventListenerOptions} [options] - Event listener options
|
|
387
|
+
*/
|
|
388
|
+
addEventListener(type, listener, options) {
|
|
389
|
+
this.nativeContext.addEventListener(type, listener, options);
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Removes an event listener for tool call events.
|
|
393
|
+
* Delegates to the native API's removeEventListener.
|
|
394
|
+
*
|
|
395
|
+
* @param {'toolcall'} type - Event type
|
|
396
|
+
* @param {(event: ToolCallEvent) => void | Promise<void>} listener - Event handler
|
|
397
|
+
* @param {boolean | EventListenerOptions} [options] - Event listener options
|
|
398
|
+
*/
|
|
399
|
+
removeEventListener(type, listener, options) {
|
|
400
|
+
this.nativeContext.removeEventListener(type, listener, options);
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Dispatches a tool call event.
|
|
404
|
+
* Delegates to the native API's dispatchEvent.
|
|
405
|
+
*
|
|
406
|
+
* @param {Event} event - The event to dispatch
|
|
407
|
+
* @returns {boolean} False if event was cancelled, true otherwise
|
|
408
|
+
*/
|
|
409
|
+
dispatchEvent(event) {
|
|
410
|
+
return this.nativeContext.dispatchEvent(event);
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Request an LLM completion from the connected client.
|
|
414
|
+
* Note: Native Chromium API does not yet support sampling.
|
|
415
|
+
* This is handled by the polyfill.
|
|
416
|
+
*/
|
|
417
|
+
async createMessage(params) {
|
|
418
|
+
console.log("[Native Adapter] Requesting sampling from client");
|
|
419
|
+
const underlyingServer = this.bridge.tabServer.server;
|
|
420
|
+
if (!underlyingServer?.createMessage) throw new Error("Sampling is not supported: no connected client with sampling capability");
|
|
421
|
+
return underlyingServer.createMessage(params);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Request user input from the connected client.
|
|
425
|
+
* Note: Native Chromium API does not yet support elicitation.
|
|
426
|
+
* This is handled by the polyfill.
|
|
427
|
+
*/
|
|
428
|
+
async elicitInput(params) {
|
|
429
|
+
console.log("[Native Adapter] Requesting elicitation from client");
|
|
430
|
+
const underlyingServer = this.bridge.tabServer.server;
|
|
431
|
+
if (!underlyingServer?.elicitInput) throw new Error("Elicitation is not supported: no connected client with elicitation capability");
|
|
432
|
+
return underlyingServer.elicitInput(params);
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
/**
|
|
436
|
+
* ToolCallEvent implementation for the Web Model Context API.
|
|
437
|
+
* Represents an event fired when a tool is called, allowing event listeners
|
|
438
|
+
* to intercept and provide custom responses.
|
|
439
|
+
*
|
|
440
|
+
* @class WebToolCallEvent
|
|
441
|
+
* @extends {Event}
|
|
442
|
+
* @implements {ToolCallEvent}
|
|
443
|
+
*/
|
|
444
|
+
var WebToolCallEvent = class extends Event {
|
|
445
|
+
name;
|
|
446
|
+
arguments;
|
|
447
|
+
_response = null;
|
|
448
|
+
_responded = false;
|
|
449
|
+
/**
|
|
450
|
+
* Creates a new ToolCallEvent.
|
|
451
|
+
*
|
|
452
|
+
* @param {string} toolName - Name of the tool being called
|
|
453
|
+
* @param {Record<string, unknown>} args - Validated arguments for the tool
|
|
454
|
+
*/
|
|
455
|
+
constructor(toolName, args) {
|
|
456
|
+
super("toolcall", { cancelable: true });
|
|
457
|
+
this.name = toolName;
|
|
458
|
+
this.arguments = args;
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Provides a response for this tool call, preventing the default tool execution.
|
|
462
|
+
*
|
|
463
|
+
* @param {ToolResponse} response - The response to use instead of executing the tool
|
|
464
|
+
* @throws {Error} If a response has already been provided
|
|
465
|
+
*/
|
|
466
|
+
respondWith(response) {
|
|
467
|
+
if (this._responded) throw new Error("Response already provided for this tool call");
|
|
468
|
+
this._response = response;
|
|
469
|
+
this._responded = true;
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* Gets the response provided via respondWith().
|
|
473
|
+
*
|
|
474
|
+
* @returns {ToolResponse | null} The response, or null if none provided
|
|
475
|
+
*/
|
|
476
|
+
getResponse() {
|
|
477
|
+
return this._response;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Checks whether a response has been provided for this tool call.
|
|
481
|
+
*
|
|
482
|
+
* @returns {boolean} True if respondWith() was called
|
|
483
|
+
*/
|
|
484
|
+
hasResponse() {
|
|
485
|
+
return this._responded;
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
/**
|
|
489
|
+
* Time window in milliseconds to detect rapid duplicate tool registrations.
|
|
490
|
+
* Used to filter out double-registrations caused by React Strict Mode.
|
|
491
|
+
*/
|
|
492
|
+
const RAPID_DUPLICATE_WINDOW_MS = 50;
|
|
493
|
+
/**
|
|
494
|
+
* Testing API implementation for the Model Context Protocol.
|
|
495
|
+
* Provides debugging, mocking, and testing capabilities for tool execution.
|
|
496
|
+
* Implements both Chromium native methods and polyfill-specific extensions.
|
|
497
|
+
*
|
|
498
|
+
* @class WebModelContextTesting
|
|
499
|
+
* @implements {ModelContextTesting}
|
|
500
|
+
*/
|
|
501
|
+
var WebModelContextTesting = class {
|
|
502
|
+
/**
|
|
503
|
+
* Marker property to identify this as a polyfill implementation.
|
|
504
|
+
* Used by detectNativeAPI() to distinguish polyfill from native Chromium API.
|
|
505
|
+
* This approach works reliably even when class names are minified in production builds.
|
|
506
|
+
*
|
|
507
|
+
* @see POLYFILL_MARKER_PROPERTY - The constant defining this property name
|
|
508
|
+
* @see MayHavePolyfillMarker - The interface for type-safe detection
|
|
509
|
+
*/
|
|
510
|
+
[POLYFILL_MARKER_PROPERTY] = true;
|
|
511
|
+
toolCallHistory = [];
|
|
512
|
+
mockResponses = /* @__PURE__ */ new Map();
|
|
513
|
+
toolsChangedCallbacks = /* @__PURE__ */ new Set();
|
|
514
|
+
bridge;
|
|
515
|
+
/**
|
|
516
|
+
* Creates a new WebModelContextTesting instance.
|
|
517
|
+
*
|
|
518
|
+
* @param {MCPBridge} bridge - The MCP bridge instance to test
|
|
519
|
+
*/
|
|
520
|
+
constructor(bridge) {
|
|
521
|
+
this.bridge = bridge;
|
|
522
|
+
}
|
|
523
|
+
/**
|
|
524
|
+
* Records a tool call in the history.
|
|
525
|
+
* Called internally by WebModelContext when tools are executed.
|
|
526
|
+
*
|
|
527
|
+
* @param {string} toolName - Name of the tool that was called
|
|
528
|
+
* @param {Record<string, unknown>} args - Arguments passed to the tool
|
|
529
|
+
* @internal
|
|
530
|
+
*/
|
|
531
|
+
recordToolCall(toolName, args) {
|
|
532
|
+
this.toolCallHistory.push({
|
|
533
|
+
toolName,
|
|
534
|
+
arguments: args,
|
|
535
|
+
timestamp: Date.now()
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Checks if a mock response is registered for a specific tool.
|
|
540
|
+
*
|
|
541
|
+
* @param {string} toolName - Name of the tool to check
|
|
542
|
+
* @returns {boolean} True if a mock response exists
|
|
543
|
+
* @internal
|
|
544
|
+
*/
|
|
545
|
+
hasMockResponse(toolName) {
|
|
546
|
+
return this.mockResponses.has(toolName);
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* Retrieves the mock response for a specific tool.
|
|
550
|
+
*
|
|
551
|
+
* @param {string} toolName - Name of the tool
|
|
552
|
+
* @returns {ToolResponse | undefined} The mock response, or undefined if none exists
|
|
553
|
+
* @internal
|
|
554
|
+
*/
|
|
555
|
+
getMockResponse(toolName) {
|
|
556
|
+
return this.mockResponses.get(toolName);
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Notifies all registered callbacks that the tools list has changed.
|
|
560
|
+
* Called internally when tools are registered, unregistered, or cleared.
|
|
561
|
+
*
|
|
562
|
+
* @internal
|
|
563
|
+
*/
|
|
564
|
+
notifyToolsChanged() {
|
|
565
|
+
for (const callback of this.toolsChangedCallbacks) try {
|
|
566
|
+
callback();
|
|
567
|
+
} catch (error) {
|
|
568
|
+
console.error("[Model Context Testing] Error in tools changed callback:", error);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Executes a tool directly with JSON string input (Chromium native API).
|
|
573
|
+
* Parses the JSON input, validates it, and executes the tool.
|
|
574
|
+
*
|
|
575
|
+
* @param {string} toolName - Name of the tool to execute
|
|
576
|
+
* @param {string} inputArgsJson - JSON string of input arguments
|
|
577
|
+
* @returns {Promise<unknown>} The tool's result, or undefined on error
|
|
578
|
+
* @throws {SyntaxError} If the input JSON is invalid
|
|
579
|
+
* @throws {Error} If the tool does not exist
|
|
580
|
+
*/
|
|
581
|
+
async executeTool(toolName, inputArgsJson) {
|
|
582
|
+
console.log(`[Model Context Testing] Executing tool: ${toolName}`);
|
|
583
|
+
let args;
|
|
584
|
+
try {
|
|
585
|
+
args = JSON.parse(inputArgsJson);
|
|
586
|
+
} catch (error) {
|
|
587
|
+
throw new SyntaxError(`Invalid JSON input: ${error instanceof Error ? error.message : String(error)}`);
|
|
588
|
+
}
|
|
589
|
+
if (!this.bridge.tools.get(toolName)) throw new Error(`Tool not found: ${toolName}`);
|
|
590
|
+
const result = await this.bridge.modelContext.executeTool(toolName, args);
|
|
591
|
+
if (result.isError) return;
|
|
592
|
+
if (result.structuredContent) return result.structuredContent;
|
|
593
|
+
if (result.content && result.content.length > 0) {
|
|
594
|
+
const firstContent = result.content[0];
|
|
595
|
+
if (firstContent && firstContent.type === "text") return firstContent.text;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Lists all registered tools with inputSchema as JSON string (Chromium native API).
|
|
600
|
+
* Returns an array of ToolInfo objects where inputSchema is stringified.
|
|
601
|
+
*
|
|
602
|
+
* @returns {Array<{name: string, description: string, inputSchema: string}>} Array of tool information
|
|
603
|
+
*/
|
|
604
|
+
listTools() {
|
|
605
|
+
return this.bridge.modelContext.listTools().map((tool) => ({
|
|
606
|
+
name: tool.name,
|
|
607
|
+
description: tool.description,
|
|
608
|
+
inputSchema: JSON.stringify(tool.inputSchema)
|
|
609
|
+
}));
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Registers a callback that fires when the tools list changes (Chromium native API).
|
|
613
|
+
* The callback will be invoked on registerTool, unregisterTool, provideContext, and clearContext.
|
|
614
|
+
*
|
|
615
|
+
* @param {() => void} callback - Function to call when tools change
|
|
616
|
+
*/
|
|
617
|
+
registerToolsChangedCallback(callback) {
|
|
618
|
+
this.toolsChangedCallbacks.add(callback);
|
|
619
|
+
console.log("[Model Context Testing] Tools changed callback registered");
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Gets all tool calls that have been recorded (polyfill extension).
|
|
623
|
+
*
|
|
624
|
+
* @returns {Array<{toolName: string, arguments: Record<string, unknown>, timestamp: number}>} Tool call history
|
|
625
|
+
*/
|
|
626
|
+
getToolCalls() {
|
|
627
|
+
return [...this.toolCallHistory];
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Clears the tool call history (polyfill extension).
|
|
631
|
+
*/
|
|
632
|
+
clearToolCalls() {
|
|
633
|
+
this.toolCallHistory = [];
|
|
634
|
+
console.log("[Model Context Testing] Tool call history cleared");
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Sets a mock response for a specific tool (polyfill extension).
|
|
638
|
+
* When set, the tool's execute function will be bypassed.
|
|
639
|
+
*
|
|
640
|
+
* @param {string} toolName - Name of the tool to mock
|
|
641
|
+
* @param {ToolResponse} response - The mock response to return
|
|
642
|
+
*/
|
|
643
|
+
setMockToolResponse(toolName, response) {
|
|
644
|
+
this.mockResponses.set(toolName, response);
|
|
645
|
+
console.log(`[Model Context Testing] Mock response set for tool: ${toolName}`);
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Clears the mock response for a specific tool (polyfill extension).
|
|
649
|
+
*
|
|
650
|
+
* @param {string} toolName - Name of the tool
|
|
651
|
+
*/
|
|
652
|
+
clearMockToolResponse(toolName) {
|
|
653
|
+
this.mockResponses.delete(toolName);
|
|
654
|
+
console.log(`[Model Context Testing] Mock response cleared for tool: ${toolName}`);
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Clears all mock tool responses (polyfill extension).
|
|
658
|
+
*/
|
|
659
|
+
clearAllMockToolResponses() {
|
|
660
|
+
this.mockResponses.clear();
|
|
661
|
+
console.log("[Model Context Testing] All mock responses cleared");
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Gets the current tools registered in the system (polyfill extension).
|
|
665
|
+
*
|
|
666
|
+
* @returns {ReturnType<InternalModelContext['listTools']>} Array of registered tools
|
|
667
|
+
*/
|
|
668
|
+
getRegisteredTools() {
|
|
669
|
+
return this.bridge.modelContext.listTools();
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Resets the entire testing state (polyfill extension).
|
|
673
|
+
* Clears both tool call history and all mock responses.
|
|
674
|
+
*/
|
|
675
|
+
reset() {
|
|
676
|
+
this.clearToolCalls();
|
|
677
|
+
this.clearAllMockToolResponses();
|
|
678
|
+
console.log("[Model Context Testing] Testing state reset");
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
/**
|
|
682
|
+
* ModelContext implementation that bridges to the Model Context Protocol SDK.
|
|
683
|
+
* Implements the W3C Web Model Context API proposal with two-bucket tool management:
|
|
684
|
+
* - Bucket A (provideContextTools): Tools registered via provideContext()
|
|
685
|
+
* - Bucket B (dynamicTools): Tools registered via registerTool()
|
|
686
|
+
*
|
|
687
|
+
* This separation ensures that component-scoped dynamic tools persist across
|
|
688
|
+
* app-level provideContext() calls.
|
|
689
|
+
*
|
|
690
|
+
* @class WebModelContext
|
|
691
|
+
* @implements {InternalModelContext}
|
|
692
|
+
*/
|
|
693
|
+
var WebModelContext = class {
|
|
694
|
+
bridge;
|
|
695
|
+
eventTarget;
|
|
696
|
+
provideContextTools;
|
|
697
|
+
dynamicTools;
|
|
698
|
+
provideContextResources;
|
|
699
|
+
dynamicResources;
|
|
700
|
+
provideContextPrompts;
|
|
701
|
+
dynamicPrompts;
|
|
702
|
+
toolRegistrationTimestamps;
|
|
703
|
+
resourceRegistrationTimestamps;
|
|
704
|
+
promptRegistrationTimestamps;
|
|
705
|
+
toolUnregisterFunctions;
|
|
706
|
+
resourceUnregisterFunctions;
|
|
707
|
+
promptUnregisterFunctions;
|
|
708
|
+
/**
|
|
709
|
+
* Tracks which list change notifications are pending.
|
|
710
|
+
* Uses microtask-based batching to coalesce rapid registrations
|
|
711
|
+
* (e.g., React mount phase) into a single notification per list type.
|
|
712
|
+
*/
|
|
713
|
+
pendingNotifications = /* @__PURE__ */ new Set();
|
|
714
|
+
testingAPI;
|
|
715
|
+
/**
|
|
716
|
+
* Creates a new WebModelContext instance.
|
|
717
|
+
*
|
|
718
|
+
* @param {MCPBridge} bridge - The MCP bridge to use for communication
|
|
719
|
+
*/
|
|
720
|
+
constructor(bridge) {
|
|
721
|
+
this.bridge = bridge;
|
|
722
|
+
this.eventTarget = new EventTarget();
|
|
723
|
+
this.provideContextTools = /* @__PURE__ */ new Map();
|
|
724
|
+
this.dynamicTools = /* @__PURE__ */ new Map();
|
|
725
|
+
this.toolRegistrationTimestamps = /* @__PURE__ */ new Map();
|
|
726
|
+
this.toolUnregisterFunctions = /* @__PURE__ */ new Map();
|
|
727
|
+
this.provideContextResources = /* @__PURE__ */ new Map();
|
|
728
|
+
this.dynamicResources = /* @__PURE__ */ new Map();
|
|
729
|
+
this.resourceRegistrationTimestamps = /* @__PURE__ */ new Map();
|
|
730
|
+
this.resourceUnregisterFunctions = /* @__PURE__ */ new Map();
|
|
731
|
+
this.provideContextPrompts = /* @__PURE__ */ new Map();
|
|
732
|
+
this.dynamicPrompts = /* @__PURE__ */ new Map();
|
|
733
|
+
this.promptRegistrationTimestamps = /* @__PURE__ */ new Map();
|
|
734
|
+
this.promptUnregisterFunctions = /* @__PURE__ */ new Map();
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Sets the testing API instance.
|
|
738
|
+
* Called during initialization to enable testing features.
|
|
739
|
+
*
|
|
740
|
+
* @param {WebModelContextTesting} testingAPI - The testing API instance
|
|
741
|
+
* @internal
|
|
742
|
+
*/
|
|
743
|
+
setTestingAPI(testingAPI) {
|
|
744
|
+
this.testingAPI = testingAPI;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Adds an event listener for tool call events.
|
|
748
|
+
*
|
|
749
|
+
* @param {'toolcall'} type - Event type (only 'toolcall' is supported)
|
|
750
|
+
* @param {(event: ToolCallEvent) => void | Promise<void>} listener - Event handler function
|
|
751
|
+
* @param {boolean | AddEventListenerOptions} [options] - Event listener options
|
|
752
|
+
*/
|
|
753
|
+
addEventListener(type, listener, options) {
|
|
754
|
+
this.eventTarget.addEventListener(type, listener, options);
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Removes an event listener for tool call events.
|
|
758
|
+
*
|
|
759
|
+
* @param {'toolcall'} type - Event type (only 'toolcall' is supported)
|
|
760
|
+
* @param {(event: ToolCallEvent) => void | Promise<void>} listener - Event handler function
|
|
761
|
+
* @param {boolean | EventListenerOptions} [options] - Event listener options
|
|
762
|
+
*/
|
|
763
|
+
removeEventListener(type, listener, options) {
|
|
764
|
+
this.eventTarget.removeEventListener(type, listener, options);
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Dispatches a tool call event to all registered listeners.
|
|
768
|
+
*
|
|
769
|
+
* @param {Event} event - The event to dispatch
|
|
770
|
+
* @returns {boolean} False if event was cancelled, true otherwise
|
|
771
|
+
*/
|
|
772
|
+
dispatchEvent(event) {
|
|
773
|
+
return this.eventTarget.dispatchEvent(event);
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Provides context (tools, resources, prompts) to AI models by registering base items (Bucket A).
|
|
777
|
+
* Clears and replaces all previously registered base items while preserving
|
|
778
|
+
* dynamic items registered via register* methods.
|
|
779
|
+
*
|
|
780
|
+
* @param {ModelContextInput} context - Context containing tools, resources, and prompts to register
|
|
781
|
+
* @throws {Error} If a name/uri collides with existing dynamic items
|
|
782
|
+
*/
|
|
783
|
+
provideContext(context) {
|
|
784
|
+
const toolCount = context.tools?.length ?? 0;
|
|
785
|
+
const resourceCount = context.resources?.length ?? 0;
|
|
786
|
+
const promptCount = context.prompts?.length ?? 0;
|
|
787
|
+
console.log(`[Web Model Context] provideContext: ${toolCount} tools, ${resourceCount} resources, ${promptCount} prompts`);
|
|
788
|
+
this.provideContextTools.clear();
|
|
789
|
+
this.provideContextResources.clear();
|
|
790
|
+
this.provideContextPrompts.clear();
|
|
791
|
+
for (const tool of context.tools ?? []) {
|
|
792
|
+
if (this.dynamicTools.has(tool.name)) throw new Error(`[Web Model Context] Tool name collision: "${tool.name}" is already registered via registerTool(). Please use a different name or unregister the dynamic tool first.`);
|
|
793
|
+
const { jsonSchema: inputJson, zodValidator: inputZod } = normalizeSchema(tool.inputSchema);
|
|
794
|
+
const normalizedOutput = tool.outputSchema ? normalizeSchema(tool.outputSchema) : null;
|
|
795
|
+
const validatedTool = {
|
|
796
|
+
name: tool.name,
|
|
797
|
+
description: tool.description,
|
|
798
|
+
inputSchema: inputJson,
|
|
799
|
+
...normalizedOutput && { outputSchema: normalizedOutput.jsonSchema },
|
|
800
|
+
...tool.annotations && { annotations: tool.annotations },
|
|
801
|
+
execute: tool.execute,
|
|
802
|
+
inputValidator: inputZod,
|
|
803
|
+
...normalizedOutput && { outputValidator: normalizedOutput.zodValidator }
|
|
804
|
+
};
|
|
805
|
+
this.provideContextTools.set(tool.name, validatedTool);
|
|
806
|
+
}
|
|
807
|
+
for (const resource of context.resources ?? []) {
|
|
808
|
+
if (this.dynamicResources.has(resource.uri)) throw new Error(`[Web Model Context] Resource URI collision: "${resource.uri}" is already registered via registerResource(). Please use a different URI or unregister the dynamic resource first.`);
|
|
809
|
+
const validatedResource = this.validateResource(resource);
|
|
810
|
+
this.provideContextResources.set(resource.uri, validatedResource);
|
|
811
|
+
}
|
|
812
|
+
for (const prompt of context.prompts ?? []) {
|
|
813
|
+
if (this.dynamicPrompts.has(prompt.name)) throw new Error(`[Web Model Context] Prompt name collision: "${prompt.name}" is already registered via registerPrompt(). Please use a different name or unregister the dynamic prompt first.`);
|
|
814
|
+
const validatedPrompt = this.validatePrompt(prompt);
|
|
815
|
+
this.provideContextPrompts.set(prompt.name, validatedPrompt);
|
|
816
|
+
}
|
|
817
|
+
this.updateBridgeTools();
|
|
818
|
+
this.updateBridgeResources();
|
|
819
|
+
this.updateBridgePrompts();
|
|
820
|
+
this.scheduleListChanged("tools");
|
|
821
|
+
this.scheduleListChanged("resources");
|
|
822
|
+
this.scheduleListChanged("prompts");
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Validates and normalizes a resource descriptor.
|
|
826
|
+
* @private
|
|
827
|
+
*/
|
|
828
|
+
validateResource(resource) {
|
|
829
|
+
const templateParamRegex = /\{([^}]+)\}/g;
|
|
830
|
+
const templateParams = [];
|
|
831
|
+
for (const match of resource.uri.matchAll(templateParamRegex)) {
|
|
832
|
+
const paramName = match[1];
|
|
833
|
+
if (paramName) templateParams.push(paramName);
|
|
834
|
+
}
|
|
835
|
+
return {
|
|
836
|
+
uri: resource.uri,
|
|
837
|
+
name: resource.name,
|
|
838
|
+
description: resource.description,
|
|
839
|
+
mimeType: resource.mimeType,
|
|
840
|
+
read: resource.read,
|
|
841
|
+
isTemplate: templateParams.length > 0,
|
|
842
|
+
templateParams
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Validates and normalizes a prompt descriptor.
|
|
847
|
+
* @private
|
|
848
|
+
*/
|
|
849
|
+
validatePrompt(prompt) {
|
|
850
|
+
let argsSchema;
|
|
851
|
+
let argsValidator;
|
|
852
|
+
if (prompt.argsSchema) {
|
|
853
|
+
const normalized = normalizeSchema(prompt.argsSchema);
|
|
854
|
+
argsSchema = normalized.jsonSchema;
|
|
855
|
+
argsValidator = normalized.zodValidator;
|
|
856
|
+
}
|
|
857
|
+
return {
|
|
858
|
+
name: prompt.name,
|
|
859
|
+
description: prompt.description,
|
|
860
|
+
argsSchema,
|
|
861
|
+
get: prompt.get,
|
|
862
|
+
argsValidator
|
|
863
|
+
};
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* Registers a single tool dynamically (Bucket B).
|
|
867
|
+
* Dynamic tools persist across provideContext() calls and can be independently managed.
|
|
868
|
+
*
|
|
869
|
+
* @param {ToolDescriptor} tool - The tool descriptor to register
|
|
870
|
+
* @returns {{unregister: () => void}} Object with unregister function
|
|
871
|
+
* @throws {Error} If tool name collides with existing tools
|
|
872
|
+
*/
|
|
873
|
+
registerTool(tool) {
|
|
874
|
+
console.log(`[Web Model Context] Registering tool dynamically: ${tool.name}`);
|
|
875
|
+
const now = Date.now();
|
|
876
|
+
const lastRegistration = this.toolRegistrationTimestamps.get(tool.name);
|
|
877
|
+
if (lastRegistration && now - lastRegistration < RAPID_DUPLICATE_WINDOW_MS) {
|
|
878
|
+
console.warn(`[Web Model Context] Tool "${tool.name}" registered multiple times within ${RAPID_DUPLICATE_WINDOW_MS}ms. This is likely due to React Strict Mode double-mounting. Ignoring duplicate registration.`);
|
|
879
|
+
const existingUnregister = this.toolUnregisterFunctions.get(tool.name);
|
|
880
|
+
if (existingUnregister) return { unregister: existingUnregister };
|
|
881
|
+
}
|
|
882
|
+
if (this.provideContextTools.has(tool.name)) throw new Error(`[Web Model Context] Tool name collision: "${tool.name}" is already registered via provideContext(). Please use a different name or update your provideContext() call.`);
|
|
883
|
+
if (this.dynamicTools.has(tool.name)) throw new Error(`[Web Model Context] Tool name collision: "${tool.name}" is already registered via registerTool(). Please unregister it first or use a different name.`);
|
|
884
|
+
const { jsonSchema: inputJson, zodValidator: inputZod } = normalizeSchema(tool.inputSchema);
|
|
885
|
+
const normalizedOutput = tool.outputSchema ? normalizeSchema(tool.outputSchema) : null;
|
|
886
|
+
const validatedTool = {
|
|
887
|
+
name: tool.name,
|
|
888
|
+
description: tool.description,
|
|
889
|
+
inputSchema: inputJson,
|
|
890
|
+
...normalizedOutput && { outputSchema: normalizedOutput.jsonSchema },
|
|
891
|
+
...tool.annotations && { annotations: tool.annotations },
|
|
892
|
+
execute: tool.execute,
|
|
893
|
+
inputValidator: inputZod,
|
|
894
|
+
...normalizedOutput && { outputValidator: normalizedOutput.zodValidator }
|
|
895
|
+
};
|
|
896
|
+
this.dynamicTools.set(tool.name, validatedTool);
|
|
897
|
+
this.toolRegistrationTimestamps.set(tool.name, now);
|
|
898
|
+
this.updateBridgeTools();
|
|
899
|
+
this.scheduleListChanged("tools");
|
|
900
|
+
const unregisterFn = () => {
|
|
901
|
+
console.log(`[Web Model Context] Unregistering tool: ${tool.name}`);
|
|
902
|
+
if (this.provideContextTools.has(tool.name)) throw new Error(`[Web Model Context] Cannot unregister tool "${tool.name}": This tool was registered via provideContext(). Use provideContext() to update the base tool set.`);
|
|
903
|
+
if (!this.dynamicTools.has(tool.name)) {
|
|
904
|
+
console.warn(`[Web Model Context] Tool "${tool.name}" is not registered, ignoring unregister call`);
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
this.dynamicTools.delete(tool.name);
|
|
908
|
+
this.toolRegistrationTimestamps.delete(tool.name);
|
|
909
|
+
this.toolUnregisterFunctions.delete(tool.name);
|
|
910
|
+
this.updateBridgeTools();
|
|
911
|
+
this.scheduleListChanged("tools");
|
|
912
|
+
};
|
|
913
|
+
this.toolUnregisterFunctions.set(tool.name, unregisterFn);
|
|
914
|
+
return { unregister: unregisterFn };
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Registers a single resource dynamically (Bucket B).
|
|
918
|
+
* Dynamic resources persist across provideContext() calls and can be independently managed.
|
|
919
|
+
*
|
|
920
|
+
* @param {ResourceDescriptor} resource - The resource descriptor to register
|
|
921
|
+
* @returns {{unregister: () => void}} Object with unregister function
|
|
922
|
+
* @throws {Error} If resource URI collides with existing resources
|
|
923
|
+
*/
|
|
924
|
+
registerResource(resource) {
|
|
925
|
+
console.log(`[Web Model Context] Registering resource dynamically: ${resource.uri}`);
|
|
926
|
+
const now = Date.now();
|
|
927
|
+
const lastRegistration = this.resourceRegistrationTimestamps.get(resource.uri);
|
|
928
|
+
if (lastRegistration && now - lastRegistration < RAPID_DUPLICATE_WINDOW_MS) {
|
|
929
|
+
console.warn(`[Web Model Context] Resource "${resource.uri}" registered multiple times within ${RAPID_DUPLICATE_WINDOW_MS}ms. This is likely due to React Strict Mode double-mounting. Ignoring duplicate registration.`);
|
|
930
|
+
const existingUnregister = this.resourceUnregisterFunctions.get(resource.uri);
|
|
931
|
+
if (existingUnregister) return { unregister: existingUnregister };
|
|
932
|
+
}
|
|
933
|
+
if (this.provideContextResources.has(resource.uri)) throw new Error(`[Web Model Context] Resource URI collision: "${resource.uri}" is already registered via provideContext(). Please use a different URI or update your provideContext() call.`);
|
|
934
|
+
if (this.dynamicResources.has(resource.uri)) throw new Error(`[Web Model Context] Resource URI collision: "${resource.uri}" is already registered via registerResource(). Please unregister it first or use a different URI.`);
|
|
935
|
+
const validatedResource = this.validateResource(resource);
|
|
936
|
+
this.dynamicResources.set(resource.uri, validatedResource);
|
|
937
|
+
this.resourceRegistrationTimestamps.set(resource.uri, now);
|
|
938
|
+
this.updateBridgeResources();
|
|
939
|
+
this.scheduleListChanged("resources");
|
|
940
|
+
const unregisterFn = () => {
|
|
941
|
+
console.log(`[Web Model Context] Unregistering resource: ${resource.uri}`);
|
|
942
|
+
if (this.provideContextResources.has(resource.uri)) throw new Error(`[Web Model Context] Cannot unregister resource "${resource.uri}": This resource was registered via provideContext(). Use provideContext() to update the base resource set.`);
|
|
943
|
+
if (!this.dynamicResources.has(resource.uri)) {
|
|
944
|
+
console.warn(`[Web Model Context] Resource "${resource.uri}" is not registered, ignoring unregister call`);
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
this.dynamicResources.delete(resource.uri);
|
|
948
|
+
this.resourceRegistrationTimestamps.delete(resource.uri);
|
|
949
|
+
this.resourceUnregisterFunctions.delete(resource.uri);
|
|
950
|
+
this.updateBridgeResources();
|
|
951
|
+
this.scheduleListChanged("resources");
|
|
952
|
+
};
|
|
953
|
+
this.resourceUnregisterFunctions.set(resource.uri, unregisterFn);
|
|
954
|
+
return { unregister: unregisterFn };
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Unregisters a resource by URI.
|
|
958
|
+
* Can unregister resources from either Bucket A (provideContext) or Bucket B (registerResource).
|
|
959
|
+
*
|
|
960
|
+
* @param {string} uri - URI of the resource to unregister
|
|
961
|
+
*/
|
|
962
|
+
unregisterResource(uri) {
|
|
963
|
+
console.log(`[Web Model Context] Unregistering resource: ${uri}`);
|
|
964
|
+
const inProvideContext = this.provideContextResources.has(uri);
|
|
965
|
+
const inDynamic = this.dynamicResources.has(uri);
|
|
966
|
+
if (!inProvideContext && !inDynamic) {
|
|
967
|
+
console.warn(`[Web Model Context] Resource "${uri}" is not registered, ignoring unregister call`);
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
if (inProvideContext) this.provideContextResources.delete(uri);
|
|
971
|
+
if (inDynamic) {
|
|
972
|
+
this.dynamicResources.delete(uri);
|
|
973
|
+
this.resourceRegistrationTimestamps.delete(uri);
|
|
974
|
+
this.resourceUnregisterFunctions.delete(uri);
|
|
975
|
+
}
|
|
976
|
+
this.updateBridgeResources();
|
|
977
|
+
this.scheduleListChanged("resources");
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* Lists all registered resources in MCP format.
|
|
981
|
+
* Returns static resources from both buckets (not templates).
|
|
982
|
+
*
|
|
983
|
+
* @returns {Resource[]} Array of resource descriptors
|
|
984
|
+
*/
|
|
985
|
+
listResources() {
|
|
986
|
+
return Array.from(this.bridge.resources.values()).filter((r) => !r.isTemplate).map((resource) => ({
|
|
987
|
+
uri: resource.uri,
|
|
988
|
+
name: resource.name,
|
|
989
|
+
description: resource.description,
|
|
990
|
+
mimeType: resource.mimeType
|
|
991
|
+
}));
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Lists all registered resource templates.
|
|
995
|
+
* Returns only resources with URI templates (dynamic resources).
|
|
996
|
+
*
|
|
997
|
+
* @returns {Array<{uriTemplate: string, name: string, description?: string, mimeType?: string}>}
|
|
998
|
+
*/
|
|
999
|
+
listResourceTemplates() {
|
|
1000
|
+
return Array.from(this.bridge.resources.values()).filter((r) => r.isTemplate).map((resource) => ({
|
|
1001
|
+
uriTemplate: resource.uri,
|
|
1002
|
+
name: resource.name,
|
|
1003
|
+
...resource.description !== void 0 && { description: resource.description },
|
|
1004
|
+
...resource.mimeType !== void 0 && { mimeType: resource.mimeType }
|
|
1005
|
+
}));
|
|
1006
|
+
}
|
|
1007
|
+
/**
|
|
1008
|
+
* Registers a single prompt dynamically (Bucket B).
|
|
1009
|
+
* Dynamic prompts persist across provideContext() calls and can be independently managed.
|
|
1010
|
+
*
|
|
1011
|
+
* @param {PromptDescriptor} prompt - The prompt descriptor to register
|
|
1012
|
+
* @returns {{unregister: () => void}} Object with unregister function
|
|
1013
|
+
* @throws {Error} If prompt name collides with existing prompts
|
|
1014
|
+
*/
|
|
1015
|
+
registerPrompt(prompt) {
|
|
1016
|
+
console.log(`[Web Model Context] Registering prompt dynamically: ${prompt.name}`);
|
|
1017
|
+
const now = Date.now();
|
|
1018
|
+
const lastRegistration = this.promptRegistrationTimestamps.get(prompt.name);
|
|
1019
|
+
if (lastRegistration && now - lastRegistration < RAPID_DUPLICATE_WINDOW_MS) {
|
|
1020
|
+
console.warn(`[Web Model Context] Prompt "${prompt.name}" registered multiple times within ${RAPID_DUPLICATE_WINDOW_MS}ms. This is likely due to React Strict Mode double-mounting. Ignoring duplicate registration.`);
|
|
1021
|
+
const existingUnregister = this.promptUnregisterFunctions.get(prompt.name);
|
|
1022
|
+
if (existingUnregister) return { unregister: existingUnregister };
|
|
1023
|
+
}
|
|
1024
|
+
if (this.provideContextPrompts.has(prompt.name)) throw new Error(`[Web Model Context] Prompt name collision: "${prompt.name}" is already registered via provideContext(). Please use a different name or update your provideContext() call.`);
|
|
1025
|
+
if (this.dynamicPrompts.has(prompt.name)) throw new Error(`[Web Model Context] Prompt name collision: "${prompt.name}" is already registered via registerPrompt(). Please unregister it first or use a different name.`);
|
|
1026
|
+
const validatedPrompt = this.validatePrompt(prompt);
|
|
1027
|
+
this.dynamicPrompts.set(prompt.name, validatedPrompt);
|
|
1028
|
+
this.promptRegistrationTimestamps.set(prompt.name, now);
|
|
1029
|
+
this.updateBridgePrompts();
|
|
1030
|
+
this.scheduleListChanged("prompts");
|
|
1031
|
+
const unregisterFn = () => {
|
|
1032
|
+
console.log(`[Web Model Context] Unregistering prompt: ${prompt.name}`);
|
|
1033
|
+
if (this.provideContextPrompts.has(prompt.name)) throw new Error(`[Web Model Context] Cannot unregister prompt "${prompt.name}": This prompt was registered via provideContext(). Use provideContext() to update the base prompt set.`);
|
|
1034
|
+
if (!this.dynamicPrompts.has(prompt.name)) {
|
|
1035
|
+
console.warn(`[Web Model Context] Prompt "${prompt.name}" is not registered, ignoring unregister call`);
|
|
1036
|
+
return;
|
|
1037
|
+
}
|
|
1038
|
+
this.dynamicPrompts.delete(prompt.name);
|
|
1039
|
+
this.promptRegistrationTimestamps.delete(prompt.name);
|
|
1040
|
+
this.promptUnregisterFunctions.delete(prompt.name);
|
|
1041
|
+
this.updateBridgePrompts();
|
|
1042
|
+
this.scheduleListChanged("prompts");
|
|
1043
|
+
};
|
|
1044
|
+
this.promptUnregisterFunctions.set(prompt.name, unregisterFn);
|
|
1045
|
+
return { unregister: unregisterFn };
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Unregisters a prompt by name.
|
|
1049
|
+
* Can unregister prompts from either Bucket A (provideContext) or Bucket B (registerPrompt).
|
|
1050
|
+
*
|
|
1051
|
+
* @param {string} name - Name of the prompt to unregister
|
|
1052
|
+
*/
|
|
1053
|
+
unregisterPrompt(name) {
|
|
1054
|
+
console.log(`[Web Model Context] Unregistering prompt: ${name}`);
|
|
1055
|
+
const inProvideContext = this.provideContextPrompts.has(name);
|
|
1056
|
+
const inDynamic = this.dynamicPrompts.has(name);
|
|
1057
|
+
if (!inProvideContext && !inDynamic) {
|
|
1058
|
+
console.warn(`[Web Model Context] Prompt "${name}" is not registered, ignoring unregister call`);
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
if (inProvideContext) this.provideContextPrompts.delete(name);
|
|
1062
|
+
if (inDynamic) {
|
|
1063
|
+
this.dynamicPrompts.delete(name);
|
|
1064
|
+
this.promptRegistrationTimestamps.delete(name);
|
|
1065
|
+
this.promptUnregisterFunctions.delete(name);
|
|
1066
|
+
}
|
|
1067
|
+
this.updateBridgePrompts();
|
|
1068
|
+
this.scheduleListChanged("prompts");
|
|
1069
|
+
}
|
|
1070
|
+
/**
|
|
1071
|
+
* Lists all registered prompts in MCP format.
|
|
1072
|
+
* Returns prompts from both buckets.
|
|
1073
|
+
*
|
|
1074
|
+
* @returns {Prompt[]} Array of prompt descriptors
|
|
1075
|
+
*/
|
|
1076
|
+
listPrompts() {
|
|
1077
|
+
return Array.from(this.bridge.prompts.values()).map((prompt) => ({
|
|
1078
|
+
name: prompt.name,
|
|
1079
|
+
description: prompt.description,
|
|
1080
|
+
arguments: prompt.argsSchema?.properties ? Object.entries(prompt.argsSchema.properties).map(([name, schema]) => ({
|
|
1081
|
+
name,
|
|
1082
|
+
description: schema.description,
|
|
1083
|
+
required: prompt.argsSchema?.required?.includes(name) ?? false
|
|
1084
|
+
})) : void 0
|
|
1085
|
+
}));
|
|
1086
|
+
}
|
|
1087
|
+
/**
|
|
1088
|
+
* Unregisters a tool by name (Chromium native API).
|
|
1089
|
+
* Can unregister tools from either Bucket A (provideContext) or Bucket B (registerTool).
|
|
1090
|
+
*
|
|
1091
|
+
* @param {string} name - Name of the tool to unregister
|
|
1092
|
+
*/
|
|
1093
|
+
unregisterTool(name) {
|
|
1094
|
+
console.log(`[Web Model Context] Unregistering tool: ${name}`);
|
|
1095
|
+
const inProvideContext = this.provideContextTools.has(name);
|
|
1096
|
+
const inDynamic = this.dynamicTools.has(name);
|
|
1097
|
+
if (!inProvideContext && !inDynamic) {
|
|
1098
|
+
console.warn(`[Web Model Context] Tool "${name}" is not registered, ignoring unregister call`);
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
if (inProvideContext) this.provideContextTools.delete(name);
|
|
1102
|
+
if (inDynamic) {
|
|
1103
|
+
this.dynamicTools.delete(name);
|
|
1104
|
+
this.toolRegistrationTimestamps.delete(name);
|
|
1105
|
+
this.toolUnregisterFunctions.delete(name);
|
|
1106
|
+
}
|
|
1107
|
+
this.updateBridgeTools();
|
|
1108
|
+
this.scheduleListChanged("tools");
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Clears all registered context from both buckets (Chromium native API).
|
|
1112
|
+
* Removes all tools, resources, and prompts registered via provideContext() and register* methods.
|
|
1113
|
+
*/
|
|
1114
|
+
clearContext() {
|
|
1115
|
+
console.log("[Web Model Context] Clearing all context (tools, resources, prompts)");
|
|
1116
|
+
this.provideContextTools.clear();
|
|
1117
|
+
this.dynamicTools.clear();
|
|
1118
|
+
this.toolRegistrationTimestamps.clear();
|
|
1119
|
+
this.toolUnregisterFunctions.clear();
|
|
1120
|
+
this.provideContextResources.clear();
|
|
1121
|
+
this.dynamicResources.clear();
|
|
1122
|
+
this.resourceRegistrationTimestamps.clear();
|
|
1123
|
+
this.resourceUnregisterFunctions.clear();
|
|
1124
|
+
this.provideContextPrompts.clear();
|
|
1125
|
+
this.dynamicPrompts.clear();
|
|
1126
|
+
this.promptRegistrationTimestamps.clear();
|
|
1127
|
+
this.promptUnregisterFunctions.clear();
|
|
1128
|
+
this.updateBridgeTools();
|
|
1129
|
+
this.updateBridgeResources();
|
|
1130
|
+
this.updateBridgePrompts();
|
|
1131
|
+
this.scheduleListChanged("tools");
|
|
1132
|
+
this.scheduleListChanged("resources");
|
|
1133
|
+
this.scheduleListChanged("prompts");
|
|
1134
|
+
}
|
|
1135
|
+
/**
|
|
1136
|
+
* Updates the bridge tools map with merged tools from both buckets.
|
|
1137
|
+
* The final tool list is the union of Bucket A (provideContext) and Bucket B (dynamic).
|
|
1138
|
+
*
|
|
1139
|
+
* @private
|
|
1140
|
+
*/
|
|
1141
|
+
updateBridgeTools() {
|
|
1142
|
+
this.bridge.tools.clear();
|
|
1143
|
+
for (const [name, tool] of this.provideContextTools) this.bridge.tools.set(name, tool);
|
|
1144
|
+
for (const [name, tool] of this.dynamicTools) this.bridge.tools.set(name, tool);
|
|
1145
|
+
console.log(`[Web Model Context] Updated bridge with ${this.provideContextTools.size} base tools + ${this.dynamicTools.size} dynamic tools = ${this.bridge.tools.size} total`);
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Notifies all servers and testing callbacks that the tools list has changed.
|
|
1149
|
+
* Sends MCP notifications to connected servers and invokes registered testing callbacks.
|
|
1150
|
+
*
|
|
1151
|
+
* @private
|
|
1152
|
+
*/
|
|
1153
|
+
notifyToolsListChanged() {
|
|
1154
|
+
if (this.bridge.tabServer.notification) this.bridge.tabServer.notification({
|
|
1155
|
+
method: "notifications/tools/list_changed",
|
|
1156
|
+
params: {}
|
|
1157
|
+
});
|
|
1158
|
+
if (this.bridge.iframeServer?.notification) this.bridge.iframeServer.notification({
|
|
1159
|
+
method: "notifications/tools/list_changed",
|
|
1160
|
+
params: {}
|
|
1161
|
+
});
|
|
1162
|
+
if (this.testingAPI && "notifyToolsChanged" in this.testingAPI) this.testingAPI.notifyToolsChanged();
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Updates the bridge resources map with merged resources from both buckets.
|
|
1166
|
+
*
|
|
1167
|
+
* @private
|
|
1168
|
+
*/
|
|
1169
|
+
updateBridgeResources() {
|
|
1170
|
+
this.bridge.resources.clear();
|
|
1171
|
+
for (const [uri, resource] of this.provideContextResources) this.bridge.resources.set(uri, resource);
|
|
1172
|
+
for (const [uri, resource] of this.dynamicResources) this.bridge.resources.set(uri, resource);
|
|
1173
|
+
console.log(`[Web Model Context] Updated bridge with ${this.provideContextResources.size} base resources + ${this.dynamicResources.size} dynamic resources = ${this.bridge.resources.size} total`);
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Notifies all servers that the resources list has changed.
|
|
1177
|
+
*
|
|
1178
|
+
* @private
|
|
1179
|
+
*/
|
|
1180
|
+
notifyResourcesListChanged() {
|
|
1181
|
+
if (this.bridge.tabServer.notification) this.bridge.tabServer.notification({
|
|
1182
|
+
method: "notifications/resources/list_changed",
|
|
1183
|
+
params: {}
|
|
1184
|
+
});
|
|
1185
|
+
if (this.bridge.iframeServer?.notification) this.bridge.iframeServer.notification({
|
|
1186
|
+
method: "notifications/resources/list_changed",
|
|
1187
|
+
params: {}
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Updates the bridge prompts map with merged prompts from both buckets.
|
|
1192
|
+
*
|
|
1193
|
+
* @private
|
|
1194
|
+
*/
|
|
1195
|
+
updateBridgePrompts() {
|
|
1196
|
+
this.bridge.prompts.clear();
|
|
1197
|
+
for (const [name, prompt] of this.provideContextPrompts) this.bridge.prompts.set(name, prompt);
|
|
1198
|
+
for (const [name, prompt] of this.dynamicPrompts) this.bridge.prompts.set(name, prompt);
|
|
1199
|
+
console.log(`[Web Model Context] Updated bridge with ${this.provideContextPrompts.size} base prompts + ${this.dynamicPrompts.size} dynamic prompts = ${this.bridge.prompts.size} total`);
|
|
1200
|
+
}
|
|
1201
|
+
/**
|
|
1202
|
+
* Notifies all servers that the prompts list has changed.
|
|
1203
|
+
*
|
|
1204
|
+
* @private
|
|
1205
|
+
*/
|
|
1206
|
+
notifyPromptsListChanged() {
|
|
1207
|
+
if (this.bridge.tabServer.notification) this.bridge.tabServer.notification({
|
|
1208
|
+
method: "notifications/prompts/list_changed",
|
|
1209
|
+
params: {}
|
|
1210
|
+
});
|
|
1211
|
+
if (this.bridge.iframeServer?.notification) this.bridge.iframeServer.notification({
|
|
1212
|
+
method: "notifications/prompts/list_changed",
|
|
1213
|
+
params: {}
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Schedules a list changed notification using microtask batching.
|
|
1218
|
+
* Multiple calls for the same list type within the same task are coalesced
|
|
1219
|
+
* into a single notification. This dramatically reduces notification spam
|
|
1220
|
+
* during React mount/unmount cycles.
|
|
1221
|
+
*
|
|
1222
|
+
* @param listType - The type of list that changed ('tools' | 'resources' | 'prompts')
|
|
1223
|
+
* @private
|
|
1224
|
+
*/
|
|
1225
|
+
scheduleListChanged(listType) {
|
|
1226
|
+
if (this.pendingNotifications.has(listType)) return;
|
|
1227
|
+
this.pendingNotifications.add(listType);
|
|
1228
|
+
queueMicrotask(() => {
|
|
1229
|
+
this.pendingNotifications.delete(listType);
|
|
1230
|
+
switch (listType) {
|
|
1231
|
+
case "tools":
|
|
1232
|
+
this.notifyToolsListChanged();
|
|
1233
|
+
break;
|
|
1234
|
+
case "resources":
|
|
1235
|
+
this.notifyResourcesListChanged();
|
|
1236
|
+
break;
|
|
1237
|
+
case "prompts":
|
|
1238
|
+
this.notifyPromptsListChanged();
|
|
1239
|
+
break;
|
|
1240
|
+
default: {
|
|
1241
|
+
const _exhaustive = listType;
|
|
1242
|
+
console.error(`[Web Model Context] Unknown list type: ${_exhaustive}`);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
});
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Reads a resource by URI (internal use only by MCP bridge).
|
|
1249
|
+
* Handles both static resources and URI templates.
|
|
1250
|
+
*
|
|
1251
|
+
* @param {string} uri - The URI of the resource to read
|
|
1252
|
+
* @returns {Promise<{contents: ResourceContents[]}>} The resource contents
|
|
1253
|
+
* @throws {Error} If resource is not found
|
|
1254
|
+
* @internal
|
|
1255
|
+
*/
|
|
1256
|
+
async readResource(uri) {
|
|
1257
|
+
console.log(`[Web Model Context] Reading resource: ${uri}`);
|
|
1258
|
+
const staticResource = this.bridge.resources.get(uri);
|
|
1259
|
+
if (staticResource && !staticResource.isTemplate) try {
|
|
1260
|
+
const parsedUri = new URL(uri);
|
|
1261
|
+
return await staticResource.read(parsedUri);
|
|
1262
|
+
} catch (error) {
|
|
1263
|
+
console.error(`[Web Model Context] Error reading resource ${uri}:`, error);
|
|
1264
|
+
throw error;
|
|
1265
|
+
}
|
|
1266
|
+
for (const resource of this.bridge.resources.values()) {
|
|
1267
|
+
if (!resource.isTemplate) continue;
|
|
1268
|
+
const params = this.matchUriTemplate(resource.uri, uri);
|
|
1269
|
+
if (params) try {
|
|
1270
|
+
const parsedUri = new URL(uri);
|
|
1271
|
+
return await resource.read(parsedUri, params);
|
|
1272
|
+
} catch (error) {
|
|
1273
|
+
console.error(`[Web Model Context] Error reading resource ${uri}:`, error);
|
|
1274
|
+
throw error;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
throw new Error(`Resource not found: ${uri}`);
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* Matches a URI against a URI template and extracts parameters.
|
|
1281
|
+
*
|
|
1282
|
+
* @param {string} template - The URI template (e.g., "file://{path}")
|
|
1283
|
+
* @param {string} uri - The actual URI to match
|
|
1284
|
+
* @returns {Record<string, string> | null} Extracted parameters or null if no match
|
|
1285
|
+
* @private
|
|
1286
|
+
*/
|
|
1287
|
+
matchUriTemplate(template, uri) {
|
|
1288
|
+
const paramNames = [];
|
|
1289
|
+
let regexPattern = template.replace(/[.*+?^${}()|[\]\\]/g, (char) => {
|
|
1290
|
+
if (char === "{" || char === "}") return char;
|
|
1291
|
+
return `\\${char}`;
|
|
1292
|
+
});
|
|
1293
|
+
regexPattern = regexPattern.replace(/\{([^}]+)\}/g, (_, paramName) => {
|
|
1294
|
+
paramNames.push(paramName);
|
|
1295
|
+
return "(.+)";
|
|
1296
|
+
});
|
|
1297
|
+
const regex = /* @__PURE__ */ new RegExp(`^${regexPattern}$`);
|
|
1298
|
+
const match = uri.match(regex);
|
|
1299
|
+
if (!match) return null;
|
|
1300
|
+
const params = {};
|
|
1301
|
+
for (let i = 0; i < paramNames.length; i++) {
|
|
1302
|
+
const paramName = paramNames[i];
|
|
1303
|
+
const paramValue = match[i + 1];
|
|
1304
|
+
if (paramName !== void 0 && paramValue !== void 0) params[paramName] = paramValue;
|
|
1305
|
+
}
|
|
1306
|
+
return params;
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* Gets a prompt with arguments (internal use only by MCP bridge).
|
|
1310
|
+
*
|
|
1311
|
+
* @param {string} name - Name of the prompt
|
|
1312
|
+
* @param {Record<string, unknown>} args - Arguments to pass to the prompt
|
|
1313
|
+
* @returns {Promise<{messages: PromptMessage[]}>} The prompt messages
|
|
1314
|
+
* @throws {Error} If prompt is not found
|
|
1315
|
+
* @internal
|
|
1316
|
+
*/
|
|
1317
|
+
async getPrompt(name, args) {
|
|
1318
|
+
console.log(`[Web Model Context] Getting prompt: ${name}`);
|
|
1319
|
+
const prompt = this.bridge.prompts.get(name);
|
|
1320
|
+
if (!prompt) throw new Error(`Prompt not found: ${name}`);
|
|
1321
|
+
if (prompt.argsValidator && args) {
|
|
1322
|
+
const validation = validateWithZod(args, prompt.argsValidator);
|
|
1323
|
+
if (!validation.success) {
|
|
1324
|
+
console.error(`[Web Model Context] Argument validation failed for prompt ${name}:`, validation.error);
|
|
1325
|
+
throw new Error(`Argument validation error for prompt "${name}":\n${validation.error}`);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
try {
|
|
1329
|
+
return await prompt.get(args ?? {});
|
|
1330
|
+
} catch (error) {
|
|
1331
|
+
console.error(`[Web Model Context] Error getting prompt ${name}:`, error);
|
|
1332
|
+
throw error;
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* Executes a tool with validation and event dispatch.
|
|
1337
|
+
* Follows this sequence:
|
|
1338
|
+
* 1. Validates input arguments against schema
|
|
1339
|
+
* 2. Records tool call in testing API (if available)
|
|
1340
|
+
* 3. Checks for mock response (if testing)
|
|
1341
|
+
* 4. Dispatches 'toolcall' event to listeners
|
|
1342
|
+
* 5. Executes tool function if not prevented
|
|
1343
|
+
* 6. Validates output (permissive mode - warns only)
|
|
1344
|
+
*
|
|
1345
|
+
* @param {string} toolName - Name of the tool to execute
|
|
1346
|
+
* @param {Record<string, unknown>} args - Arguments to pass to the tool
|
|
1347
|
+
* @returns {Promise<ToolResponse>} The tool's response
|
|
1348
|
+
* @throws {Error} If tool is not found
|
|
1349
|
+
* @internal
|
|
1350
|
+
*/
|
|
1351
|
+
async executeTool(toolName, args) {
|
|
1352
|
+
const tool = this.bridge.tools.get(toolName);
|
|
1353
|
+
if (!tool) throw new Error(`Tool not found: ${toolName}`);
|
|
1354
|
+
console.log(`[Web Model Context] Validating input for tool: ${toolName}`);
|
|
1355
|
+
const validation = validateWithZod(args, tool.inputValidator);
|
|
1356
|
+
if (!validation.success) {
|
|
1357
|
+
console.error(`[Web Model Context] Input validation failed for ${toolName}:`, validation.error);
|
|
1358
|
+
return {
|
|
1359
|
+
content: [{
|
|
1360
|
+
type: "text",
|
|
1361
|
+
text: `Input validation error for tool "${toolName}":\n${validation.error}`
|
|
1362
|
+
}],
|
|
1363
|
+
isError: true
|
|
1364
|
+
};
|
|
1365
|
+
}
|
|
1366
|
+
const validatedArgs = validation.data;
|
|
1367
|
+
if (this.testingAPI) this.testingAPI.recordToolCall(toolName, validatedArgs);
|
|
1368
|
+
if (this.testingAPI?.hasMockResponse(toolName)) {
|
|
1369
|
+
const mockResponse = this.testingAPI.getMockResponse(toolName);
|
|
1370
|
+
if (mockResponse) {
|
|
1371
|
+
console.log(`[Web Model Context] Returning mock response for tool: ${toolName}`);
|
|
1372
|
+
return mockResponse;
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
const event = new WebToolCallEvent(toolName, validatedArgs);
|
|
1376
|
+
this.dispatchEvent(event);
|
|
1377
|
+
if (event.defaultPrevented && event.hasResponse()) {
|
|
1378
|
+
const response = event.getResponse();
|
|
1379
|
+
if (response) {
|
|
1380
|
+
console.log(`[Web Model Context] Tool ${toolName} handled by event listener`);
|
|
1381
|
+
return response;
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
console.log(`[Web Model Context] Executing tool: ${toolName}`);
|
|
1385
|
+
try {
|
|
1386
|
+
const response = await tool.execute(validatedArgs);
|
|
1387
|
+
if (tool.outputValidator && response.structuredContent) {
|
|
1388
|
+
const outputValidation = validateWithZod(response.structuredContent, tool.outputValidator);
|
|
1389
|
+
if (!outputValidation.success) console.warn(`[Web Model Context] Output validation failed for ${toolName}:`, outputValidation.error);
|
|
1390
|
+
}
|
|
1391
|
+
if (response.metadata && "willNavigate" in response.metadata) console.info(`[Web Model Context] Tool "${toolName}" will trigger navigation`, response.metadata);
|
|
1392
|
+
return response;
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
console.error(`[Web Model Context] Error executing tool ${toolName}:`, error);
|
|
1395
|
+
return {
|
|
1396
|
+
content: [{
|
|
1397
|
+
type: "text",
|
|
1398
|
+
text: `Error: ${error instanceof Error ? error.message : String(error)}`
|
|
1399
|
+
}],
|
|
1400
|
+
isError: true
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
/**
|
|
1405
|
+
* Lists all registered tools in MCP format.
|
|
1406
|
+
* Returns tools from both buckets with full MCP specification including
|
|
1407
|
+
* annotations and output schemas.
|
|
1408
|
+
*
|
|
1409
|
+
* @returns {Array<{name: string, description: string, inputSchema: InputSchema, outputSchema?: InputSchema, annotations?: ToolAnnotations}>} Array of tool descriptors
|
|
1410
|
+
*/
|
|
1411
|
+
listTools() {
|
|
1412
|
+
return Array.from(this.bridge.tools.values()).map((tool) => ({
|
|
1413
|
+
name: tool.name,
|
|
1414
|
+
description: tool.description,
|
|
1415
|
+
inputSchema: tool.inputSchema,
|
|
1416
|
+
...tool.outputSchema && { outputSchema: tool.outputSchema },
|
|
1417
|
+
...tool.annotations && { annotations: tool.annotations }
|
|
1418
|
+
}));
|
|
1419
|
+
}
|
|
1420
|
+
/**
|
|
1421
|
+
* Request an LLM completion from the connected client.
|
|
1422
|
+
* This sends a sampling request to the connected MCP client.
|
|
1423
|
+
*
|
|
1424
|
+
* @param {SamplingRequestParams} params - Parameters for the sampling request
|
|
1425
|
+
* @returns {Promise<SamplingResult>} The LLM completion result
|
|
1426
|
+
*/
|
|
1427
|
+
async createMessage(params) {
|
|
1428
|
+
console.log("[Web Model Context] Requesting sampling from client");
|
|
1429
|
+
const underlyingServer = this.bridge.tabServer.server;
|
|
1430
|
+
if (!underlyingServer?.createMessage) throw new Error("Sampling is not supported: no connected client with sampling capability");
|
|
1431
|
+
return underlyingServer.createMessage(params);
|
|
1432
|
+
}
|
|
1433
|
+
/**
|
|
1434
|
+
* Request user input from the connected client.
|
|
1435
|
+
* This sends an elicitation request to the connected MCP client.
|
|
1436
|
+
*
|
|
1437
|
+
* @param {ElicitationParams} params - Parameters for the elicitation request
|
|
1438
|
+
* @returns {Promise<ElicitationResult>} The user's response
|
|
1439
|
+
*/
|
|
1440
|
+
async elicitInput(params) {
|
|
1441
|
+
console.log("[Web Model Context] Requesting elicitation from client");
|
|
1442
|
+
const underlyingServer = this.bridge.tabServer.server;
|
|
1443
|
+
if (!underlyingServer?.elicitInput) throw new Error("Elicitation is not supported: no connected client with elicitation capability");
|
|
1444
|
+
return underlyingServer.elicitInput(params);
|
|
1445
|
+
}
|
|
1446
|
+
};
|
|
1447
|
+
/**
|
|
1448
|
+
* Initializes the MCP bridge with dual-server support.
|
|
1449
|
+
* Creates TabServer for same-window communication and optionally IframeChildServer
|
|
1450
|
+
* for parent-child iframe communication.
|
|
1451
|
+
*
|
|
1452
|
+
* @param {WebModelContextInitOptions} [options] - Configuration options
|
|
1453
|
+
* @returns {MCPBridge} The initialized MCP bridge
|
|
1454
|
+
*/
|
|
1455
|
+
function initializeMCPBridge(options) {
|
|
1456
|
+
console.log("[Web Model Context] Initializing MCP bridge");
|
|
1457
|
+
const hostname = window.location.hostname || "localhost";
|
|
1458
|
+
const transportOptions = options?.transport;
|
|
1459
|
+
const setupServerHandlers = (server, bridge$1) => {
|
|
1460
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
1461
|
+
console.log("[MCP Bridge] Handling list_tools request");
|
|
1462
|
+
return { tools: bridge$1.modelContext.listTools() };
|
|
1463
|
+
});
|
|
1464
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
1465
|
+
console.log(`[MCP Bridge] Handling call_tool request: ${request.params.name}`);
|
|
1466
|
+
const toolName = request.params.name;
|
|
1467
|
+
const args = request.params.arguments || {};
|
|
1468
|
+
try {
|
|
1469
|
+
const response = await bridge$1.modelContext.executeTool(toolName, args);
|
|
1470
|
+
return {
|
|
1471
|
+
content: response.content,
|
|
1472
|
+
isError: response.isError,
|
|
1473
|
+
...response.structuredContent && { structuredContent: response.structuredContent }
|
|
1474
|
+
};
|
|
1475
|
+
} catch (error) {
|
|
1476
|
+
console.error(`[MCP Bridge] Error calling tool ${toolName}:`, error);
|
|
1477
|
+
throw error;
|
|
1478
|
+
}
|
|
1479
|
+
});
|
|
1480
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
1481
|
+
console.log("[MCP Bridge] Handling list_resources request");
|
|
1482
|
+
return { resources: bridge$1.modelContext.listResources() };
|
|
1483
|
+
});
|
|
1484
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
1485
|
+
console.log(`[MCP Bridge] Handling read_resource request: ${request.params.uri}`);
|
|
1486
|
+
try {
|
|
1487
|
+
return await bridge$1.modelContext.readResource(request.params.uri);
|
|
1488
|
+
} catch (error) {
|
|
1489
|
+
console.error(`[MCP Bridge] Error reading resource ${request.params.uri}:`, error);
|
|
1490
|
+
throw error;
|
|
1491
|
+
}
|
|
1492
|
+
});
|
|
1493
|
+
server.setRequestHandler(ListPromptsRequestSchema, async () => {
|
|
1494
|
+
console.log("[MCP Bridge] Handling list_prompts request");
|
|
1495
|
+
return { prompts: bridge$1.modelContext.listPrompts() };
|
|
1496
|
+
});
|
|
1497
|
+
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
|
|
1498
|
+
console.log(`[MCP Bridge] Handling get_prompt request: ${request.params.name}`);
|
|
1499
|
+
try {
|
|
1500
|
+
return await bridge$1.modelContext.getPrompt(request.params.name, request.params.arguments);
|
|
1501
|
+
} catch (error) {
|
|
1502
|
+
console.error(`[MCP Bridge] Error getting prompt ${request.params.name}:`, error);
|
|
1503
|
+
throw error;
|
|
1504
|
+
}
|
|
1505
|
+
});
|
|
1506
|
+
};
|
|
1507
|
+
const customTransport = transportOptions?.create?.();
|
|
1508
|
+
if (customTransport) {
|
|
1509
|
+
console.log("[Web Model Context] Using custom transport");
|
|
1510
|
+
const server = new Server({
|
|
1511
|
+
name: hostname,
|
|
1512
|
+
version: "1.0.0"
|
|
1513
|
+
}, { capabilities: {
|
|
1514
|
+
tools: { listChanged: true },
|
|
1515
|
+
resources: { listChanged: true },
|
|
1516
|
+
prompts: { listChanged: true }
|
|
1517
|
+
} });
|
|
1518
|
+
const bridge$1 = {
|
|
1519
|
+
tabServer: server,
|
|
1520
|
+
tools: /* @__PURE__ */ new Map(),
|
|
1521
|
+
resources: /* @__PURE__ */ new Map(),
|
|
1522
|
+
prompts: /* @__PURE__ */ new Map(),
|
|
1523
|
+
modelContext: void 0,
|
|
1524
|
+
isInitialized: true
|
|
1525
|
+
};
|
|
1526
|
+
bridge$1.modelContext = new WebModelContext(bridge$1);
|
|
1527
|
+
setupServerHandlers(server, bridge$1);
|
|
1528
|
+
server.connect(customTransport);
|
|
1529
|
+
console.log("[Web Model Context] MCP server connected with custom transport");
|
|
1530
|
+
return bridge$1;
|
|
1531
|
+
}
|
|
1532
|
+
console.log("[Web Model Context] Using dual-server mode");
|
|
1533
|
+
const tabServerEnabled = transportOptions?.tabServer !== false;
|
|
1534
|
+
const tabServer = new Server({
|
|
1535
|
+
name: `${hostname}-tab`,
|
|
1536
|
+
version: "1.0.0"
|
|
1537
|
+
}, { capabilities: {
|
|
1538
|
+
tools: { listChanged: true },
|
|
1539
|
+
resources: { listChanged: true },
|
|
1540
|
+
prompts: { listChanged: true }
|
|
1541
|
+
} });
|
|
1542
|
+
const bridge = {
|
|
1543
|
+
tabServer,
|
|
1544
|
+
tools: /* @__PURE__ */ new Map(),
|
|
1545
|
+
resources: /* @__PURE__ */ new Map(),
|
|
1546
|
+
prompts: /* @__PURE__ */ new Map(),
|
|
1547
|
+
modelContext: void 0,
|
|
1548
|
+
isInitialized: true
|
|
1549
|
+
};
|
|
1550
|
+
bridge.modelContext = new WebModelContext(bridge);
|
|
1551
|
+
setupServerHandlers(tabServer, bridge);
|
|
1552
|
+
if (tabServerEnabled) {
|
|
1553
|
+
const { allowedOrigins,...restTabServerOptions } = typeof transportOptions?.tabServer === "object" ? transportOptions.tabServer : {};
|
|
1554
|
+
const tabTransport = new TabServerTransport({
|
|
1555
|
+
allowedOrigins: allowedOrigins ?? ["*"],
|
|
1556
|
+
...restTabServerOptions
|
|
1557
|
+
});
|
|
1558
|
+
tabServer.connect(tabTransport);
|
|
1559
|
+
console.log("[Web Model Context] Tab server connected");
|
|
1560
|
+
}
|
|
1561
|
+
const isInIframe = typeof window !== "undefined" && window.parent !== window;
|
|
1562
|
+
const iframeServerConfig = transportOptions?.iframeServer;
|
|
1563
|
+
if (iframeServerConfig !== false && (iframeServerConfig !== void 0 || isInIframe)) {
|
|
1564
|
+
console.log("[Web Model Context] Enabling iframe server");
|
|
1565
|
+
const iframeServer = new Server({
|
|
1566
|
+
name: `${hostname}-iframe`,
|
|
1567
|
+
version: "1.0.0"
|
|
1568
|
+
}, { capabilities: {
|
|
1569
|
+
tools: { listChanged: true },
|
|
1570
|
+
resources: { listChanged: true },
|
|
1571
|
+
prompts: { listChanged: true }
|
|
1572
|
+
} });
|
|
1573
|
+
setupServerHandlers(iframeServer, bridge);
|
|
1574
|
+
const { allowedOrigins,...restIframeServerOptions } = typeof iframeServerConfig === "object" ? iframeServerConfig : {};
|
|
1575
|
+
const iframeTransport = new IframeChildTransport({
|
|
1576
|
+
allowedOrigins: allowedOrigins ?? ["*"],
|
|
1577
|
+
...restIframeServerOptions
|
|
1578
|
+
});
|
|
1579
|
+
iframeServer.connect(iframeTransport);
|
|
1580
|
+
bridge.iframeServer = iframeServer;
|
|
1581
|
+
console.log("[Web Model Context] Iframe server connected");
|
|
1582
|
+
}
|
|
1583
|
+
return bridge;
|
|
1584
|
+
}
|
|
1585
|
+
/**
|
|
1586
|
+
* Initializes the Web Model Context API on window.navigator.
|
|
1587
|
+
* Creates and exposes navigator.modelContext and navigator.modelContextTesting.
|
|
1588
|
+
* Automatically detects and uses native Chromium implementation if available.
|
|
1589
|
+
*
|
|
1590
|
+
* @param {WebModelContextInitOptions} [options] - Configuration options
|
|
1591
|
+
* @throws {Error} If initialization fails
|
|
1592
|
+
* @example
|
|
1593
|
+
* ```typescript
|
|
1594
|
+
* import { initializeWebModelContext } from '@mcp-b/global';
|
|
1595
|
+
*
|
|
1596
|
+
* initializeWebModelContext({
|
|
1597
|
+
* transport: {
|
|
1598
|
+
* tabServer: {
|
|
1599
|
+
* allowedOrigins: ['https://example.com']
|
|
1600
|
+
* }
|
|
1601
|
+
* }
|
|
1602
|
+
* });
|
|
1603
|
+
* ```
|
|
1604
|
+
*/
|
|
1605
|
+
function initializeWebModelContext(options) {
|
|
1606
|
+
if (typeof window === "undefined") {
|
|
1607
|
+
console.warn("[Web Model Context] Not in browser environment, skipping initialization");
|
|
1608
|
+
return;
|
|
1609
|
+
}
|
|
1610
|
+
const effectiveOptions = options ?? window.__webModelContextOptions;
|
|
1611
|
+
const native = detectNativeAPI();
|
|
1612
|
+
if (native.hasNativeContext && native.hasNativeTesting) {
|
|
1613
|
+
const nativeContext = window.navigator.modelContext;
|
|
1614
|
+
const nativeTesting = window.navigator.modelContextTesting;
|
|
1615
|
+
if (!nativeContext || !nativeTesting) {
|
|
1616
|
+
console.error("[Web Model Context] Native API detection mismatch");
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
console.log("✅ [Web Model Context] Native Chromium API detected");
|
|
1620
|
+
console.log(" Using native implementation with MCP bridge synchronization");
|
|
1621
|
+
console.log(" Native API will automatically collect tools from embedded iframes");
|
|
1622
|
+
try {
|
|
1623
|
+
const bridge = initializeMCPBridge(effectiveOptions);
|
|
1624
|
+
bridge.modelContext = new NativeModelContextAdapter(bridge, nativeContext, nativeTesting);
|
|
1625
|
+
bridge.modelContextTesting = nativeTesting;
|
|
1626
|
+
Object.defineProperty(window, "__mcpBridge", {
|
|
1627
|
+
value: bridge,
|
|
1628
|
+
writable: false,
|
|
1629
|
+
configurable: true
|
|
1630
|
+
});
|
|
1631
|
+
console.log("✅ [Web Model Context] MCP bridge synced with native API");
|
|
1632
|
+
console.log(" MCP clients will receive automatic tool updates from native registry");
|
|
1633
|
+
} catch (error) {
|
|
1634
|
+
console.error("[Web Model Context] Failed to initialize native adapter:", error);
|
|
1635
|
+
throw error;
|
|
1636
|
+
}
|
|
1637
|
+
return;
|
|
1638
|
+
}
|
|
1639
|
+
if (native.hasNativeContext && !native.hasNativeTesting) {
|
|
1640
|
+
console.warn("[Web Model Context] Partial native API detected");
|
|
1641
|
+
console.warn(" navigator.modelContext exists but navigator.modelContextTesting is missing");
|
|
1642
|
+
console.warn(" Cannot sync with native API. Please enable experimental features:");
|
|
1643
|
+
console.warn(" - Navigate to chrome://flags");
|
|
1644
|
+
console.warn(" - Enable \"Experimental Web Platform Features\"");
|
|
1645
|
+
console.warn(" - Or launch with: --enable-experimental-web-platform-features");
|
|
1646
|
+
console.warn(" Skipping initialization to avoid conflicts");
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1649
|
+
if (window.navigator.modelContext) {
|
|
1650
|
+
console.warn("[Web Model Context] window.navigator.modelContext already exists, skipping initialization");
|
|
1651
|
+
return;
|
|
1652
|
+
}
|
|
1653
|
+
console.log("[Web Model Context] Native API not detected, installing polyfill");
|
|
1654
|
+
try {
|
|
1655
|
+
const bridge = initializeMCPBridge(effectiveOptions);
|
|
1656
|
+
Object.defineProperty(window.navigator, "modelContext", {
|
|
1657
|
+
value: bridge.modelContext,
|
|
1658
|
+
writable: false,
|
|
1659
|
+
configurable: false
|
|
1660
|
+
});
|
|
1661
|
+
Object.defineProperty(window, "__mcpBridge", {
|
|
1662
|
+
value: bridge,
|
|
1663
|
+
writable: false,
|
|
1664
|
+
configurable: true
|
|
1665
|
+
});
|
|
1666
|
+
console.log("✅ [Web Model Context] window.navigator.modelContext initialized successfully");
|
|
1667
|
+
console.log("[Model Context Testing] Installing polyfill");
|
|
1668
|
+
console.log(" 💡 To use the native implementation in Chromium:");
|
|
1669
|
+
console.log(" - Navigate to chrome://flags");
|
|
1670
|
+
console.log(" - Enable \"Experimental Web Platform Features\"");
|
|
1671
|
+
console.log(" - Or launch with: --enable-experimental-web-platform-features");
|
|
1672
|
+
const testingAPI = new WebModelContextTesting(bridge);
|
|
1673
|
+
bridge.modelContextTesting = testingAPI;
|
|
1674
|
+
bridge.modelContext.setTestingAPI(testingAPI);
|
|
1675
|
+
Object.defineProperty(window.navigator, "modelContextTesting", {
|
|
1676
|
+
value: testingAPI,
|
|
1677
|
+
writable: false,
|
|
1678
|
+
configurable: true
|
|
1679
|
+
});
|
|
1680
|
+
console.log("✅ [Model Context Testing] Polyfill installed at window.navigator.modelContextTesting");
|
|
1681
|
+
} catch (error) {
|
|
1682
|
+
console.error("[Web Model Context] Failed to initialize:", error);
|
|
1683
|
+
throw error;
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Cleans up the Web Model Context API.
|
|
1688
|
+
* Closes all MCP servers and removes API from window.navigator.
|
|
1689
|
+
* Useful for testing and hot module replacement.
|
|
1690
|
+
*
|
|
1691
|
+
* @example
|
|
1692
|
+
* ```typescript
|
|
1693
|
+
* import { cleanupWebModelContext } from '@mcp-b/global';
|
|
1694
|
+
*
|
|
1695
|
+
* cleanupWebModelContext();
|
|
1696
|
+
* ```
|
|
1697
|
+
*/
|
|
1698
|
+
function cleanupWebModelContext() {
|
|
1699
|
+
if (typeof window === "undefined") return;
|
|
1700
|
+
if (window.__mcpBridge) try {
|
|
1701
|
+
window.__mcpBridge.tabServer.close();
|
|
1702
|
+
if (window.__mcpBridge.iframeServer) window.__mcpBridge.iframeServer.close();
|
|
1703
|
+
} catch (error) {
|
|
1704
|
+
console.warn("[Web Model Context] Error closing MCP servers:", error);
|
|
1705
|
+
}
|
|
1706
|
+
delete window.navigator.modelContext;
|
|
1707
|
+
delete window.navigator.modelContextTesting;
|
|
1708
|
+
delete window.__mcpBridge;
|
|
1709
|
+
console.log("[Web Model Context] Cleaned up");
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
//#endregion
|
|
1713
|
+
//#region src/index.ts
|
|
1714
|
+
function mergeTransportOptions(base, override) {
|
|
1715
|
+
if (!base) return override;
|
|
1716
|
+
if (!override) return base;
|
|
1717
|
+
return {
|
|
1718
|
+
...base,
|
|
1719
|
+
...override,
|
|
1720
|
+
tabServer: {
|
|
1721
|
+
...base.tabServer ?? {},
|
|
1722
|
+
...override.tabServer ?? {}
|
|
1723
|
+
}
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1726
|
+
function mergeInitOptions(base, override) {
|
|
1727
|
+
if (!base) return override;
|
|
1728
|
+
if (!override) return base;
|
|
1729
|
+
return {
|
|
1730
|
+
...base,
|
|
1731
|
+
...override,
|
|
1732
|
+
transport: mergeTransportOptions(base.transport ?? {}, override.transport ?? {})
|
|
1733
|
+
};
|
|
1734
|
+
}
|
|
1735
|
+
function parseScriptTagOptions(script) {
|
|
1736
|
+
if (!script || !script.dataset) return;
|
|
1737
|
+
const { dataset } = script;
|
|
1738
|
+
if (dataset.webmcpOptions) try {
|
|
1739
|
+
return JSON.parse(dataset.webmcpOptions);
|
|
1740
|
+
} catch (error) {
|
|
1741
|
+
console.error("[Web Model Context] Invalid JSON in data-webmcp-options:", error);
|
|
1742
|
+
return;
|
|
1743
|
+
}
|
|
1744
|
+
const options = {};
|
|
1745
|
+
let hasOptions = false;
|
|
1746
|
+
if (dataset.webmcpAutoInitialize !== void 0) {
|
|
1747
|
+
options.autoInitialize = dataset.webmcpAutoInitialize !== "false";
|
|
1748
|
+
hasOptions = true;
|
|
1749
|
+
}
|
|
1750
|
+
const tabServerOptions = {};
|
|
1751
|
+
let hasTabServerOptions = false;
|
|
1752
|
+
if (dataset.webmcpAllowedOrigins) {
|
|
1753
|
+
const origins = dataset.webmcpAllowedOrigins.split(",").map((origin) => origin.trim()).filter((origin) => origin.length > 0);
|
|
1754
|
+
if (origins.length > 0) {
|
|
1755
|
+
tabServerOptions.allowedOrigins = origins;
|
|
1756
|
+
hasOptions = true;
|
|
1757
|
+
hasTabServerOptions = true;
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
if (dataset.webmcpChannelId) {
|
|
1761
|
+
tabServerOptions.channelId = dataset.webmcpChannelId;
|
|
1762
|
+
hasOptions = true;
|
|
1763
|
+
hasTabServerOptions = true;
|
|
1764
|
+
}
|
|
1765
|
+
if (hasTabServerOptions) options.transport = {
|
|
1766
|
+
...options.transport ?? {},
|
|
1767
|
+
tabServer: {
|
|
1768
|
+
...options.transport?.tabServer ?? {},
|
|
1769
|
+
...tabServerOptions
|
|
1770
|
+
}
|
|
1771
|
+
};
|
|
1772
|
+
return hasOptions ? options : void 0;
|
|
1773
|
+
}
|
|
1774
|
+
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
|
1775
|
+
const globalOptions = window.__webModelContextOptions;
|
|
1776
|
+
const scriptElement = document.currentScript;
|
|
1777
|
+
const scriptOptions = parseScriptTagOptions(scriptElement);
|
|
1778
|
+
const mergedOptions = mergeInitOptions(globalOptions, scriptOptions) ?? globalOptions ?? scriptOptions;
|
|
1779
|
+
if (mergedOptions) window.__webModelContextOptions = mergedOptions;
|
|
1780
|
+
const shouldAutoInitialize = mergedOptions?.autoInitialize !== false;
|
|
1781
|
+
try {
|
|
1782
|
+
if (shouldAutoInitialize) initializeWebModelContext(mergedOptions);
|
|
1783
|
+
} catch (error) {
|
|
1784
|
+
console.error("[Web Model Context] Auto-initialization failed:", error);
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
//#endregion
|
|
1789
|
+
export { cleanupWebModelContext, initializeWebModelContext, zodToJsonSchema };
|
|
1790
|
+
//# sourceMappingURL=index.js.map
|