@mcp-b/webmcp-polyfill 4.0.0 → 5.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +123 -193
- package/dist/index.d.ts +7 -23
- package/dist/index.iife.js +1 -2
- package/dist/index.js +940 -373
- package/dist/index.js.map +1 -1
- package/dist/schema.d.ts +22 -12
- package/dist/schema.js +208 -101
- package/dist/schema.js.map +1 -1
- package/package.json +10 -13
- package/dist/index.d.ts.map +0 -1
- package/dist/schema.d.ts.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import type {\n InputSchema,\n ModelContext,\n ModelContextClient,\n ModelContextRegisterToolOptions,\n ModelContextTesting,\n ModelContextTestingExecuteToolOptions,\n ModelContextTestingToolInfo,\n ModelContextToolInfo,\n ModelContextToolReference,\n ToolDescriptor,\n ToolResponse,\n} from '@mcp-b/webmcp-types';\nimport {\n isPlainObject,\n normalizeInputSchema,\n toJsonValue,\n validateValueWithSchema,\n} from './schema.js';\nimport type { StandardInputValidatorSchema } from './schema.js';\nexport {\n isPlainObject,\n normalizeInputSchema,\n toJsonValue,\n validateValueWithSchema,\n} from './schema.js';\nexport type {\n StandardInputJsonSchema,\n StandardInputValidatorSchema,\n StandardJSONSchemaV1,\n ToolInputSchema,\n ToolOutputSchema,\n} from './schema.js';\n\nconst FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE = 'Failed to parse input arguments';\nconst TOOL_INVOCATION_FAILED_MESSAGE =\n 'Tool was executed but the invocation failed. For example, the script function threw an error';\nconst TOOL_CANCELLED_MESSAGE = 'Tool was cancelled';\n/** WebMCP §4.2 tool name: ASCII alnum, underscore, hyphen, period; 1–128 code points. */\nconst VALID_TOOL_NAME_RE = /^[A-Za-z0-9_\\-.]{1,128}$/u;\n\nconst POLYFILL_MARKER_PROPERTY = '__isWebMCPPolyfill' as const;\nconst STANDARD_VALIDATOR_SYMBOL = Symbol('standardValidator');\n\nfunction createAbortError(): Error {\n return new DOMException('signal is aborted without reason', 'AbortError');\n}\n\ntype StandardValidationResult = Awaited<\n ReturnType<StandardInputValidatorSchema['~standard']['validate']>\n>;\ntype StandardValidationIssue = NonNullable<StandardValidationResult['issues']>[number];\n\ninterface PolyfillModelContext extends ModelContext {\n [POLYFILL_MARKER_PROPERTY]: true;\n}\n\ninterface PolyfillToolDescriptor extends ToolDescriptor<Record<string, unknown>, unknown, string> {\n inputSchema: InputSchema;\n [STANDARD_VALIDATOR_SYMBOL]: StandardInputValidatorSchema;\n}\n\ninterface InstallState {\n installed: boolean;\n previousNavigatorModelContextDescriptor: PropertyDescriptor | undefined;\n previousNavigatorModelContextTestingDescriptor: PropertyDescriptor | undefined;\n previousDocumentModelContextDescriptor: PropertyDescriptor | undefined;\n installedNavigatorModelContext: boolean;\n installedNavigatorModelContextTesting: boolean;\n installedDocumentModelContext: boolean;\n}\n\nconst installState: InstallState = {\n installed: false,\n previousNavigatorModelContextDescriptor: undefined,\n previousNavigatorModelContextTestingDescriptor: undefined,\n previousDocumentModelContextDescriptor: undefined,\n installedNavigatorModelContext: false,\n installedNavigatorModelContextTesting: false,\n installedDocumentModelContext: false,\n};\n\nexport interface WebMCPPolyfillInitOptions {\n /**\n * Controls whether the polyfill auto-initializes when loaded.\n * Set to false to prevent auto-initialization; then call initializeWebMCPPolyfill() manually.\n * @default true\n */\n autoInitialize?: boolean;\n\n /**\n * Controls installation of navigator.modelContextTesting when this polyfill provides modelContext.\n * - true or 'if-missing' (default): install only when modelContextTesting is missing.\n * - 'always': install even when modelContextTesting already exists.\n * - false: do not install.\n * @default 'if-missing'\n */\n installTestingShim?: boolean | 'always' | 'if-missing';\n\n /**\n * Deprecated no-op kept for backward compatibility with previous wrappers.\n */\n disableIframeTransportByDefault?: boolean;\n}\n\nclass StrictWebMCPContext extends EventTarget {\n private tools = new Map<string, PolyfillToolDescriptor>();\n private testingShim: PolyfillTestingShim | null = null;\n private _ontoolchange: ((this: ModelContext, ev: Event) => unknown) | null = null;\n private unregisterToolDeprecationWarned = false;\n private toolsChangedQueued = false;\n\n get ontoolchange(): ((this: ModelContext, ev: Event) => unknown) | null {\n return this._ontoolchange;\n }\n\n set ontoolchange(handler: ((this: ModelContext, ev: Event) => unknown) | null) {\n this._ontoolchange = handler;\n }\n\n registerTool(tool: ToolDescriptor, options?: ModelContextRegisterToolOptions): Promise<void> {\n const signal = options?.signal;\n\n if (signal?.aborted) {\n return Promise.reject(createAbortError());\n }\n\n const normalized = normalizeToolDescriptor(tool, this.tools);\n this.tools.set(normalized.name, normalized);\n this.notifyToolsChanged();\n\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n if (this.tools.delete(normalized.name)) {\n this.notifyToolsChanged();\n }\n },\n { once: true }\n );\n }\n\n return Promise.resolve();\n }\n\n unregisterTool(nameOrTool: string | ModelContextToolReference): void {\n this.warnUnregisterToolDeprecationOnce();\n\n const name = getToolNameForUnregister(nameOrTool);\n const removed = this.tools.delete(name);\n if (removed) {\n this.notifyToolsChanged();\n }\n }\n\n getTools(): Promise<ModelContextToolInfo[]> {\n return Promise.resolve(this.getRegisteredToolInfos());\n }\n\n executeTool(\n tool: ModelContextToolInfo,\n inputArgsJson: string,\n options?: ModelContextTestingExecuteToolOptions\n ): Promise<string | null> {\n return this.executeToolByName(tool.name, inputArgsJson, options, false);\n }\n\n getTestingShim(): PolyfillTestingShim {\n if (!this.testingShim) {\n this.testingShim = new PolyfillTestingShim(this);\n }\n return this.testingShim;\n }\n\n /** @internal Used by PolyfillTestingShim */\n getToolInfos(): ModelContextTestingToolInfo[] {\n return [...this.tools.values()].map((tool) => {\n let inputSchema: string;\n try {\n inputSchema = JSON.stringify(tool.inputSchema ?? { type: 'object' });\n } catch {\n inputSchema = '{\"type\":\"object\"}';\n }\n return { name: tool.name, description: tool.description, inputSchema };\n });\n }\n\n /** @internal Used by getTools() */\n getRegisteredToolInfos(): ModelContextToolInfo[] {\n return this.getToolInfos().map((toolInfo) => {\n const tool = this.tools.get(toolInfo.name);\n return {\n ...toolInfo,\n title: tool?.title ?? '',\n origin: globalThis.location?.origin ?? '',\n window: globalThis.window,\n };\n });\n }\n\n /** @internal Used by PolyfillTestingShim */\n async executeToolForTesting(\n toolName: string,\n inputArgsJson: string,\n options?: ModelContextTestingExecuteToolOptions\n ): Promise<string | null> {\n return this.executeToolByName(toolName, inputArgsJson, options, true);\n }\n\n private async executeToolByName(\n toolName: string,\n inputArgsJson: string,\n options: ModelContextTestingExecuteToolOptions | undefined,\n normalizeResult: boolean\n ): Promise<string | null> {\n if (options?.signal?.aborted) {\n throw createUnknownError(TOOL_CANCELLED_MESSAGE);\n }\n\n const tool = this.tools.get(toolName);\n if (!tool) {\n throw createUnknownError(`Tool not found: ${toolName}`);\n }\n\n const args = parseInputArgsJson(inputArgsJson);\n const validationError = await validateArgsForTool(args, tool);\n if (validationError) {\n throw createUnknownError(validationError);\n }\n\n let contextActive = true;\n const client: ModelContextClient = {\n requestUserInteraction: async (callback: () => Promise<unknown>): Promise<unknown> => {\n if (!contextActive) {\n throw new Error(\n `ModelContextClient for tool \"${toolName}\" is no longer active after execute() resolved`\n );\n }\n\n if (typeof callback !== 'function') {\n throw new TypeError('requestUserInteraction(callback) requires a function callback');\n }\n\n return callback();\n },\n };\n\n try {\n const execution = tool.execute(args, client);\n const rawResult = await withAbortSignal(Promise.resolve(execution), options?.signal);\n const normalizedResult = normalizeToolResponse(rawResult);\n const outputValidationError = validateOutputForTool(normalizedResult, tool);\n if (outputValidationError) {\n throw new Error(outputValidationError);\n }\n if (normalizeResult) {\n return toSerializedTestingResult(normalizedResult);\n }\n const serialized = JSON.stringify(rawResult);\n return serialized === undefined ? null : serialized;\n } catch (error) {\n const detail =\n error instanceof Error\n ? `${TOOL_INVOCATION_FAILED_MESSAGE}: ${error.message}`\n : TOOL_INVOCATION_FAILED_MESSAGE;\n throw createUnknownError(detail);\n } finally {\n contextActive = false;\n }\n }\n\n private notifyToolsChanged(): void {\n if (this.toolsChangedQueued) {\n return;\n }\n this.toolsChangedQueued = true;\n\n queueMicrotask(() => {\n this.toolsChangedQueued = false;\n const event = new Event('toolchange');\n try {\n this._ontoolchange?.call(this as unknown as ModelContext, event);\n } catch (error) {\n console.warn('[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:', error);\n }\n this.dispatchEvent(event);\n this.testingShim?.dispatchToolChange();\n });\n }\n\n private warnUnregisterToolDeprecationOnce(): void {\n if (this.unregisterToolDeprecationWarned) {\n return;\n }\n\n this.unregisterToolDeprecationWarned = true;\n console.warn(\n '[WebMCPPolyfill] navigator.modelContext.unregisterTool() is deprecated. The April 23, 2026 WebMCP draft removed it in favor of registerTool(tool, { signal }) — pass an AbortSignal and abort it to unregister.'\n );\n }\n}\n\n/**\n * EventTarget-based testing shim matching the native Chromium ModelContextTesting surface.\n *\n * Fires `toolchange` events and supports the `ontoolchange` handler property,\n * matching the native Chromium 148 API. The deprecated `registerToolsChangedCallback`\n * is kept as a compat layer that wraps `addEventListener`.\n */\nclass PolyfillTestingShim extends EventTarget implements ModelContextTesting {\n private context: StrictWebMCPContext;\n private _ontoolchange: ((this: ModelContextTesting, ev: Event) => unknown) | null = null;\n\n constructor(context: StrictWebMCPContext) {\n super();\n this.context = context;\n }\n\n listTools(): ModelContextTestingToolInfo[] {\n return this.context.getToolInfos();\n }\n\n executeTool(\n toolName: string,\n inputArgsJson: string,\n options?: ModelContextTestingExecuteToolOptions\n ): Promise<string | null> {\n return this.context.executeToolForTesting(toolName, inputArgsJson, options);\n }\n\n getCrossDocumentScriptToolResult(): Promise<string> {\n return Promise.resolve('[]');\n }\n\n get ontoolchange(): ((this: ModelContextTesting, ev: Event) => unknown) | null {\n return this._ontoolchange;\n }\n\n set ontoolchange(handler: ((this: ModelContextTesting, ev: Event) => unknown) | null) {\n this._ontoolchange = handler;\n }\n\n /**\n * @deprecated Use `addEventListener('toolchange', callback)` instead.\n * Kept for backward compatibility with older polyfill consumers.\n */\n registerToolsChangedCallback(callback: () => void): void {\n if (typeof callback !== 'function') {\n throw new TypeError(\n \"Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.\"\n );\n }\n this.addEventListener('toolchange', callback);\n }\n\n /** @internal Called by StrictWebMCPContext when tools change. */\n dispatchToolChange(): void {\n const event = new Event('toolchange');\n try {\n this._ontoolchange?.call(this, event);\n } catch (error) {\n console.warn('[WebMCPPolyfill] ontoolchange handler threw:', error);\n }\n this.dispatchEvent(event);\n // Deprecated compat: fire old event name so existing listeners keep working\n this.dispatchEvent(new Event('toolschanged'));\n }\n}\n\nfunction createUnknownError(message: string): Error {\n try {\n return new DOMException(message, 'UnknownError');\n } catch {\n const error = new Error(message);\n error.name = 'UnknownError';\n return error;\n }\n}\n\nfunction createInvalidStateError(message: string): DOMException | Error {\n try {\n return new DOMException(message, 'InvalidStateError');\n } catch {\n const error = new Error(message);\n error.name = 'InvalidStateError';\n return error;\n }\n}\n\nfunction parseInputArgsJson(inputArgsJson: string): Record<string, unknown> {\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(inputArgsJson);\n } catch {\n throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);\n }\n\n return parsed as Record<string, unknown>;\n}\n\nfunction getToolNameForUnregister(nameOrTool: string | ModelContextToolReference): string {\n if (typeof nameOrTool === 'string') {\n return nameOrTool;\n }\n\n if (isPlainObject(nameOrTool) && typeof nameOrTool.name === 'string') {\n return nameOrTool.name;\n }\n\n throw new TypeError(\n \"Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.\"\n );\n}\n\nfunction normalizeToolDescriptor(\n tool: ToolDescriptor,\n existing: Map<string, PolyfillToolDescriptor>\n): PolyfillToolDescriptor {\n if (!tool || typeof tool !== 'object') {\n throw new TypeError('registerTool(tool) requires a tool object');\n }\n\n if (typeof tool.name !== 'string' || tool.name.length === 0) {\n throw createInvalidStateError('Tool \"name\" must be a non-empty string');\n }\n\n if (!VALID_TOOL_NAME_RE.test(tool.name) || Array.from(tool.name).length > 128) {\n throw createInvalidStateError(\n 'Tool \"name\" must be 1–128 characters and contain only ASCII alphanumeric, underscore, hyphen, or period'\n );\n }\n\n if (typeof tool.description !== 'string' || tool.description.length === 0) {\n throw createInvalidStateError('Tool \"description\" must be a non-empty string');\n }\n\n if (typeof tool.execute !== 'function') {\n throw new TypeError('Tool \"execute\" must be a function');\n }\n\n if (existing.has(tool.name)) {\n throw new Error(`Tool already registered: ${tool.name}`);\n }\n\n const normalizedInputSchema = normalizeInputSchema(tool.inputSchema);\n\n const annotations = tool.annotations;\n const normalizedAnnotations = annotations\n ? {\n ...annotations,\n ...(annotations.readOnlyHint === 'true'\n ? { readOnlyHint: true }\n : annotations.readOnlyHint === 'false'\n ? { readOnlyHint: false }\n : {}),\n ...(annotations.destructiveHint === 'true'\n ? { destructiveHint: true }\n : annotations.destructiveHint === 'false'\n ? { destructiveHint: false }\n : {}),\n ...(annotations.idempotentHint === 'true'\n ? { idempotentHint: true }\n : annotations.idempotentHint === 'false'\n ? { idempotentHint: false }\n : {}),\n ...(annotations.openWorldHint === 'true'\n ? { openWorldHint: true }\n : annotations.openWorldHint === 'false'\n ? { openWorldHint: false }\n : {}),\n }\n : undefined;\n\n return {\n ...tool,\n ...(normalizedAnnotations ? { annotations: normalizedAnnotations } : {}),\n inputSchema: normalizedInputSchema.inputSchema,\n [STANDARD_VALIDATOR_SYMBOL]: normalizedInputSchema.standardValidator,\n };\n}\n\nfunction formatStandardIssuePath(path: StandardValidationIssue['path']) {\n if (!path || path.length === 0) {\n return null;\n }\n\n const segments = path\n .map((segment) => {\n if (isPlainObject(segment) && 'key' in segment) {\n return segment.key;\n }\n return segment;\n })\n .map((segment) => String(segment))\n .filter((segment) => segment.length > 0);\n\n if (segments.length === 0) {\n return null;\n }\n\n return segments.join('.');\n}\n\nasync function validateArgsWithStandardSchema(\n args: Record<string, unknown>,\n schema: StandardInputValidatorSchema\n): Promise<string | null> {\n let result: StandardValidationResult;\n\n try {\n result = await Promise.resolve(schema['~standard'].validate(args));\n } catch (error) {\n const detail = error instanceof Error ? `: ${error.message}` : '';\n console.error('[WebMCPPolyfill] Standard Schema validation threw unexpectedly:', error);\n return `Input validation error: schema validation failed${detail}`;\n }\n\n if (!result.issues || result.issues.length === 0) {\n return null;\n }\n\n const firstIssue = result.issues[0];\n if (!firstIssue) {\n return 'Input validation error';\n }\n\n const path = formatStandardIssuePath(firstIssue?.path);\n if (path) {\n return `Input validation error: ${firstIssue.message} at ${path}`;\n }\n\n return `Input validation error: ${firstIssue.message}`;\n}\n\nasync function validateArgsForTool(\n args: Record<string, unknown>,\n tool: PolyfillToolDescriptor\n): Promise<string | null> {\n return validateArgsWithStandardSchema(args, tool[STANDARD_VALIDATOR_SYMBOL]);\n}\n\nfunction validateOutputForTool(result: ToolResponse, tool: PolyfillToolDescriptor): string | null {\n if (!tool.outputSchema || result.isError) {\n return null;\n }\n\n if (result.structuredContent === undefined) {\n return `Output validation error: Tool ${tool.name} has an output schema but no structured content was provided`;\n }\n\n const issue = validateValueWithSchema(result.structuredContent, tool.outputSchema);\n return issue ? `Output validation error: ${issue.message}` : null;\n}\n\nfunction isCallToolResult(value: unknown): value is ToolResponse {\n return isPlainObject(value) && Array.isArray(value.content);\n}\n\nfunction serializeTextContent(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n\n try {\n const candidate = JSON.stringify(value);\n return candidate ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction normalizeToolResponse(value: unknown): ToolResponse {\n if (isCallToolResult(value)) {\n return value;\n }\n\n const structuredContent = toJsonValue(value);\n\n return {\n content: [\n {\n type: 'text',\n text: serializeTextContent(value),\n },\n ],\n ...(structuredContent !== undefined ? { structuredContent } : {}),\n isError: false,\n };\n}\n\nfunction getFirstTextBlock(result: ToolResponse): string | null {\n for (const block of result.content ?? []) {\n if (block.type === 'text' && 'text' in block && typeof block.text === 'string') {\n return block.text;\n }\n }\n\n return null;\n}\n\nfunction toSerializedTestingResult(result: ToolResponse): string | null {\n if (result.isError) {\n const firstText = getFirstTextBlock(result);\n const message = firstText?.replace(/^Error:\\s*/i, '').trim() || TOOL_INVOCATION_FAILED_MESSAGE;\n throw createUnknownError(message);\n }\n\n const metadata = (result as ToolResponse & { metadata?: { willNavigate?: boolean } }).metadata;\n if (metadata && typeof metadata === 'object' && metadata.willNavigate) {\n return null;\n }\n\n try {\n return JSON.stringify(result);\n } catch {\n throw createUnknownError(TOOL_INVOCATION_FAILED_MESSAGE);\n }\n}\n\nfunction withAbortSignal<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {\n if (!signal) {\n return operation;\n }\n\n if (signal.aborted) {\n return Promise.reject(createUnknownError(TOOL_CANCELLED_MESSAGE));\n }\n\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => {\n cleanup();\n reject(createUnknownError(TOOL_CANCELLED_MESSAGE));\n };\n\n const cleanup = () => {\n signal.removeEventListener('abort', onAbort);\n };\n\n signal.addEventListener('abort', onAbort, { once: true });\n\n operation.then(\n (value) => {\n cleanup();\n resolve(value);\n },\n (error) => {\n cleanup();\n reject(error);\n }\n );\n });\n}\n\nfunction getNavigator(): Navigator | null {\n if (typeof navigator !== 'undefined') {\n return navigator;\n }\n\n return null;\n}\n\nfunction getDocument(): Document | null {\n if (typeof document !== 'undefined') {\n return document;\n }\n\n return null;\n}\n\nfunction defineNavigatorProperty<K extends keyof Navigator>(\n target: Navigator,\n key: K,\n value: Navigator[K]\n): void {\n Object.defineProperty(target, key, {\n configurable: true,\n enumerable: true,\n writable: false,\n value,\n });\n}\n\nfunction defineDocumentModelContextProperty(target: Document, value: ModelContext): void {\n Object.defineProperty(target, 'modelContext', {\n configurable: true,\n enumerable: true,\n writable: false,\n value,\n });\n}\n\nlet navigatorModelContextDeprecationWarned = false;\n\n// Per webmachinelearning/webmcp#173 / PR #184, the modelContext getter moved\n// from Navigator to Document. We install on document.modelContext as the\n// primary surface and expose navigator.modelContext as a deprecated alias that\n// returns the same instance and logs a one-time console warning on first\n// access. This mirrors the deprecation behavior shipped in Chrome 150.\nfunction defineDeprecatedNavigatorModelContext(target: Navigator, value: ModelContext): void {\n Object.defineProperty(target, 'modelContext', {\n configurable: true,\n enumerable: true,\n get() {\n if (!navigatorModelContextDeprecationWarned) {\n navigatorModelContextDeprecationWarned = true;\n console.warn(\n '[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.'\n );\n }\n return value;\n },\n });\n}\n\nexport function initializeWebMCPPolyfill(options?: WebMCPPolyfillInitOptions): void {\n const nav = getNavigator();\n const doc = getDocument();\n if (!nav && !doc) {\n return;\n }\n\n const documentModelContext = doc?.modelContext;\n const hasDocumentModelContext = Boolean(documentModelContext);\n\n if (hasDocumentModelContext) {\n return;\n }\n\n const navigatorModelContext = nav?.modelContext;\n const hasNavigatorModelContext = Boolean(navigatorModelContext);\n\n if (installState.installed) {\n cleanupWebMCPPolyfill();\n }\n\n if (doc && navigatorModelContext) {\n installState.previousDocumentModelContextDescriptor = Object.getOwnPropertyDescriptor(\n doc,\n 'modelContext'\n );\n defineDocumentModelContextProperty(doc, navigatorModelContext);\n installState.installedDocumentModelContext = true;\n installState.installed = true;\n return;\n }\n\n if (hasNavigatorModelContext) {\n return;\n }\n\n const context = new StrictWebMCPContext();\n const modelContext = context as unknown as PolyfillModelContext;\n modelContext[POLYFILL_MARKER_PROPERTY] = true;\n\n if (doc) {\n installState.previousDocumentModelContextDescriptor = Object.getOwnPropertyDescriptor(\n doc,\n 'modelContext'\n );\n defineDocumentModelContextProperty(doc, modelContext as ModelContext);\n installState.installedDocumentModelContext = true;\n }\n\n if (nav) {\n installState.previousNavigatorModelContextDescriptor = Object.getOwnPropertyDescriptor(\n nav,\n 'modelContext'\n );\n installState.previousNavigatorModelContextTestingDescriptor = Object.getOwnPropertyDescriptor(\n nav,\n 'modelContextTesting'\n );\n\n // Reset the one-shot warning flag so a fresh install warns again on first access.\n navigatorModelContextDeprecationWarned = false;\n defineDeprecatedNavigatorModelContext(nav, modelContext as ModelContext);\n installState.installedNavigatorModelContext = true;\n\n const installTestingShim = options?.installTestingShim ?? 'if-missing';\n const hasModelContextTesting = Boolean(nav.modelContextTesting);\n const shouldInstallTestingShim =\n installTestingShim === 'always' ||\n ((installTestingShim === true || installTestingShim === 'if-missing') &&\n !hasModelContextTesting);\n\n if (shouldInstallTestingShim) {\n defineNavigatorProperty(\n nav,\n 'modelContextTesting',\n context.getTestingShim() as Navigator['modelContextTesting']\n );\n installState.installedNavigatorModelContextTesting = true;\n }\n }\n\n installState.installed = true;\n}\n\nexport function cleanupWebMCPPolyfill(): void {\n if (!installState.installed) {\n return;\n }\n\n const restore = (\n target: Navigator | Document,\n key: string,\n previousDescriptor: PropertyDescriptor | undefined\n ) => {\n if (previousDescriptor) {\n Object.defineProperty(target, key, previousDescriptor);\n return;\n }\n\n delete (target as unknown as Record<string, unknown>)[key];\n };\n\n const nav = getNavigator();\n const doc = getDocument();\n\n if (doc && installState.installedDocumentModelContext) {\n restore(doc, 'modelContext', installState.previousDocumentModelContextDescriptor);\n }\n if (nav && installState.installedNavigatorModelContext) {\n restore(nav, 'modelContext', installState.previousNavigatorModelContextDescriptor);\n }\n if (nav && installState.installedNavigatorModelContextTesting) {\n restore(\n nav,\n 'modelContextTesting',\n installState.previousNavigatorModelContextTestingDescriptor\n );\n }\n\n installState.installed = false;\n installState.previousDocumentModelContextDescriptor = undefined;\n installState.previousNavigatorModelContextDescriptor = undefined;\n installState.previousNavigatorModelContextTestingDescriptor = undefined;\n installState.installedDocumentModelContext = false;\n installState.installedNavigatorModelContext = false;\n installState.installedNavigatorModelContextTesting = false;\n navigatorModelContextDeprecationWarned = false;\n}\n\nexport { initializeWebMCPPolyfill as initializeWebModelContextPolyfill };\n\ndeclare global {\n interface Window {\n __webMCPPolyfillOptions?: WebMCPPolyfillInitOptions;\n }\n}\n\nif (typeof window !== 'undefined' && typeof document !== 'undefined') {\n const options = window.__webMCPPolyfillOptions;\n const shouldAutoInitialize = options?.autoInitialize !== false;\n\n if (shouldAutoInitialize) {\n try {\n initializeWebMCPPolyfill(options);\n } catch (error) {\n console.error('[WebMCPPolyfill] Auto-initialization failed:', error);\n }\n }\n}\n"],"mappings":";;;AAkCA,MAAM,0CAA0C;AAChD,MAAM,iCACJ;AACF,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;AAE3B,MAAM,2BAA2B;AACjC,MAAM,4BAA4B,OAAO,oBAAoB;AAE7D,SAAS,mBAA0B;CACjC,OAAO,IAAI,aAAa,oCAAoC,aAAa;;AA2B3E,MAAM,eAA6B;CACjC,WAAW;CACX,yCAAyC;CACzC,gDAAgD;CAChD,wCAAwC;CACxC,gCAAgC;CAChC,uCAAuC;CACvC,+BAA+B;CAChC;AAyBD,IAAM,sBAAN,cAAkC,YAAY;CAC5C,AAAQ,wBAAQ,IAAI,KAAqC;CACzD,AAAQ,cAA0C;CAClD,AAAQ,gBAAqE;CAC7E,AAAQ,kCAAkC;CAC1C,AAAQ,qBAAqB;CAE7B,IAAI,eAAoE;EACtE,OAAO,KAAK;;CAGd,IAAI,aAAa,SAA8D;EAC7E,KAAK,gBAAgB;;CAGvB,aAAa,MAAsB,SAA0D;EAC3F,MAAM,SAAS,SAAS;EAExB,IAAI,QAAQ,SACV,OAAO,QAAQ,OAAO,kBAAkB,CAAC;EAG3C,MAAM,aAAa,wBAAwB,MAAM,KAAK,MAAM;EAC5D,KAAK,MAAM,IAAI,WAAW,MAAM,WAAW;EAC3C,KAAK,oBAAoB;EAEzB,IAAI,QACF,OAAO,iBACL,eACM;GACJ,IAAI,KAAK,MAAM,OAAO,WAAW,KAAK,EACpC,KA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,OAGvD,IAAI;EACF,yBAAyB,QAAQ;UAC1B,OAAO;EACd,QAAQ,MAAM,gDAAgD,MAAM"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#tools","#ontoolchangeListener","#ontoolchangeHandler","#domException","#ownerDocument","#removeTool","#notifyToolsChanged","#invokeToolByName","#testingShim","#context"],"sources":["../src/declarative-forms.ts","../src/index.ts"],"sourcesContent":["import type { InputSchema, ModelContext, WebMcpToolInput } from '@mcp-b/webmcp-types';\n\ntype DeclarativeControl = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;\ntype Submitter = HTMLButtonElement | HTMLInputElement;\n\ninterface DeclarativeToolDefinition {\n name: string;\n title: string;\n description: string;\n inputSchema: InputSchema;\n autosubmit: boolean;\n}\n\ninterface DeclarativeRegistration {\n controller: AbortController;\n fingerprint: string;\n form: HTMLFormElement;\n cancelPending?: (reason: unknown) => void;\n}\n\ninterface ActiveSubmission {\n complete(event: SubmitEvent): void;\n direct(): void;\n respond(event: SubmitEvent): void;\n}\n\nconst agentInvokedEvents = new WeakSet<SubmitEvent>();\nconst agentResponses = new WeakMap<SubmitEvent, Promise<unknown>>();\nconst activeSubmissions = new WeakMap<HTMLFormElement, ActiveSubmission>();\n\nexport function isAgentInvokedSubmitEvent(event: SubmitEvent): boolean {\n return (\n event.isTrusted &&\n (agentInvokedEvents.has(event) ||\n (event.eventPhase !== Event.NONE &&\n event.target instanceof HTMLFormElement &&\n activeSubmissions.has(event.target)))\n );\n}\n\nexport function respondWithAgentSubmitEvent(\n event: SubmitEvent,\n agentResponse: Promise<unknown>\n): void {\n if (!isAgentInvokedSubmitEvent(event)) {\n throw new DOMException(\n 'respondWith() is only available during an agent-invoked submit event',\n 'InvalidStateError'\n );\n }\n if (!event.defaultPrevented) {\n throw new DOMException(\n 'respondWith() requires preventDefault() during an agent-invoked submit event',\n 'InvalidStateError'\n );\n }\n if (event.eventPhase === Event.NONE) {\n throw new DOMException(\n 'respondWith() is only available while the submit event is being dispatched',\n 'InvalidStateError'\n );\n }\n agentInvokedEvents.add(event);\n const response = Promise.resolve(agentResponse);\n agentResponses.set(event, response);\n if (event.target instanceof HTMLFormElement) {\n activeSubmissions.get(event.target)?.respond(event);\n }\n}\n\nconst TEXT_INPUT_TYPES = new Set(['email', 'password', 'search', 'tel', 'text', 'url']);\nconst READONLY_INPUT_TYPES = new Set([\n ...TEXT_INPUT_TYPES,\n 'date',\n 'datetime-local',\n 'month',\n 'number',\n 'time',\n 'week',\n]);\n\nfunction isControl(element: Element): element is DeclarativeControl {\n return (\n element instanceof HTMLInputElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement\n );\n}\n\nfunction getFormControls(form: HTMLFormElement): HTMLFormControlsCollection {\n return Reflect.get(HTMLFormElement.prototype, 'elements', form);\n}\n\nfunction getFormAttribute(form: HTMLFormElement, name: string): string | null {\n return Reflect.apply(Element.prototype.getAttribute, form, [name]);\n}\n\nfunction formHasAttribute(form: HTMLFormElement, name: string): boolean {\n return Reflect.apply(Element.prototype.hasAttribute, form, [name]);\n}\n\nfunction isFormConnected(form: HTMLFormElement): boolean {\n return Reflect.get(Node.prototype, 'isConnected', form);\n}\n\nfunction getOpenShadowRoot(element: Element): ShadowRoot | null {\n return Reflect.get(Element.prototype, 'shadowRoot', element);\n}\n\nfunction checkFormValidity(form: HTMLFormElement): boolean {\n return Reflect.apply(HTMLFormElement.prototype.checkValidity, form, []);\n}\n\nfunction requestFormSubmit(form: HTMLFormElement, submitter?: Submitter): void {\n Reflect.apply(HTMLFormElement.prototype.requestSubmit, form, submitter ? [submitter] : []);\n}\n\nfunction getControls(form: HTMLFormElement): DeclarativeControl[] {\n return [...getFormControls(form)].filter(\n (element): element is DeclarativeControl =>\n isControl(element) &&\n !element.matches(':disabled') &&\n !(\n 'readOnly' in element &&\n element.readOnly &&\n (element instanceof HTMLTextAreaElement || READONLY_INPUT_TYPES.has(element.type))\n )\n );\n}\n\nfunction controlGroups(form: HTMLFormElement): Map<string, DeclarativeControl[]> {\n const groups = new Map<string, DeclarativeControl[]>();\n for (const control of getControls(form)) {\n const name = control.name.trim();\n const controls = groups.get(name);\n if (controls) controls.push(control);\n else groups.set(name, [control]);\n }\n return groups;\n}\n\nfunction labelText(control: DeclarativeControl): string {\n return [...(control.labels ?? [])]\n .map((label) => {\n const copy = label.cloneNode(true);\n if (!(copy instanceof HTMLElement)) return '';\n copy\n .querySelectorAll('button, input, meter, output, progress, select, textarea')\n .forEach((element) => element.remove());\n return copy.textContent?.trim() ?? '';\n })\n .filter(Boolean)\n .join('; ');\n}\n\nfunction commonFieldset(\n form: HTMLFormElement,\n controls: readonly DeclarativeControl[]\n): HTMLFieldSetElement | undefined {\n for (\n let element = controls[0]?.parentElement;\n element && element !== form;\n element = element.parentElement\n ) {\n if (\n element instanceof HTMLFieldSetElement &&\n controls.every((control) => element.contains(control))\n ) {\n return element;\n }\n }\n return undefined;\n}\n\nfunction parameterDescription(\n form: HTMLFormElement,\n controls: readonly DeclarativeControl[]\n): string | undefined {\n if (controls.length === 1) {\n const control = controls[0];\n if (!control) return undefined;\n return (\n control.getAttribute('toolparamdescription') ||\n labelText(control) ||\n control.getAttribute('aria-description') ||\n undefined\n );\n }\n return commonFieldset(form, controls)?.getAttribute('toolparamdescription') || undefined;\n}\n\nfunction withDescription(\n schema: Record<string, unknown>,\n form: HTMLFormElement,\n controls: readonly DeclarativeControl[],\n extra?: string\n): Record<string, unknown> {\n const description = parameterDescription(form, controls);\n const combined = description && extra ? `${description} (${extra})` : description || extra;\n return combined ? { ...schema, description: combined } : schema;\n}\n\nfunction validNumberAttribute(input: HTMLInputElement, name: 'max' | 'min'): number | undefined {\n const raw = input.getAttribute(name);\n if (raw === null || raw.trim() === '') return undefined;\n const value = Number(raw);\n return Number.isFinite(value) ? value : undefined;\n}\n\nfunction isStepBaseMultiple(stepBase: number, step: number): boolean {\n const quotient = stepBase / step;\n return Math.abs(quotient - Math.round(quotient)) < Number.EPSILON * 16;\n}\n\nfunction validPattern(input: HTMLInputElement): string | undefined {\n const pattern = input.getAttribute('pattern');\n if (pattern === null) return undefined;\n try {\n new RegExp(pattern, 'v');\n return pattern;\n } catch {\n return undefined;\n }\n}\n\nfunction numberSchema(input: HTMLInputElement, includePattern = true): Record<string, unknown> {\n const schema: Record<string, unknown> = { type: 'number' };\n const minimum = validNumberAttribute(input, 'min');\n const maximum = validNumberAttribute(input, 'max');\n if (minimum !== undefined) schema.minimum = minimum;\n if (maximum !== undefined) schema.maximum = maximum;\n\n const rawStep = input.getAttribute('step');\n if (rawStep !== 'any') {\n const parsedStep = rawStep === null || rawStep === '' ? 1 : Number(rawStep);\n const step = Number.isFinite(parsedStep) && parsedStep > 0 ? parsedStep : 1;\n const rawValue = Number(input.getAttribute('value'));\n const stepBase = minimum ?? (Number.isFinite(rawValue) ? rawValue : 0);\n if (isStepBaseMultiple(stepBase, step)) schema.multipleOf = step;\n }\n\n const pattern = includePattern ? validPattern(input) : undefined;\n if (pattern !== undefined) schema.pattern = pattern;\n return schema;\n}\n\nfunction temporalFormat(input: HTMLInputElement, datePrefix: string): string {\n const rawStep = input.getAttribute('step');\n const parsedStep = rawStep === null || rawStep === '' ? 60 : Number(rawStep);\n const step = Number.isFinite(parsedStep) && parsedStep > 0 ? parsedStep : 60;\n if (step < 1) return `${datePrefix}(:[0-5][0-9](\\\\.[0-9]{1,3})?)?$`;\n if (step < 60) return `${datePrefix}(:[0-5][0-9])?$`;\n return `${datePrefix}$`;\n}\n\nfunction optionSchemas(options: readonly HTMLOptionElement[]): {\n anyOf: Record<string, unknown>[];\n enum: string[];\n} {\n return {\n anyOf: options.map((option) => ({\n type: 'string',\n const: option.value,\n title: option.textContent ?? '',\n })),\n enum: options.map((option) => option.value),\n };\n}\n\nfunction groupChoiceSchemas(controls: readonly HTMLInputElement[]): {\n anyOf: Record<string, unknown>[];\n enum: string[];\n} {\n return {\n anyOf: controls.map((control) => {\n const title = labelText(control);\n return { type: 'string', const: control.value, ...(title ? { title } : {}) };\n }),\n enum: controls.map((control) => control.value),\n };\n}\n\nfunction parameterSchema(\n form: HTMLFormElement,\n controls: readonly DeclarativeControl[]\n): Record<string, unknown> | undefined {\n const first = controls[0];\n if (!first) return undefined;\n\n if (controls.length > 1) {\n if (!controls.every((control) => control instanceof HTMLInputElement)) return undefined;\n if (controls.every((control) => control.type === 'checkbox')) {\n return withDescription(\n {\n type: 'array',\n items: { type: 'string', ...groupChoiceSchemas(controls) },\n uniqueItems: true,\n },\n form,\n controls\n );\n }\n if (controls.every((control) => control.type === 'radio')) {\n return withDescription({ type: 'string', ...groupChoiceSchemas(controls) }, form, controls);\n }\n return undefined;\n }\n\n if (first instanceof HTMLTextAreaElement) {\n return withDescription({ type: 'string' }, form, controls);\n }\n\n if (first instanceof HTMLSelectElement) {\n const choices = optionSchemas([...first.options]);\n return withDescription(\n first.multiple\n ? { type: 'array', items: { type: 'string', ...choices }, uniqueItems: true }\n : { type: 'string', ...choices },\n form,\n controls\n );\n }\n\n if (TEXT_INPUT_TYPES.has(first.type)) {\n const schema: Record<string, unknown> = { type: 'string' };\n const pattern = validPattern(first);\n if (pattern !== undefined) schema.pattern = pattern;\n return withDescription(schema, form, controls);\n }\n if (first.type === 'hidden') {\n return first.getAttribute('toolparamdescription')\n ? withDescription({ type: 'string' }, form, controls)\n : undefined;\n }\n if (first.type === 'number') {\n return withDescription(numberSchema(first), form, controls);\n }\n if (first.type === 'range') {\n const schema = numberSchema(first, false);\n schema.minimum ??= 0;\n schema.maximum ??= 100;\n return withDescription(schema, form, controls);\n }\n if (first.type === 'checkbox') {\n return withDescription({ type: 'boolean' }, form, controls);\n }\n if (first.type === 'radio') {\n return withDescription({ type: 'string', ...groupChoiceSchemas([first]) }, form, controls);\n }\n if (first.type === 'date') {\n return withDescription(\n { type: 'string', format: 'date' },\n form,\n controls,\n \"Dates MUST be provided in 'YYYY-MM-DD' format.\"\n );\n }\n if (first.type === 'month') {\n return withDescription(\n { type: 'string', format: '^[0-9]{4}-(0[1-9]|1[0-2])$' },\n form,\n controls\n );\n }\n if (first.type === 'week') {\n return withDescription(\n { type: 'string', format: '^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$' },\n form,\n controls\n );\n }\n if (first.type === 'time') {\n return withDescription(\n {\n type: 'string',\n format: temporalFormat(first, '^([01][0-9]|2[0-3]):[0-5][0-9]'),\n },\n form,\n controls\n );\n }\n if (first.type === 'datetime-local') {\n return withDescription(\n {\n type: 'string',\n format: temporalFormat(\n first,\n '^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T([01][0-9]|2[0-3]):[0-5][0-9]'\n ),\n },\n form,\n controls\n );\n }\n if (first.type === 'color') {\n return withDescription({ type: 'string', format: '^#[0-9a-zA-Z]{6}$' }, form, controls);\n }\n return undefined;\n}\n\nfunction synthesizeSchema(form: HTMLFormElement): InputSchema {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [name, controls] of controlGroups(form)) {\n if (!name) continue;\n const schema = parameterSchema(form, controls);\n if (!schema) continue;\n Object.defineProperty(properties, name, {\n configurable: true,\n enumerable: true,\n value: schema,\n writable: true,\n });\n if (controls.some((control) => control.required)) required.push(name);\n }\n return { type: 'object', properties, required };\n}\n\nfunction toolDefinition(form: HTMLFormElement): DeclarativeToolDefinition {\n return {\n name: getFormAttribute(form, 'toolname') ?? '',\n title: getFormAttribute(form, 'tooltitle') ?? '',\n description: getFormAttribute(form, 'tooldescription') ?? '',\n inputSchema: synthesizeSchema(form),\n autosubmit: formHasAttribute(form, 'toolautosubmit'),\n };\n}\n\nfunction toFormString(value: unknown): string | undefined {\n if (typeof value === 'string' || typeof value === 'boolean') return String(value);\n if (typeof value === 'number' && Number.isFinite(value)) return String(value);\n return undefined;\n}\n\nfunction toFormBoolean(value: unknown): boolean | undefined {\n if (typeof value === 'boolean') return value;\n if (typeof value === 'number' && Number.isInteger(value)) return value !== 0;\n if (typeof value !== 'string') return undefined;\n if (value === '1' || value.toLowerCase() === 'true') return true;\n if (value === '0' || value.toLowerCase() === 'false') return false;\n return undefined;\n}\n\nfunction hasUniqueAllowedValues(value: unknown, allowed: ReadonlySet<string>): value is unknown[] {\n if (!Array.isArray(value)) return false;\n const remaining = new Set(allowed);\n for (const item of value) {\n const string = toFormString(item);\n if (string === undefined || !remaining.delete(string)) return false;\n }\n return true;\n}\n\nfunction inputAcceptsValue(input: HTMLInputElement, value: string): boolean {\n if (value === '') return input.type !== 'number' && input.type !== 'range';\n const probe = input.ownerDocument.createElement('input');\n probe.type = input.type;\n probe.value = value;\n return probe.value !== '';\n}\n\nfunction validatesParameter(\n form: HTMLFormElement,\n controls: readonly DeclarativeControl[],\n value: unknown\n): boolean {\n const first = controls[0];\n if (!first || !parameterSchema(form, controls)) return false;\n\n if (controls.length > 1) {\n if (!controls.every((control) => control instanceof HTMLInputElement)) return false;\n if (controls.every((control) => control.type === 'checkbox')) {\n return hasUniqueAllowedValues(value, new Set(controls.map((control) => control.value)));\n }\n if (controls.every((control) => control.type === 'radio')) {\n const string = toFormString(value);\n return string !== undefined && controls.some((control) => control.value === string);\n }\n return false;\n }\n\n if (first instanceof HTMLSelectElement) {\n const allowed = new Set([...first.options].map((option) => option.value));\n if (first.multiple) return hasUniqueAllowedValues(value, allowed);\n const string = toFormString(value);\n return string !== undefined && allowed.has(string);\n }\n if (first instanceof HTMLTextAreaElement) return toFormString(value) !== undefined;\n if (first.type === 'checkbox') return toFormBoolean(value) !== undefined;\n if (first.type === 'radio') {\n const string = toFormString(value);\n return string !== undefined && first.value === string;\n }\n const string = toFormString(value);\n return string !== undefined && inputAcceptsValue(first, string);\n}\n\nfunction dispatchInputAndChange(control: DeclarativeControl): void {\n control.dispatchEvent(new Event('input', { bubbles: true, composed: true }));\n control.dispatchEvent(new Event('change', { bubbles: true }));\n}\n\nfunction setNativeValue(control: HTMLInputElement | HTMLTextAreaElement, value: string): void {\n const prototype =\n control instanceof HTMLInputElement\n ? HTMLInputElement.prototype\n : HTMLTextAreaElement.prototype;\n Object.getOwnPropertyDescriptor(prototype, 'value')?.set?.call(control, value);\n}\n\nfunction setNativeChecked(control: HTMLInputElement, checked: boolean): void {\n Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked')?.set?.call(\n control,\n checked\n );\n}\n\nfunction fillParameter(controls: readonly DeclarativeControl[], value: unknown): void {\n const first = controls[0];\n if (!first) return;\n\n if (controls.length > 1 && controls.every((control) => control instanceof HTMLInputElement)) {\n if (controls.every((control) => control.type === 'checkbox') && Array.isArray(value)) {\n const checked = new Set(value.map(toFormString));\n for (const control of controls) {\n const next = checked.has(control.value);\n if (control.checked === next) continue;\n setNativeChecked(control, next);\n dispatchInputAndChange(control);\n }\n return;\n }\n const selected = toFormString(value);\n const control = controls.find((candidate) => candidate.value === selected);\n if (control && !control.checked) {\n setNativeChecked(control, true);\n dispatchInputAndChange(control);\n }\n return;\n }\n\n if (first instanceof HTMLSelectElement) {\n if (first.multiple && Array.isArray(value)) {\n const selected = new Set(value.map(toFormString));\n let changed = false;\n for (const option of first.options) {\n const next = selected.has(option.value);\n if (option.selected === next) continue;\n option.selected = next;\n changed = true;\n }\n if (changed) dispatchInputAndChange(first);\n return;\n }\n const next = toFormString(value);\n if (next !== undefined && first.value !== next) {\n first.value = next;\n dispatchInputAndChange(first);\n }\n return;\n }\n\n if (first instanceof HTMLInputElement && first.type === 'checkbox') {\n const next = toFormBoolean(value);\n if (next !== undefined && first.checked !== next) {\n setNativeChecked(first, next);\n dispatchInputAndChange(first);\n }\n return;\n }\n\n if (first instanceof HTMLInputElement && first.type === 'radio') {\n const next = toFormString(value);\n if (next === first.value && !first.checked) {\n setNativeChecked(first, true);\n dispatchInputAndChange(first);\n }\n return;\n }\n\n const next = toFormString(value);\n if (next !== undefined && first.value !== next) {\n setNativeValue(first, next);\n dispatchInputAndChange(first);\n }\n}\n\nfunction fillForm(form: HTMLFormElement, input: WebMcpToolInput): void {\n if (Array.isArray(input)) throw new TypeError('Declarative tool input must be an object');\n const groups = controlGroups(form);\n for (const [name, value] of Object.entries(input)) {\n const controls = groups.get(name);\n if (!controls || !validatesParameter(form, controls, value)) {\n throw new TypeError(`Invalid value for declarative form parameter \"${name}\"`);\n }\n }\n for (const [name, value] of Object.entries(input)) fillParameter(groups.get(name) ?? [], value);\n}\n\nfunction findSubmitter(form: HTMLFormElement): Submitter | undefined {\n return [...getFormControls(form)].find(\n (element): element is Submitter =>\n !element.matches(':disabled') &&\n ((element instanceof HTMLButtonElement && element.type === 'submit') ||\n (element instanceof HTMLInputElement && ['image', 'submit'].includes(element.type)))\n );\n}\n\nfunction validationError(form: HTMLFormElement): DOMException {\n const failures = [...getFormControls(form)]\n .filter(\n (element): element is DeclarativeControl =>\n isControl(element) && element.willValidate && !element.validity.valid\n )\n .map((control) => `${control.name.trim() || '{unknown}'}: ${control.validationMessage}`)\n .join('. ');\n return new DOMException(`Form validation failed: ${failures}`, 'UnknownError');\n}\n\nfunction toolActivatedEvent(toolName: string): Event {\n const event = new Event('toolactivated');\n Object.defineProperty(event, 'toolName', { enumerable: true, value: toolName });\n return event;\n}\n\nfunction waitForSubmission(\n registration: DeclarativeRegistration,\n toolName: string,\n autosubmit: boolean,\n submitter: Submitter | undefined\n): Promise<unknown> {\n const { form } = registration;\n registration.cancelPending?.(new DOMException('Tool execution cancelled', 'UnknownError'));\n\n return new Promise((resolve, reject) => {\n let settled = false;\n\n const cleanup = () => {\n Reflect.apply(EventTarget.prototype.removeEventListener, form, ['invalid', onInvalid, true]);\n activeSubmissions.delete(form);\n if (registration.cancelPending === cancel) delete registration.cancelPending;\n };\n const finish = (callback: () => void) => {\n if (settled) return;\n settled = true;\n cleanup();\n callback();\n };\n const cancel = (reason: unknown) => finish(() => reject(reason));\n const settleResponse = (response: Promise<unknown>) => {\n response.then(\n (value) => finish(() => resolve(value)),\n (error: unknown) => finish(() => reject(error))\n );\n };\n const onInvalid = (event: Event) => {\n if (!event.isTrusted) return;\n queueMicrotask(() => {\n if (!checkFormValidity(form)) cancel(validationError(form));\n });\n };\n\n activeSubmissions.set(form, {\n complete(event) {\n queueMicrotask(() => {\n const response = agentResponses.get(event);\n if (response) settleResponse(response);\n else if (event.defaultPrevented) {\n cancel(new DOMException('preventDefault() requires respondWith()', 'UnknownError'));\n } else finish(() => resolve(undefined));\n });\n },\n direct() {\n finish(() => resolve(undefined));\n },\n respond(event) {\n queueMicrotask(() => {\n const response = agentResponses.get(event);\n if (response) settleResponse(response);\n });\n },\n });\n registration.cancelPending = cancel;\n Reflect.apply(EventTarget.prototype.addEventListener, form, ['invalid', onInvalid, true]);\n\n if (!autosubmit) {\n submitter?.focus();\n window.dispatchEvent(toolActivatedEvent(toolName));\n return;\n }\n try {\n requestFormSubmit(form, submitter);\n window.dispatchEvent(toolActivatedEvent(toolName));\n } catch (error) {\n cancel(error);\n }\n });\n}\n\n/** Installs the DOM-backed half of the draft Declarative WebMCP API. */\nexport function installDeclarativeForms(document: Document, context: ModelContext): () => void {\n let active = true;\n const registrations = new Map<HTMLFormElement, DeclarativeRegistration>();\n const blockedDefinitions = new Map<HTMLFormElement, string>();\n const observers = new Map<Document | ShadowRoot, MutationObserver>();\n const onSubmit = (event: Event) => {\n if (\n !(event instanceof SubmitEvent) ||\n !event.isTrusted ||\n !(event.target instanceof HTMLFormElement)\n ) {\n return;\n }\n // Only a form with a running tool call submits on the agent's behalf; marking\n // every trusted submit would report agentInvoked for ordinary user submissions.\n const submission = activeSubmissions.get(event.target);\n if (!submission) return;\n agentInvokedEvents.add(event);\n submission.complete(event);\n };\n\n const onReset = (event: Event) => {\n if (!event.isTrusted || !(event.target instanceof HTMLFormElement)) return;\n const form = event.target;\n queueMicrotask(() => {\n if (event.defaultPrevented) return;\n registrations\n .get(form)\n ?.cancelPending?.(\n new DOMException('Tool execution cancelled by form reset', 'UnknownError')\n );\n });\n };\n\n function stopObservingRoot(root: Document | ShadowRoot): void {\n observers.get(root)?.disconnect();\n observers.delete(root);\n root.removeEventListener('reset', onReset, true);\n root.removeEventListener('submit', onSubmit, true);\n }\n\n function observeRoot(root: Document | ShadowRoot): void {\n if (observers.has(root)) return;\n const observer = new MutationObserver(sync);\n observers.set(root, observer);\n observer.observe(root, {\n attributes: true,\n characterData: true,\n childList: true,\n subtree: true,\n });\n root.addEventListener('reset', onReset, true);\n // ponytail: submit is composed:false, so per-root capture sees every submission; hook\n // window capture too if a page listener ever stops propagation before this one.\n root.addEventListener('submit', onSubmit, true);\n }\n\n function sync(): void {\n observeRoot(document);\n for (const root of observers.keys()) {\n if (root instanceof ShadowRoot && !Reflect.get(Node.prototype, 'isConnected', root.host)) {\n stopObservingRoot(root);\n }\n }\n\n const candidates = new Set<HTMLFormElement>();\n const selected = new Map<\n HTMLFormElement,\n { definition: DeclarativeToolDefinition; fingerprint: string }\n >();\n const selectedByName = new Map<string, HTMLFormElement>();\n for (const root of observers.keys()) {\n for (const element of root.querySelectorAll('*')) {\n const shadowRoot = getOpenShadowRoot(element);\n if (shadowRoot) observeRoot(shadowRoot);\n\n if (\n !(element instanceof HTMLFormElement) ||\n !formHasAttribute(element, 'toolname') ||\n !formHasAttribute(element, 'tooldescription') ||\n !isFormConnected(element)\n ) {\n continue;\n }\n const form = element;\n candidates.add(form);\n const definition = toolDefinition(form);\n const fingerprint = JSON.stringify(definition);\n const blockedFingerprint = blockedDefinitions.get(form);\n if (blockedFingerprint === fingerprint) continue;\n const retryingChangedDefinition = blockedFingerprint !== undefined;\n blockedDefinitions.delete(form);\n const existingForm = selectedByName.get(definition.name);\n if (existingForm && !retryingChangedDefinition) {\n blockedDefinitions.set(form, fingerprint);\n continue;\n }\n if (existingForm) {\n const existingSelection = selected.get(existingForm);\n if (existingSelection) {\n blockedDefinitions.set(existingForm, existingSelection.fingerprint);\n selected.delete(existingForm);\n }\n }\n selectedByName.set(definition.name, form);\n selected.set(form, { definition, fingerprint });\n }\n }\n for (const form of blockedDefinitions.keys()) {\n if (!candidates.has(form)) blockedDefinitions.delete(form);\n }\n\n for (const [form, registration] of registrations) {\n const fingerprint = selected.get(form)?.fingerprint;\n if (fingerprint !== registration.fingerprint) {\n registration.cancelPending?.(\n new DOMException('Tool execution cancelled because its form changed', 'UnknownError')\n );\n registration.controller.abort();\n registrations.delete(form);\n }\n }\n\n for (const [form, { definition, fingerprint }] of selected) {\n if (registrations.has(form)) continue;\n const controller = new AbortController();\n const registration: DeclarativeRegistration = {\n controller,\n fingerprint,\n form,\n };\n registrations.set(form, registration);\n void context\n .registerTool(\n {\n name: definition.name,\n title: definition.title,\n description: definition.description,\n inputSchema: definition.inputSchema,\n execute(input: WebMcpToolInput) {\n const submitter = findSubmitter(form);\n if (!definition.autosubmit && !submitter) {\n throw new DOMException(\n 'A declarative form without toolautosubmit requires a submit button',\n 'UnknownError'\n );\n }\n fillForm(form, input);\n return waitForSubmission(\n registration,\n definition.name,\n definition.autosubmit,\n submitter\n );\n },\n },\n { signal: controller.signal }\n )\n .catch((error: unknown) => {\n controller.abort();\n // Invalid toolname/tooldescription attributes reject here. Without this the\n // form silently never becomes a tool, with no diagnostic in any channel.\n // Aborts are ordinary teardown, not a failure worth reporting.\n if ((error as { name?: unknown } | null)?.name === 'AbortError') return;\n console.error(\n `[webmcp] declarative form tool \"${definition.name}\" was not registered:`,\n error\n );\n });\n }\n }\n\n let restoreAttachShadow = () => {};\n const elementPrototype = document.defaultView?.Element.prototype;\n const attachShadowDescriptor = elementPrototype\n ? Object.getOwnPropertyDescriptor(elementPrototype, 'attachShadow')\n : undefined;\n if (elementPrototype && attachShadowDescriptor?.configurable) {\n const nativeAttachShadow = elementPrototype.attachShadow;\n const attachShadow = function (this: Element, init: ShadowRootInit): ShadowRoot {\n const root = nativeAttachShadow.call(this, init);\n if (\n active &&\n root.mode === 'open' &&\n Reflect.get(Node.prototype, 'ownerDocument', this) === document &&\n Reflect.get(Node.prototype, 'isConnected', this)\n ) {\n observeRoot(root);\n }\n return root;\n };\n Object.defineProperty(elementPrototype, 'attachShadow', {\n ...attachShadowDescriptor,\n value: attachShadow,\n });\n restoreAttachShadow = () => {\n if (elementPrototype.attachShadow === attachShadow) {\n Object.defineProperty(elementPrototype, 'attachShadow', attachShadowDescriptor);\n }\n };\n }\n\n let restoreFormSubmit = () => {};\n const formPrototype = document.defaultView?.HTMLFormElement.prototype;\n const submitDescriptor = formPrototype\n ? Object.getOwnPropertyDescriptor(formPrototype, 'submit')\n : undefined;\n if (formPrototype && submitDescriptor?.configurable) {\n const nativeSubmit = formPrototype.submit;\n const submit = function (this: HTMLFormElement): void {\n nativeSubmit.call(this);\n if (active) activeSubmissions.get(this)?.direct();\n };\n Object.defineProperty(formPrototype, 'submit', { ...submitDescriptor, value: submit });\n restoreFormSubmit = () => {\n if (formPrototype.submit === submit) {\n Object.defineProperty(formPrototype, 'submit', submitDescriptor);\n }\n };\n }\n\n // ponytail: a whole-tree rescan keeps DOM ownership obvious; index forms if this\n // becomes measurable on pages with thousands of annotated controls.\n sync();\n\n return () => {\n active = false;\n restoreFormSubmit();\n restoreAttachShadow();\n for (const root of observers.keys()) stopObservingRoot(root);\n blockedDefinitions.clear();\n for (const registration of registrations.values()) {\n registration.cancelPending?.(new DOMException('Tool execution cancelled', 'UnknownError'));\n registration.controller.abort();\n }\n registrations.clear();\n };\n}\n","import type {\n ChromeModelContextExecuteToolOptions,\n ModelContext,\n ModelContextGetToolOptions,\n ModelContextRegisterToolOptions,\n ModelContextTesting,\n ModelContextTestingToolInfo,\n ModelContextTool,\n RegisteredTool,\n WebMcpToolInput,\n} from '@mcp-b/webmcp-types';\nimport {\n coerceWebMcpToolDescriptor,\n createInvalidStateError,\n createToolInvocationFailedError,\n createUnknownError,\n isPlainObject,\n parseChromeToolInput,\n serializeChromeToolResult,\n serializeInputSchema,\n toWebMcpAnnotations,\n validateExecutableOrigin,\n validatePotentiallyTrustworthyOrigins,\n validateWebMcpAccess,\n validateWebMcpToolDescriptor,\n withAbortSignal,\n} from './schema.js';\nimport {\n installDeclarativeForms,\n isAgentInvokedSubmitEvent,\n respondWithAgentSubmitEvent,\n} from './declarative-forms.js';\n\nconst POLYFILL_MARKER_PROPERTY = '__isWebMCPPolyfill' as const;\nconst REGISTERED_INPUT_SCHEMA_SYMBOL = Symbol('registeredInputSchema');\nconst REGISTRATION_SIGNAL_SYMBOL = Symbol('registrationSignal');\nconst REGISTRATION_ABORT_SYMBOL = Symbol('registrationAbort');\n\ninterface PolyfillToolDescriptor extends Omit<ModelContextTool<WebMcpToolInput>, 'execute'> {\n execute(input: WebMcpToolInput): unknown;\n [REGISTERED_INPUT_SCHEMA_SYMBOL]?: string;\n [REGISTRATION_SIGNAL_SYMBOL]?: AbortSignal;\n [REGISTRATION_ABORT_SYMBOL]?: () => void;\n}\n\ninterface InstalledProperty {\n target: object;\n key: PropertyKey;\n previous: PropertyDescriptor | undefined;\n}\n\nconst installedProperties: InstalledProperty[] = [];\nlet installedContext: StrictWebMCPContext | null = null;\nlet cleanupDeclarativeForms: (() => void) | null = null;\n\nfunction currentOrigin(): string {\n return typeof globalThis.origin === 'string'\n ? globalThis.origin\n : (globalThis.location?.origin ?? '');\n}\n\nfunction installProperty(target: object, key: PropertyKey, descriptor: PropertyDescriptor): void {\n const previous = Object.getOwnPropertyDescriptor(target, key);\n try {\n Object.defineProperty(target, key, descriptor);\n } catch (error) {\n cleanupWebMCPPolyfill();\n throw error;\n }\n installedProperties.push({ target, key, previous });\n}\n\nexport interface WebMCPPolyfillInitOptions {\n /**\n * Controls installation of navigator.modelContextTesting when this polyfill provides modelContext.\n * The shim is testing-only and never replaces an existing implementation.\n *\n * Off by default so the polyfill stays spec-pure; modelContextTesting is a removed\n * Chromium preview API. `@mcp-b/global` deliberately opts in (its own default is true).\n * @default false\n */\n installTestingShim?: boolean;\n}\n\nclass StrictWebMCPContext extends EventTarget implements ModelContext {\n // ECMAScript #private, not TypeScript `private`: TypeScript's modifier is\n // erased at build time and leaves ordinary own enumerable properties, which\n // leak through Object.keys/for..in/spread and make JSON.stringify throw on\n // the ownerDocument cycle. Chrome's ModelContext instance has no own keys.\n readonly #tools = new Map<string, PolyfillToolDescriptor>();\n #testingShim: PolyfillTestingShim | null = null;\n #ontoolchangeHandler: ((this: ModelContext, ev: Event) => unknown) | null = null;\n readonly #ontoolchangeListener: EventListener = (event) => {\n this.#ontoolchangeHandler?.call(this, event);\n };\n readonly #domException: typeof DOMException;\n readonly #ownerDocument: Document | null;\n\n constructor(ownerDocument: Document | null) {\n super();\n this.#ownerDocument = ownerDocument;\n this.#domException = ownerDocument?.defaultView?.DOMException ?? DOMException;\n // The sole deliberate exception to \"Chrome's ModelContext has no own keys\":\n // this is the documented polyfill-vs-native check, read by\n // e2e/web-standards-showcase/src/api/detection.ts and the e2e specs. Keeping\n // it non-enumerable means the instance still spreads, enumerates, and\n // JSON.stringify()s exactly like Chrome's.\n Object.defineProperty(this, POLYFILL_MARKER_PROPERTY, {\n value: true,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n }\n\n get ontoolchange(): ((this: ModelContext, ev: Event) => unknown) | null {\n return this.#ontoolchangeHandler;\n }\n\n set ontoolchange(handler: ((this: ModelContext, ev: Event) => unknown) | null) {\n const listener = typeof handler === 'function' ? handler : null;\n if (listener === null) {\n this.#ontoolchangeHandler = null;\n super.removeEventListener('toolchange', this.#ontoolchangeListener);\n return;\n }\n\n if (this.#ontoolchangeHandler === null) {\n super.addEventListener('toolchange', this.#ontoolchangeListener);\n }\n this.#ontoolchangeHandler = listener;\n }\n\n // The `= {}` defaults on `options` here and in getTools/executeTool are\n // load-bearing: a defaulted parameter is excluded from Function.length, which\n // is what gives these three the arity WebIDL requires and idlharness checks\n // (1, 0, 2). The `options?.` reads stay too — a default only fills in\n // `undefined`, so an explicitly passed `null` still reaches the body.\n async registerTool<TArgs extends WebMcpToolInput>(\n tool: ModelContextTool<TArgs>,\n options: ModelContextRegisterToolOptions = {}\n ): Promise<void> {\n validateWebMcpAccess(this.#ownerDocument);\n const signal = options?.signal;\n const normalized = normalizeToolDescriptor(tool, this.#tools);\n signal?.throwIfAborted();\n validatePotentiallyTrustworthyOrigins(options?.exposedTo);\n signal?.throwIfAborted();\n if (options?.exposedTo?.length) {\n throw new this.#domException(\n 'Cross-document tool exposure requires native WebMCP',\n 'NotSupportedError'\n );\n }\n this.#tools.set(normalized.name, normalized);\n\n if (signal) {\n const abort = () => {\n if (this.#removeTool(normalized.name, normalized)) void this.#notifyToolsChanged();\n };\n normalized[REGISTRATION_SIGNAL_SYMBOL] = signal;\n normalized[REGISTRATION_ABORT_SYMBOL] = abort;\n signal.addEventListener('abort', abort, { once: true });\n }\n\n await this.#notifyToolsChanged();\n if (signal?.aborted) throw signal.reason;\n }\n\n async getTools(options: ModelContextGetToolOptions = {}): Promise<RegisteredTool[]> {\n validateWebMcpAccess(this.#ownerDocument);\n validatePotentiallyTrustworthyOrigins(options?.fromOrigins);\n if (options?.fromOrigins?.length) {\n throw new this.#domException(\n 'Cross-document tool discovery requires native WebMCP',\n 'NotSupportedError'\n );\n }\n const tools = [...this.#tools.values()]\n .map((tool) => {\n // A fresh object per call, like Blink parsing its serialized copy\n // (webmcp#241). A custom toJSON can serialize to non-object JSON; omit\n // those rather than emit a value consumers would mistake for a pre-154\n // serialized string.\n const serialized = tool[REGISTERED_INPUT_SCHEMA_SYMBOL];\n const parsed: unknown = serialized === undefined ? undefined : JSON.parse(serialized);\n return {\n name: tool.name,\n title: tool.title ?? '',\n description: tool.description,\n ...(isPlainObject(parsed) ? { inputSchema: parsed } : {}),\n origin: currentOrigin(),\n window: globalThis.window,\n ...(tool.annotations ? { annotations: toWebMcpAnnotations(tool.annotations) } : {}),\n };\n })\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n await new Promise((resolve) => setTimeout(resolve, 0));\n return tools;\n }\n\n async executeTool(\n tool: RegisteredTool,\n inputArgsJson: string,\n options: ChromeModelContextExecuteToolOptions = {}\n ): Promise<string | null> {\n validateWebMcpAccess(this.#ownerDocument);\n if (tool === null || typeof tool !== 'object') {\n throw new TypeError('RegisteredTool must be an object');\n }\n for (const required of ['name', 'description', 'window', 'origin'] as const) {\n if (!(required in tool)) {\n throw new TypeError(`RegisteredTool.${required} is required`);\n }\n }\n validateExecutableOrigin(tool.origin);\n if (tool.window !== globalThis.window || tool.origin !== currentOrigin()) {\n throw createUnknownError(`Tool not found: ${tool.name}`);\n }\n return this.#invokeToolByName(tool.name, inputArgsJson, options);\n }\n\n // Everything below is non-standard. `ModelContext.prototype` must expose only\n // the WebIDL members above, so the polyfill's own plumbing is either #private\n // (which gets no prototype slot at all) or static. The statics hang off this\n // module-private class binding, not off the exposed `ModelContext` interface\n // object, so no page script can reach them.\n\n /** @internal Used by initializeWebMCPPolyfill */\n static getTestingShim(context: StrictWebMCPContext): PolyfillTestingShim {\n context.#testingShim ??= new PolyfillTestingShim(context);\n return context.#testingShim;\n }\n\n /** @internal Used by PolyfillTestingShim */\n static getToolInfos(context: StrictWebMCPContext): ModelContextTestingToolInfo[] {\n return [...context.#tools.values()].map((tool) => ({\n name: tool.name,\n description: tool.description,\n // Pinned to the string: the removed modelContextTesting surface predates\n // webmcp#241.\n ...(tool[REGISTERED_INPUT_SCHEMA_SYMBOL] === undefined\n ? {}\n : { inputSchema: tool[REGISTERED_INPUT_SCHEMA_SYMBOL] }),\n }));\n }\n\n /** @internal Used by PolyfillTestingShim */\n static executeToolForTesting(\n context: StrictWebMCPContext,\n toolName: string,\n inputArgsJson: string,\n options?: ChromeModelContextExecuteToolOptions\n ): Promise<string | null> {\n validateWebMcpAccess(context.#ownerDocument);\n return context.#invokeToolByName(toolName, inputArgsJson, options);\n }\n\n /** @internal Used by cleanupWebMCPPolyfill */\n static dispose(context: StrictWebMCPContext): void {\n for (const name of context.#tools.keys()) context.#removeTool(name);\n context.ontoolchange = null;\n context.#testingShim?.dispose();\n }\n\n #removeTool(name: string, expected?: PolyfillToolDescriptor): boolean {\n const registered = this.#tools.get(name);\n if (!registered || (expected && registered !== expected)) return false;\n const signal = registered[REGISTRATION_SIGNAL_SYMBOL];\n const abort = registered[REGISTRATION_ABORT_SYMBOL];\n if (signal && abort) signal.removeEventListener('abort', abort);\n return this.#tools.delete(name);\n }\n\n async #invokeToolByName(\n toolName: string,\n inputArgsJson: string,\n options: ChromeModelContextExecuteToolOptions | undefined\n ): Promise<string | null> {\n options?.signal?.throwIfAborted();\n\n const tool = this.#tools.get(toolName);\n if (!tool) {\n throw createUnknownError(`Tool not found: ${toolName}`);\n }\n\n const args = parseChromeToolInput(inputArgsJson);\n options?.signal?.throwIfAborted();\n if (tool[REGISTRATION_SIGNAL_SYMBOL]?.aborted) throw createUnknownError('Tool unregistered');\n\n let rawResult: unknown;\n try {\n const registrationSignal = tool[REGISTRATION_SIGNAL_SYMBOL];\n const execution = withAbortSignal(\n Promise.resolve(tool.execute(args)),\n registrationSignal,\n () => createUnknownError('Tool unregistered')\n );\n rawResult = await withAbortSignal(execution, options?.signal);\n } catch (error) {\n if (options?.signal?.aborted && error === options.signal.reason) throw error;\n if (tool[REGISTRATION_SIGNAL_SYMBOL]?.aborted) throw error;\n throw createToolInvocationFailedError(error);\n }\n\n return serializeChromeToolResult(rawResult);\n }\n\n async #notifyToolsChanged(): Promise<void> {\n // ponytail: the platform does not expose its WebMCP task source; a timer\n // preserves task (rather than microtask) ordering for local registrations.\n await new Promise((resolve) => setTimeout(resolve, 0));\n this.dispatchEvent(new Event('toolchange'));\n this.#testingShim?.dispatchToolChange();\n }\n}\n\n// A function *expression*, not a method shorthand: WebIDL interface objects must\n// pass the IsConstructor check, and method shorthands have no [[Construct]].\nconst modelContextConstructor = function ModelContext(): never {\n throw new TypeError('Illegal constructor');\n};\n\n// Pinned explicitly: minifiers rename function expressions, and WebIDL requires\n// the interface object's `name` to be the interface identifier.\nObject.defineProperty(modelContextConstructor, 'name', { value: 'ModelContext' });\nObject.defineProperty(modelContextConstructor, 'prototype', {\n value: StrictWebMCPContext.prototype,\n writable: false,\n});\n// WebIDL: an interface object's [[Prototype]] is the inherited interface's\n// interface object. `interface ModelContext : EventTarget` therefore requires\n// Object.getPrototypeOf(ModelContext) === EventTarget, not Function.prototype.\nObject.setPrototypeOf(modelContextConstructor, EventTarget);\nObject.defineProperty(StrictWebMCPContext.prototype, 'constructor', {\n configurable: true,\n writable: true,\n value: modelContextConstructor,\n});\nObject.defineProperty(StrictWebMCPContext.prototype, Symbol.toStringTag, {\n configurable: true,\n value: 'ModelContext',\n});\n\n// WebIDL members are enumerable on the interface prototype object; ECMAScript\n// class members are not. `executeTool` is a Chrome extension, not spec IDL.\nfor (const member of ['registerTool', 'getTools', 'executeTool', 'ontoolchange'] as const) {\n const descriptor = Object.getOwnPropertyDescriptor(StrictWebMCPContext.prototype, member);\n if (descriptor) {\n Object.defineProperty(StrictWebMCPContext.prototype, member, {\n ...descriptor,\n enumerable: true,\n });\n }\n}\n\n/**\n * EventTarget-based testing shim matching the native Chromium ModelContextTesting surface.\n *\n * Fires `toolchange` events and supports the `ontoolchange` handler property.\n */\nclass PolyfillTestingShim extends EventTarget implements ModelContextTesting {\n private _ontoolchange: ((this: ModelContextTesting, ev: Event) => unknown) | null = null;\n private readonly ontoolchangeListener: EventListener = (event) => {\n this._ontoolchange?.call(this, event);\n };\n\n readonly #context: StrictWebMCPContext;\n\n constructor(context: StrictWebMCPContext) {\n super();\n this.#context = context;\n }\n\n listTools(): ModelContextTestingToolInfo[] {\n return StrictWebMCPContext.getToolInfos(this.#context);\n }\n\n executeTool(\n toolName: string,\n inputArgsJson: string,\n options?: ChromeModelContextExecuteToolOptions\n ): Promise<string | null> {\n return StrictWebMCPContext.executeToolForTesting(\n this.#context,\n toolName,\n inputArgsJson,\n options\n );\n }\n\n get ontoolchange(): ((this: ModelContextTesting, ev: Event) => unknown) | null {\n return this._ontoolchange;\n }\n\n set ontoolchange(handler: ((this: ModelContextTesting, ev: Event) => unknown) | null) {\n const listener = typeof handler === 'function' ? handler : null;\n if (listener === null) {\n this._ontoolchange = null;\n super.removeEventListener('toolchange', this.ontoolchangeListener);\n return;\n }\n\n if (this._ontoolchange === null) {\n super.addEventListener('toolchange', this.ontoolchangeListener);\n }\n this._ontoolchange = listener;\n }\n\n /** @internal Called by StrictWebMCPContext when tools change. */\n dispatchToolChange(): void {\n this.dispatchEvent(new Event('toolchange'));\n }\n\n dispose(): void {\n this.ontoolchange = null;\n }\n}\n\nfunction normalizeToolDescriptor<TArgs extends WebMcpToolInput>(\n tool: ModelContextTool<TArgs>,\n existing: Map<string, PolyfillToolDescriptor>\n): PolyfillToolDescriptor {\n if (!tool || typeof tool !== 'object') {\n throw new TypeError('registerTool(tool) requires a tool object');\n }\n\n const coerced = coerceWebMcpToolDescriptor(tool);\n\n validateWebMcpToolDescriptor(coerced);\n\n if (existing.has(coerced.name)) {\n throw createInvalidStateError(`Tool already registered: ${coerced.name}`);\n }\n\n const registeredInputSchema =\n coerced.inputSchema === undefined ? undefined : serializeInputSchema(coerced.inputSchema);\n\n return {\n name: coerced.name,\n ...(coerced.title === undefined ? {} : { title: coerced.title }),\n description: coerced.description,\n ...(coerced.inputSchema === undefined ? {} : { inputSchema: coerced.inputSchema }),\n ...(coerced.annotations === undefined ? {} : { annotations: coerced.annotations }),\n execute: (input) => Reflect.apply(coerced.execute, undefined, [input]),\n ...(registeredInputSchema !== undefined\n ? { [REGISTERED_INPUT_SCHEMA_SYMBOL]: registeredInputSchema }\n : {}),\n };\n}\n\nlet navigatorModelContextDeprecationWarned = false;\n\n/**\n * Backing store for the `Document.prototype.modelContext` getter.\n *\n * WebIDL puts `[SameObject] readonly attribute ModelContext modelContext` on\n * the Document *interface prototype object*, not on the document instance, and\n * Chrome matches that. One shared accessor therefore needs somewhere to keep\n * the per-document value, and keying it by document is what makes repeated\n * reads return the identical object, as `[SameObject]` requires.\n */\nconst documentModelContexts = new WeakMap<Document, ModelContext>();\n\n// A method shorthand, so it has no `prototype` and is not constructable, like a\n// native getter. `name` is pinned because Chrome reports \"get modelContext\" and\n// minifiers rename otherwise.\nconst { modelContext: documentModelContextGetter } = {\n modelContext(this: Document): ModelContext | undefined {\n // WebIDL brand check: the getter is only callable on a Document.\n // Document.prototype is not one, so reading it throws, as Chrome does.\n if (!(this instanceof Document)) {\n throw new TypeError('Illegal invocation');\n }\n return documentModelContexts.get(this);\n },\n};\nObject.defineProperty(documentModelContextGetter, 'name', { value: 'get modelContext' });\n\nfunction defineDocumentModelContext(target: Document, value: ModelContext): void {\n documentModelContexts.set(target, value);\n if (Object.hasOwn(Document.prototype, 'modelContext')) return;\n installProperty(Document.prototype, 'modelContext', {\n configurable: true,\n enumerable: true,\n get: documentModelContextGetter,\n });\n}\n\n// Per webmachinelearning/webmcp#173 / PR #184, the modelContext getter moved\n// from Navigator to Document. We install on document.modelContext as the\n// primary surface and expose navigator.modelContext as a deprecated alias that\n// returns the same instance and logs a one-time console warning on first\n// access. This mirrors the deprecation behavior shipped in Chrome 150.\nfunction defineDeprecatedNavigatorModelContext(target: Navigator, value: ModelContext): void {\n installProperty(target, 'modelContext', {\n configurable: true,\n enumerable: true,\n get() {\n if (!navigatorModelContextDeprecationWarned) {\n navigatorModelContextDeprecationWarned = true;\n console.warn(\n '[WebMCPPolyfill] navigator.modelContext is deprecated. The May 27, 2026 WebMCP draft moved the modelContext getter from Navigator to Document — use document.modelContext instead. See https://github.com/webmachinelearning/webmcp/pull/184.'\n );\n }\n return value;\n },\n });\n}\n\nfunction installSubmitEventPolyfill(): void {\n const prototype = SubmitEvent.prototype;\n if (!('agentInvoked' in prototype)) {\n installProperty(prototype, 'agentInvoked', {\n configurable: true,\n enumerable: true,\n get(this: SubmitEvent) {\n return isAgentInvokedSubmitEvent(this);\n },\n });\n }\n if (!('respondWith' in prototype)) {\n installProperty(prototype, 'respondWith', {\n configurable: true,\n enumerable: true,\n writable: true,\n value(this: SubmitEvent, agentResponse: Promise<unknown>) {\n respondWithAgentSubmitEvent(this, agentResponse);\n },\n });\n }\n}\n\nexport function initializeWebMCPPolyfill(options?: WebMCPPolyfillInitOptions): void {\n if (globalThis.isSecureContext === false) return;\n const nav = typeof navigator === 'undefined' ? null : navigator;\n const doc = typeof document === 'undefined' ? null : document;\n if (!nav || !doc || typeof window === 'undefined') return;\n\n if (doc.modelContext) return;\n\n const navigatorModelContext = nav.modelContext;\n\n if (installedProperties.length > 0) {\n cleanupWebMCPPolyfill();\n }\n\n if (navigatorModelContext) {\n defineDocumentModelContext(doc, navigatorModelContext);\n return;\n }\n\n const previousDescriptor = Object.getOwnPropertyDescriptor(window, 'ModelContext');\n if (previousDescriptor && !previousDescriptor.configurable) {\n if (!Object.is(Reflect.get(window, 'ModelContext'), modelContextConstructor)) {\n throw new TypeError('Cannot install ModelContext over a non-configurable global');\n }\n } else {\n installProperty(window, 'ModelContext', {\n configurable: true,\n enumerable: false,\n writable: true,\n value: modelContextConstructor,\n });\n }\n\n const context = new StrictWebMCPContext(doc);\n installedContext = context;\n\n defineDocumentModelContext(doc, context);\n\n // Reset the one-shot warning flag so a fresh install warns again on first access.\n navigatorModelContextDeprecationWarned = false;\n defineDeprecatedNavigatorModelContext(nav, context);\n installSubmitEventPolyfill();\n\n if (options?.installTestingShim && !nav.modelContextTesting) {\n installProperty(nav, 'modelContextTesting', {\n configurable: true,\n enumerable: true,\n writable: false,\n value: StrictWebMCPContext.getTestingShim(context),\n });\n }\n\n cleanupDeclarativeForms = installDeclarativeForms(doc, context);\n}\n\nexport function cleanupWebMCPPolyfill(): void {\n cleanupDeclarativeForms?.();\n cleanupDeclarativeForms = null;\n if (installedContext) StrictWebMCPContext.dispose(installedContext);\n installedContext = null;\n for (const { target, key, previous } of [...installedProperties].reverse()) {\n if (previous) Object.defineProperty(target, key, previous);\n else Reflect.deleteProperty(target, key);\n }\n installedProperties.length = 0;\n navigatorModelContextDeprecationWarned = false;\n}\n"],"mappings":";;;AA0BA,MAAM,qCAAqB,IAAI,SAAsB;AACrD,MAAM,iCAAiB,IAAI,SAAwC;AACnE,MAAM,oCAAoB,IAAI,SAA4C;AAE1E,SAAgB,0BAA0B,OAA6B;CACrE,OACE,MAAM,cACL,mBAAmB,IAAI,MAAM,IAC3B,MAAM,eAAe,MAAM,QAC1B,MAAM,kBAAkB,mBACxB,kBAAk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mB;CACnB,KAAK,MAAM,EAAE,QAAQ,KAAK,cAAc,CAAC,GAAG,oBAAoB,CAAC,SAAS,EACxE,IAAI,UAAU,OAAO,eAAe,QAAQ,KAAK,SAAS;MACrD,QAAQ,eAAe,QAAQ,IAAI;CAE1C,oBAAoB,SAAS;CAC7B,yCAAyC"}
|
package/dist/schema.d.ts
CHANGED
|
@@ -1,21 +1,31 @@
|
|
|
1
|
-
import { InputSchema,
|
|
2
|
-
import { StandardJSONSchemaV1
|
|
1
|
+
import { CallToolResult, InputSchema, ToolDescriptor, WebMcpToolAnnotations, WebMcpToolInput } from "@mcp-b/webmcp-types";
|
|
2
|
+
import { StandardJSONSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
|
|
4
4
|
//#region src/schema.d.ts
|
|
5
|
-
type
|
|
6
|
-
type
|
|
7
|
-
type ToolInputSchema = InputSchema | StandardInputValidatorSchema | StandardInputJsonSchema;
|
|
8
|
-
type ToolOutputSchema = InputSchema | StandardInputJsonSchema;
|
|
9
|
-
type StandardValidationResult = Awaited<ReturnType<StandardInputValidatorSchema['~standard']['validate']>>;
|
|
10
|
-
type StandardValidationIssue = NonNullable<StandardValidationResult['issues']>[number];
|
|
5
|
+
type StandardInputJsonSchema = StandardJSONSchemaV1<WebMcpToolInput, WebMcpToolInput>;
|
|
6
|
+
type ToolInputSchema = InputSchema | StandardInputJsonSchema;
|
|
11
7
|
interface NormalizedInputSchema {
|
|
12
8
|
inputSchema: InputSchema;
|
|
13
|
-
|
|
9
|
+
registeredInputSchema?: string;
|
|
14
10
|
}
|
|
15
11
|
declare function isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
16
|
-
declare function
|
|
12
|
+
declare function coerceWebMcpToolDescriptor<TArgs extends WebMcpToolInput>(tool: ToolDescriptor<TArgs>): ToolDescriptor<TArgs>;
|
|
13
|
+
declare function coerceWebMcpToolDescriptor(tool: Record<string, unknown>): ToolDescriptor<WebMcpToolInput>;
|
|
14
|
+
declare function normalizeToolResponse(value: unknown): CallToolResult;
|
|
15
|
+
declare function createUnknownError(message: string): Error;
|
|
16
|
+
declare function createToolInvocationFailedError(error: unknown): Error;
|
|
17
|
+
declare function createInvalidStateError(message: string): Error;
|
|
18
|
+
declare function validateWebMcpToolDescriptor<TArgs extends WebMcpToolInput>(tool: ToolDescriptor<TArgs>): void;
|
|
19
|
+
declare function toWebMcpAnnotations(annotations: WebMcpToolAnnotations): WebMcpToolAnnotations;
|
|
20
|
+
declare function parseChromeToolInput(input: string): WebMcpToolInput;
|
|
21
|
+
declare function serializeChromeToolResult(value: unknown): string;
|
|
22
|
+
declare function withAbortSignal<T>(operation: Promise<T>, signal?: AbortSignal, getAbortReason?: () => unknown): Promise<T>;
|
|
23
|
+
declare function validatePotentiallyTrustworthyOrigins(origins: readonly string[] | undefined): void;
|
|
24
|
+
declare function validateWebMcpAccess(ownerDocument: Document | null): void;
|
|
25
|
+
declare function validateOriginAgentCluster(): void;
|
|
26
|
+
declare function validateExecutableOrigin(origin: unknown): void;
|
|
17
27
|
declare function normalizeInputSchema(inputSchema: ToolInputSchema | undefined): NormalizedInputSchema;
|
|
18
|
-
declare function
|
|
28
|
+
declare function serializeInputSchema(schema: unknown): string;
|
|
19
29
|
//#endregion
|
|
20
|
-
export { NormalizedInputSchema,
|
|
30
|
+
export { NormalizedInputSchema, ToolInputSchema, coerceWebMcpToolDescriptor, createInvalidStateError, createToolInvocationFailedError, createUnknownError, isPlainObject, normalizeInputSchema, normalizeToolResponse, parseChromeToolInput, serializeChromeToolResult, serializeInputSchema, toWebMcpAnnotations, validateExecutableOrigin, validateOriginAgentCluster, validatePotentiallyTrustworthyOrigins, validateWebMcpAccess, validateWebMcpToolDescriptor, withAbortSignal };
|
|
21
31
|
//# sourceMappingURL=schema.d.ts.map
|