Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
5f635a4c0This file is pinned to the selected release. Download the original to open it in your design tool.
import { WebMcpToolRegistry } from './WebMcpToolRegistry.mjs'
import { WebMcpTelemetry } from './WebMcpTelemetry.mjs'
/**
* Registers loaded-session WebMCP tools with the native browser API.
*/
export class WebMcpAdapter {
/** @type {WebMcpTelemetry} */
#telemetry
/** @type {object | null} */
#modelContext
/** @type {boolean} */
#resolveModelContextOnInitialize
/** @type {WebMcpToolRegistry} */
#registry
/** @type {object | undefined} Optional explicit feedback tool provider. */
#feedback
/**
* @param {{ getSnapshot: () => object, modelContext?: object | null, registry?: WebMcpToolRegistry, analytics?: { track?: (eventName: string, properties?: object) => void } | null, feedback?: import('./WebMcpFeedback.mjs').WebMcpFeedback, appVersion?: string, now?: () => number, pageSessionId?: string }} dependencies Dependencies.
*/
constructor(dependencies = {}) {
this.#telemetry = new WebMcpTelemetry(dependencies)
this.#feedback = dependencies?.feedback
this.#resolveModelContextOnInitialize =
dependencies?.modelContext === undefined
this.#modelContext =
dependencies?.modelContext === undefined
? null
: dependencies.modelContext
this.#registry =
dependencies?.registry ||
new WebMcpToolRegistry({
getSnapshot: dependencies?.getSnapshot,
appVersion: dependencies?.appVersion
})
}
/**
* Registers tools when WebMCP runtime support is available.
* @param {{ available?: boolean, imported?: boolean }} [runtime] Loader result.
* @returns {Promise<{ available: boolean, registered: number, failed: number }>}
*/
async initialize(runtime = {}) {
this.#telemetry.setRuntime(runtime)
this.#modelContext = this.#resolveModelContext()
if (
!this.#modelContext ||
typeof this.#modelContext.registerTool !== 'function'
) {
this.#track('webmcp_unavailable', {
resultStatus: 'unavailable',
errorBucket: 'runtime_unavailable'
})
return { available: false, registered: 0, failed: 0 }
}
let registered = 0
let failed = 0
const apiForm = this.#apiForm()
const tools = this.#registry.getTools()
// The oldest positional API cannot carry consequential-action annotations.
if (this.#feedback && apiForm !== 'legacy_positional') {
tools.push(
this.#feedback.createTool(tools.map((tool) => tool.name))
)
}
for (const tool of tools) {
try {
await this.#registerTool(tool, apiForm)
registered += 1
} catch (_error) {
failed += 1
this.#track('webmcp_tool_registration_failed', {
methodName: tool.name,
apiForm,
resultStatus: 'error',
errorBucket: 'registration_failed'
})
}
}
this.#track('webmcp_available', {
apiForm,
resultStatus: failed === 0 ? 'success' : 'error',
registeredCount: registered,
failedCount: failed
})
return { available: true, registered, failed }
}
/**
* Resolves the browser model context at startup time unless one was
* injected for tests or alternate runtimes.
* @returns {object | null}
*/
#resolveModelContext() {
if (this.#resolveModelContextOnInitialize) {
return WebMcpAdapter.#getNativeModelContext()
}
return this.#modelContext
}
/**
* Registers one tool using the available browser signature.
* @param {{ name: string, description: string, inputSchema: object, annotations?: object, handler: (args: object, executionOptions?: object) => unknown }} tool Tool definition.
* @param {string} apiForm Browser API form.
* @returns {Promise<void>}
*/
async #registerTool(tool, apiForm) {
const registerTool = this.#modelContext.registerTool
if (registerTool.length <= 2) {
await registerTool.call(
this.#modelContext,
this.#toNativeTool(tool, apiForm)
)
return
}
const handler = this.#toLegacyHandler(tool, apiForm)
if (this.#modelContext.registerTool.length >= 4) {
await registerTool.call(
this.#modelContext,
tool.name,
tool.description,
tool.inputSchema,
handler
)
return
}
await registerTool.call(
this.#modelContext,
tool.name,
{
description: tool.description,
inputSchema: tool.inputSchema,
annotations: tool.annotations
},
handler
)
}
/**
* Returns a stable label for the native WebMCP registration signature.
* @returns {string}
*/
#apiForm() {
if (this.#modelContext.registerTool.length <= 2) {
return 'object'
}
if (this.#modelContext.registerTool.length >= 4) {
return 'legacy_positional'
}
return 'legacy_descriptor'
}
/**
* Returns the current document-scoped browser WebMCP model context.
* @returns {object | null}
*/
static #getNativeModelContext() {
return globalThis.document?.modelContext || null
}
/**
* Converts one registry tool to the current object-form WebMCP API.
* @param {{ name: string, description: string, inputSchema: object, annotations?: object, handler: (args: object) => unknown }} tool Tool definition.
* @param {string} apiForm Browser API form.
* @returns {{ name: string, description: string, inputSchema: object, annotations?: object, execute: (args?: object, callbackOptions?: object) => Promise<unknown> }}
*/
#toNativeTool(tool, apiForm) {
return {
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
annotations: tool.annotations,
execute: async (args = {}, callbackOptions = {}) =>
this.#trackToolCall(
tool,
apiForm,
args || {},
WebMcpAdapter.#executionOptions(callbackOptions)
)
}
}
/**
* Builds a handler for older positional browser APIs.
* @param {{ handler: (args: object, executionOptions?: object) => object }} tool Tool definition.
* @param {string} apiForm Browser API form.
* @returns {(args?: object, callbackOptions?: object) => Promise<{ content: { type: 'text', text: string }[] }>}
*/
#toLegacyHandler(tool, apiForm) {
return async (args = {}, callbackOptions = {}) => {
return WebMcpAdapter.#formatResult(
await this.#trackToolCall(
tool,
apiForm,
args || {},
WebMcpAdapter.#executionOptions(callbackOptions)
)
)
}
}
/**
* Executes one tool while emitting privacy-safe method-call analytics.
* @param {{ name: string, handler: (args: object, executionOptions?: object) => unknown }} tool Tool definition.
* @param {string} apiForm Browser API form.
* @param {object} args Tool arguments.
* @param {{ signal?: AbortSignal }} [executionOptions] Execution options.
* @returns {Promise<unknown>}
*/
async #trackToolCall(tool, apiForm, args, executionOptions = {}) {
return this.#telemetry.execute(tool, apiForm, args, executionOptions)
}
/**
* Keeps browser execution context separate from JSON tool arguments.
* @param {object | null | undefined} callbackOptions Browser callback options.
* @returns {{ signal?: AbortSignal }}
*/
static #executionOptions(callbackOptions) {
if (
!callbackOptions ||
typeof callbackOptions !== 'object' ||
callbackOptions.signal === undefined
) {
return {}
}
return { signal: callbackOptions.signal }
}
/**
* Emits one analytics event when a compatible tracker is configured.
* @param {string} eventName Event name.
* @param {object} properties Event properties.
* @returns {void}
*/
#track(eventName, properties) {
this.#telemetry.track(eventName, properties)
}
/**
* Formats one result as MCP text content.
* @param {unknown} result Tool result.
* @returns {{ content: { type: 'text', text: string }[] }}
*/
static #formatResult(result) {
return {
content: [
{
type: 'text',
text: JSON.stringify(result, null, 2)
}
]
}
}
}