@mcp-b/webmcp-polyfill 2.3.2 → 3.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 CHANGED
@@ -1,21 +1,39 @@
1
1
  # @mcp-b/webmcp-polyfill
2
2
 
3
- Strict WebMCP core runtime polyfill for `navigator.modelContext`.
3
+ Strict WebMCP core runtime polyfill for `document.modelContext` (with a
4
+ backward-compatible `navigator.modelContext` alias).
5
+
6
+ > **Heads up — WebMCP spec migration.** The `modelContext` getter moved from
7
+ > `Navigator` to `Document` in
8
+ > [webmachinelearning/webmcp#184](https://github.com/webmachinelearning/webmcp/pull/184)
9
+ > and Chrome 150 deprecates `navigator.modelContext`. The polyfill installs on
10
+ > both surfaces today: `document.modelContext` is the canonical install
11
+ > location, and `navigator.modelContext` remains as a deprecated alias that
12
+ > resolves to the same instance and logs a one-time console warning on first
13
+ > access. Prefer `document.modelContext` for new code.
14
+
15
+ ```js
16
+ const modelContext = document.modelContext || navigator.modelContext;
17
+ if (modelContext) {
18
+ // Register tools…
19
+ }
20
+ ```
4
21
 
5
22
  `@mcp-b/webmcp-polyfill` installs only the strict core API:
6
23
 
7
24
  - `registerTool(tool, options?)` — pass `options.signal` (`AbortSignal`) to unregister when aborted
25
+ - `getTools()` — async Chromium producer-preview discovery API
26
+ - `executeTool(toolFromGetTools, inputArgsJson, options?)` — Chromium producer-preview execution API
8
27
  - `unregisterTool(nameOrTool)` (deprecated compatibility API)
9
- - `provideContext(options?)` (deprecated compatibility API)
10
- - `clearContext()` (deprecated compatibility API)
11
28
 
12
29
  It does not install MCP bridge extensions like `callTool`, resources, or prompts.
13
30
 
14
31
  Important:
15
32
 
16
- - `navigator.modelContext` in this package does not provide `listTools()` or `callTool(...)`.
33
+ - `document.modelContext` is the canonical install location. `navigator.modelContext` is kept as a backward-compatible alias that returns the same instance and logs a one-time deprecation warning on first access. The upstream WebMCP draft moved the getter from Navigator to Document on May 27, 2026 ([webmachinelearning/webmcp#184](https://github.com/webmachinelearning/webmcp/pull/184)) and Chrome 150 deprecates `navigator.modelContext`. The polyfill will remove the Navigator alias in the next major version.
34
+ - `document.modelContext` in this package does not provide `listTools()` or `callTool(...)`; producer discovery/execution uses `getTools()` and `executeTool(...)`.
17
35
  - For list/execute test flows, use `navigator.modelContextTesting` (when `installTestingShim` is enabled).
18
- - `provideContext()` and `clearContext()` still work for now, but the upstream WebMCP spec removed them on March 5, 2026. The polyfill logs a deprecation warning and will remove them in the next major version.
36
+ - `provideContext()` and `clearContext()` were removed from the upstream WebMCP spec on March 5, 2026 and are not exposed by this polyfill.
19
37
  - `unregisterTool(name)` was removed from the WebMCP draft on April 23, 2026 in favor of `AbortSignal`-driven unregistration. The polyfill keeps it functional with a one-time deprecation warning; it will be removed in the next major version.
20
38
 
21
39
  ## Type Safety First
@@ -30,11 +48,11 @@ Recommended setup:
30
48
 
31
49
  ## Package Selection
32
50
 
33
- | Package | Use When |
34
- | ------------------------ | ---------------------------------------------------------- |
35
- | `@mcp-b/webmcp-types` | You only need compile-time types (no runtime) |
36
- | `@mcp-b/webmcp-polyfill` | You need strict `navigator.modelContext` core runtime only |
37
- | `@mcp-b/global` | You want full MCPB runtime (core + bridge extensions) |
51
+ | Package | Use When |
52
+ | ------------------------ | --------------------------------------------------------- |
53
+ | `@mcp-b/webmcp-types` | You only need compile-time types (no runtime) |
54
+ | `@mcp-b/webmcp-polyfill` | You need strict `document.modelContext` core runtime only |
55
+ | `@mcp-b/global` | You want full MCPB runtime (core + bridge extensions) |
38
56
 
39
57
  ## Install
40
58
 
@@ -51,7 +69,7 @@ import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill';
51
69
 
52
70
  initializeWebMCPPolyfill();
53
71
 
54
- navigator.modelContext.registerTool({
72
+ document.modelContext.registerTool({
55
73
  name: 'get-page-title',
56
74
  description: 'Get the current page title',
57
75
  inputSchema: { type: 'object', properties: {} },
@@ -96,7 +114,7 @@ const inputSchema = {
96
114
  additionalProperties: false,
97
115
  } as const satisfies JsonSchemaForInference;
98
116
 
99
- navigator.modelContext.registerTool({
117
+ document.modelContext.registerTool({
100
118
  name: 'search',
101
119
  description: 'Search indexed docs',
102
120
  inputSchema,
@@ -119,7 +137,7 @@ Inference notes:
119
137
 
120
138
  ### `initializeWebMCPPolyfill(options?)`
121
139
 
122
- Installs the strict core polyfill on `navigator.modelContext`.
140
+ Installs the strict core polyfill on `document.modelContext` (canonical) and `navigator.modelContext` (deprecated alias to the same instance).
123
141
 
124
142
  | Option | Type | Default | Notes |
125
143
  | --------------------------------- | ------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------ |
@@ -130,7 +148,7 @@ Installs the strict core polyfill on `navigator.modelContext`.
130
148
  Behavior:
131
149
 
132
150
  - No-op in non-browser environments.
133
- - Non-destructive by default: if `navigator.modelContext` already exists, initialization is skipped.
151
+ - Non-destructive by default: if either `document.modelContext` or `navigator.modelContext` already exists (e.g. native Chromium support), initialization is skipped.
134
152
  - Safe to call repeatedly.
135
153
 
136
154
  ### `initializeWebModelContextPolyfill(options?)`
@@ -139,16 +157,10 @@ Alias of `initializeWebMCPPolyfill`.
139
157
 
140
158
  ### `cleanupWebMCPPolyfill()`
141
159
 
142
- Restores previous `navigator.modelContext` and `navigator.modelContextTesting` descriptors and resets polyfill install state.
160
+ Restores previous `document.modelContext`, `navigator.modelContext`, and `navigator.modelContextTesting` descriptors and resets polyfill install state.
143
161
 
144
162
  ## Strict Core Behavior
145
163
 
146
- ### `provideContext(options?)`
147
-
148
- - Deprecated compatibility API.
149
- - Replaces the active tool registry with `options.tools`.
150
- - Clears previously registered tools before applying new tools.
151
-
152
164
  ### `registerTool(tool, options?)`
153
165
 
154
166
  - Requires a non-empty `name`, non-empty `description`, and `execute` function.
@@ -180,15 +192,10 @@ ac.abort();
180
192
  - Unknown names are a no-op.
181
193
  - Logs a one-time deprecation warning. Prefer the `AbortSignal` form on `registerTool(tool, options)`.
182
194
 
183
- ### `clearContext()`
184
-
185
- - Deprecated compatibility API.
186
- - Removes all registered tools.
187
-
188
195
  ## Listing and Executing Tools
189
196
 
190
197
  In `@mcp-b/webmcp-polyfill`, listing and execution helpers are exposed on
191
- `navigator.modelContextTesting` (not `navigator.modelContext`) when the testing shim is enabled.
198
+ `navigator.modelContextTesting` (not `document.modelContext`) when the testing shim is enabled.
192
199
 
193
200
  ```ts
194
201
  import { initializeWebMCPPolyfill } from '@mcp-b/webmcp-polyfill';
@@ -205,7 +212,7 @@ void tools;
205
212
  void result;
206
213
  ```
207
214
 
208
- If you want `callTool(...)` / extension-style runtime methods on `navigator.modelContext`, use
215
+ If you want `callTool(...)` / extension-style runtime methods on `document.modelContext`, use
209
216
  `@mcp-b/global`.
210
217
 
211
218
  ## Input Schema Support
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;KA2BY,4BAAA,GAA+B,gBAAA,CACzC,MAAA,mBACA,MAAA;AAAA,UAEe,oBAAA,2BAA+C,KAAA;EAAA,SACrD,WAAA;IAAA,SACE,OAAA;IAAA,SACA,MAAA;IAAA,SACA,KAAA;MAAA,SAAmB,KAAA,EAAO,KAAA;MAAA,SAAgB,MAAA,EAAQ,MAAA;IAAA;IAAA,SAClD,UAAA;MAAA,SACE,KAAA,GAAQ,OAAA;QAAA,SACN,MAAA;QAAA,SACA,cAAA,GAAiB,MAAA;MAAA,MACtB,MAAA;MAAA,SACG,MAAA,GAAS,OAAA;QAAA,SACP,MAAA;QAAA,SACA,cAAA,GAAiB,MAAA;MAAA,MACtB,MAAA;IAAA;EAAA;AAAA;AAAA,KAIA,uBAAA,GAA0B,oBAAA,CACpC,MAAA,mBACA,MAAA;AAAA,KAEU,eAAA,GAAkB,WAAA,GAAc,4BAAA,GAA+B,uBAAA;AAAA,KAC/D,gBAAA,GAAmB,WAAA,GAAc,uBAAA;AAAA,KAExC,wBAAA,GAA2B,OAAA,CAC9B,UAAA,CAAW,4BAAA;AAAA,KAER,uBAAA,G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;;;;EAqEpC,cAAA;EAjEW;;;;;;;EA0EX,kBAAA;EAtEe;;;EA2Ef,+BAAA;AAAA;AAAA,iBA2Sc,aAAA,CAAc,KAAA,YAAiB,KAAA,IAAS,MAAA;AAAA,iBAmRxC,sBAAA,CACd,IAAA,EAAM,MAAA,mBACN,MAAA,EAAQ,WAAA,GACP,uBAAA;AAAA,iBA8Qa,wBAAA,CAAyB,OAAA,GAAU,yBAAA;AAAA,iBAoFnC,qBAAA,CAAA;AAAA,QA+CR,MAAA;EAAA,UACI,MAAA;IACR,uBAAA,GAA0B,yBAAA;EAAA;AAAA"}
@@ -1,2 +1,2 @@
1
- var WebMCPPolyfill=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e,n){let r=typeof e;if(r!==typeof n)return!1;if(Array.isArray(e)){if(!Array.isArray(n))return!1;let r=e.length;if(r!==n.length)return!1;for(let i=0;i<r;i++)if(!t(e[i],n[i]))return!1;return!0}if(r===`object`){if(!e||!n)return e===n;let r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;for(let i of r)if(!t(e[i],n[i]))return!1;return!0}return e===n}function n(e){return encodeURI(r(e))}function r(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}let i={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},a={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},o={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},s=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function c(e,t=Object.create(null),r=s,l=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let n=e.$id||e.id;if(n){let i=new URL(n,r.href);i.hash.length>1?t[i.href]=e:(i.hash=``,l===``?r=i:c(e,t,r))}}else if(e!==!0&&e!==!1)return t;let u=r.href+(l?`#`+l:``);if(t[u]!==void 0)throw Error(`Duplicate schema URI "${u}".`);if(t[u]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,`__absolute_uri__`,{enumerable:!1,value:u}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}if(e.$anchor){let n=new URL(`#`+e.$anchor,r.href);t[n.href]=e}for(let s in e){if(o[s])continue;let u=`${l}/${n(s)}`,d=e[s];if(Array.isArray(d)){if(i[s]){let e=d.length;for(let n=0;n<e;n++)c(d[n],t,r,`${u}/${n}`)}}else if(a[s])for(let e in d)c(d[e],t,r,`${u}/${n(e)}`);else c(d,t,r,u)}return t}let l=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,u=[0,31,28,31,30,31,30,31,31,30,31,30,31],d=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,f=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,p=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){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%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,ee=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,h=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,g=/^(?:\/(?:[^~/]|~0|~1)*)*$/,_=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,v=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,te=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},ne=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,y=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,b=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function x(e){return e.test.bind(e)}let re={date:S,time:C.bind(void 0,!1),"date-time":T,duration:b,uri:oe,"uri-reference":x(p),"uri-template":x(m),url:x(ee),email:te,hostname:x(f),ipv4:x(ne),ipv6:x(y),regex:O,uuid:x(h),"json-pointer":x(g),"json-pointer-uri-fragment":x(_),"relative-json-pointer":x(v)};function ie(e){return e%4==0&&(e%100!=0||e%400==0)}function S(e){let t=e.match(l);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&ie(n)?29:u[r])}function C(e,t){let n=t.match(d);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}let w=/t|\s/i;function T(e){let t=e.split(w);return t.length==2&&S(t[0])&&C(!0,t[1])}let E=/\/|:/,ae=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function oe(e){return E.test(e)&&ae.test(e)}let D=/[^\\]\\Z/;function O(e){if(D.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function se(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function k(e,r,i=`2019-09`,a=c(r),o=!0,s=null,l=`#`,u=`#`,d=Object.create(null)){if(r===!0)return{valid:!0,errors:[]};if(r===!1)return{valid:!1,errors:[{instanceLocation:l,keyword:`false`,keywordLocation:l,error:`False boolean schema.`}]};let f=typeof e,p;switch(f){case`boolean`:case`number`:case`string`:p=f;break;case`object`:p=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${f}" type are not supported.`)}let{$ref:m,$recursiveRef:ee,$recursiveAnchor:h,type:g,const:_,enum:v,required:te,not:ne,anyOf:y,allOf:b,oneOf:x,if:ie,then:S,else:C,format:w,properties:T,patternProperties:E,additionalProperties:ae,unevaluatedProperties:oe,minProperties:D,maxProperties:O,propertyNames:ce,dependentRequired:A,dependentSchemas:j,dependencies:M,prefixItems:N,items:P,additionalItems:F,unevaluatedItems:I,contains:le,minContains:L,maxContains:R,minItems:z,maxItems:B,uniqueItems:V,minimum:H,maximum:U,exclusiveMinimum:W,exclusiveMaximum:G,multipleOf:K,minLength:q,maxLength:J,pattern:Y,__absolute_ref__:X,__absolute_recursive_ref__:Z}=r,Q=[];if(h===!0&&s===null&&(s=r),ee===`#`){let t=s===null?a[Z]:s,n=`${u}/$recursiveRef`,c=k(e,s===null?r:s,i,a,o,t,l,n,d);c.valid||Q.push({instanceLocation:l,keyword:`$recursiveRef`,keywordLocation:n,error:`A subschema had errors.`},...c.errors)}if(m!==void 0){let t=a[X||m];if(t===void 0){let e=`Unresolved $ref "${m}".`;throw X&&X!==m&&(e+=` Absolute URI "${X}".`),e+=`\nKnown schemas:\n- ${Object.keys(a).join(`
2
- - `)}`,Error(e)}let n=`${u}/$ref`,r=k(e,t,i,a,o,s,l,n,d);if(r.valid||Q.push({instanceLocation:l,keyword:`$ref`,keywordLocation:n,error:`A subschema had errors.`},...r.errors),i===`4`||i===`7`)return{valid:Q.length===0,errors:Q}}if(Array.isArray(g)){let t=g.length,n=!1;for(let r=0;r<t;r++)if(p===g[r]||g[r]===`integer`&&p===`number`&&e%1==0&&e===e){n=!0;break}n||Q.push({instanceLocation:l,keyword:`type`,keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${g.join(`", "`)}".`})}else g===`integer`?(p!==`number`||e%1||e!==e)&&Q.push({instanceLocation:l,keyword:`type`,keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${g}".`}):g!==void 0&&p!==g&&Q.push({instanceLocation:l,keyword:`type`,keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${g}".`});if(_!==void 0&&(p===`object`||p===`array`?t(e,_)||Q.push({instanceLocation:l,keyword:`const`,keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(_)}.`}):e!==_&&Q.push({instanceLocation:l,keyword:`const`,keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(_)}.`})),v!==void 0&&(p===`object`||p===`array`?v.some(n=>t(e,n))||Q.push({instanceLocation:l,keyword:`enum`,keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(t=>e===t)||Q.push({instanceLocation:l,keyword:`enum`,keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),ne!==void 0){let t=`${u}/not`;k(e,ne,i,a,o,s,l,t).valid&&Q.push({instanceLocation:l,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let $=[];if(y!==void 0){let t=`${u}/anyOf`,n=Q.length,r=!1;for(let n=0;n<y.length;n++){let c=y[n],u=Object.create(d),f=k(e,c,i,a,o,h===!0?s:null,l,`${t}/${n}`,u);Q.push(...f.errors),r||=f.valid,f.valid&&$.push(u)}r?Q.length=n:Q.splice(n,0,{instanceLocation:l,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${u}/allOf`,n=Q.length,r=!0;for(let n=0;n<b.length;n++){let c=b[n],u=Object.create(d),f=k(e,c,i,a,o,h===!0?s:null,l,`${t}/${n}`,u);Q.push(...f.errors),r&&=f.valid,f.valid&&$.push(u)}r?Q.length=n:Q.splice(n,0,{instanceLocation:l,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${u}/oneOf`,n=Q.length,r=x.filter((n,r)=>{let c=Object.create(d),u=k(e,n,i,a,o,h===!0?s:null,l,`${t}/${r}`,c);return Q.push(...u.errors),u.valid&&$.push(c),u.valid}).length;r===1?Q.length=n:Q.splice(n,0,{instanceLocation:l,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${r} matches).`})}if((p===`object`||p===`array`)&&Object.assign(d,...$),ie!==void 0){let t=`${u}/if`;if(k(e,ie,i,a,o,s,l,t,d).valid){if(S!==void 0){let n=k(e,S,i,a,o,s,l,`${u}/then`,d);n.valid||Q.push({instanceLocation:l,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...n.errors)}}else if(C!==void 0){let n=k(e,C,i,a,o,s,l,`${u}/else`,d);n.valid||Q.push({instanceLocation:l,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...n.errors)}}if(p===`object`){if(te!==void 0)for(let t of te)t in e||Q.push({instanceLocation:l,keyword:`required`,keywordLocation:`${u}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(D!==void 0&&t.length<D&&Q.push({instanceLocation:l,keyword:`minProperties`,keywordLocation:`${u}/minProperties`,error:`Instance does not have at least ${D} properties.`}),O!==void 0&&t.length>O&&Q.push({instanceLocation:l,keyword:`maxProperties`,keywordLocation:`${u}/maxProperties`,error:`Instance does not have at least ${O} properties.`}),ce!==void 0){let t=`${u}/propertyNames`;for(let r in e){let e=`${l}/${n(r)}`,c=k(r,ce,i,a,o,s,e,t);c.valid||Q.push({instanceLocation:l,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${r}" does not match schema.`},...c.errors)}}if(A!==void 0){let t=`${u}/dependantRequired`;for(let n in A)if(n in e){let r=A[n];for(let i of r)i in e||Q.push({instanceLocation:l,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(j!==void 0)for(let t in j){let r=`${u}/dependentSchemas`;if(t in e){let c=k(e,j[t],i,a,o,s,l,`${r}/${n(t)}`,d);c.valid||Q.push({instanceLocation:l,keyword:`dependentSchemas`,keywordLocation:r,error:`Instance has "${t}" but does not match dependant schema.`},...c.errors)}}if(M!==void 0){let t=`${u}/dependencies`;for(let r in M)if(r in e){let c=M[r];if(Array.isArray(c))for(let n of c)n in e||Q.push({instanceLocation:l,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${r}" but does not have "${n}".`});else{let u=k(e,c,i,a,o,s,l,`${t}/${n(r)}`);u.valid||Q.push({instanceLocation:l,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${r}" but does not match dependant schema.`},...u.errors)}}}let r=Object.create(null),c=!1;if(T!==void 0){let t=`${u}/properties`;for(let u in T){if(!(u in e))continue;let f=`${l}/${n(u)}`,p=k(e[u],T[u],i,a,o,s,f,`${t}/${n(u)}`);if(p.valid)d[u]=r[u]=!0;else if(c=o,Q.push({instanceLocation:l,keyword:`properties`,keywordLocation:t,error:`Property "${u}" does not match schema.`},...p.errors),c)break}}if(!c&&E!==void 0){let t=`${u}/patternProperties`;for(let u in E){let f=new RegExp(u,`u`),p=E[u];for(let m in e){if(!f.test(m))continue;let ee=`${l}/${n(m)}`,h=k(e[m],p,i,a,o,s,ee,`${t}/${n(u)}`);h.valid?d[m]=r[m]=!0:(c=o,Q.push({instanceLocation:l,keyword:`patternProperties`,keywordLocation:t,error:`Property "${m}" matches pattern "${u}" but does not match associated schema.`},...h.errors))}}}if(!c&&ae!==void 0){let t=`${u}/additionalProperties`;for(let u in e){if(r[u])continue;let f=`${l}/${n(u)}`,p=k(e[u],ae,i,a,o,s,f,t);p.valid?d[u]=!0:(c=o,Q.push({instanceLocation:l,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${u}" does not match additional properties schema.`},...p.errors))}}else if(!c&&oe!==void 0){let t=`${u}/unevaluatedProperties`;for(let r in e)if(!d[r]){let c=`${l}/${n(r)}`,u=k(e[r],oe,i,a,o,s,c,t);u.valid?d[r]=!0:Q.push({instanceLocation:l,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${r}" does not match unevaluated properties schema.`},...u.errors)}}}else if(p===`array`){B!==void 0&&e.length>B&&Q.push({instanceLocation:l,keyword:`maxItems`,keywordLocation:`${u}/maxItems`,error:`Array has too many items (${e.length} > ${B}).`}),z!==void 0&&e.length<z&&Q.push({instanceLocation:l,keyword:`minItems`,keywordLocation:`${u}/minItems`,error:`Array has too few items (${e.length} < ${z}).`});let n=e.length,r=0,c=!1;if(N!==void 0){let t=`${u}/prefixItems`,f=Math.min(N.length,n);for(;r<f;r++){let n=k(e[r],N[r],i,a,o,s,`${l}/${r}`,`${t}/${r}`);if(d[r]=!0,!n.valid&&(c=o,Q.push({instanceLocation:l,keyword:`prefixItems`,keywordLocation:t,error:`Items did not match schema.`},...n.errors),c))break}}if(P!==void 0){let t=`${u}/items`;if(Array.isArray(P)){let u=Math.min(P.length,n);for(;r<u;r++){let n=k(e[r],P[r],i,a,o,s,`${l}/${r}`,`${t}/${r}`);if(d[r]=!0,!n.valid&&(c=o,Q.push({instanceLocation:l,keyword:`items`,keywordLocation:t,error:`Items did not match schema.`},...n.errors),c))break}}else for(;r<n;r++){let n=k(e[r],P,i,a,o,s,`${l}/${r}`,t);if(d[r]=!0,!n.valid&&(c=o,Q.push({instanceLocation:l,keyword:`items`,keywordLocation:t,error:`Items did not match schema.`},...n.errors),c))break}if(!c&&F!==void 0){let t=`${u}/additionalItems`;for(;r<n;r++){let n=k(e[r],F,i,a,o,s,`${l}/${r}`,t);d[r]=!0,n.valid||(c=o,Q.push({instanceLocation:l,keyword:`additionalItems`,keywordLocation:t,error:`Items did not match additional items schema.`},...n.errors))}}}if(le!==void 0)if(n===0&&L===void 0)Q.push({instanceLocation:l,keyword:`contains`,keywordLocation:`${u}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(L!==void 0&&n<L)Q.push({instanceLocation:l,keyword:`minContains`,keywordLocation:`${u}/minContains`,error:`Array has less items (${n}) than minContains (${L}).`});else{let t=`${u}/contains`,r=Q.length,c=0;for(let r=0;r<n;r++){let n=k(e[r],le,i,a,o,s,`${l}/${r}`,t);n.valid?(d[r]=!0,c++):Q.push(...n.errors)}c>=(L||0)&&(Q.length=r),L===void 0&&R===void 0&&c===0?Q.splice(r,0,{instanceLocation:l,keyword:`contains`,keywordLocation:t,error:`Array does not contain item matching schema.`}):L!==void 0&&c<L?Q.push({instanceLocation:l,keyword:`minContains`,keywordLocation:`${u}/minContains`,error:`Array must contain at least ${L} items matching schema. Only ${c} items were found.`}):R!==void 0&&c>R&&Q.push({instanceLocation:l,keyword:`maxContains`,keywordLocation:`${u}/maxContains`,error:`Array may contain at most ${R} items matching schema. ${c} items were found.`})}if(!c&&I!==void 0){let t=`${u}/unevaluatedItems`;for(;r<n;r++){if(d[r])continue;let n=k(e[r],I,i,a,o,s,`${l}/${r}`,t);d[r]=!0,n.valid||Q.push({instanceLocation:l,keyword:`unevaluatedItems`,keywordLocation:t,error:`Items did not match unevaluated items schema.`},...n.errors)}}if(V)for(let r=0;r<n;r++){let i=e[r],a=typeof i==`object`&&!!i;for(let o=0;o<n;o++){if(r===o)continue;let n=e[o];(i===n||a&&typeof n==`object`&&n&&t(i,n))&&(Q.push({instanceLocation:l,keyword:`uniqueItems`,keywordLocation:`${u}/uniqueItems`,error:`Duplicate items at indexes ${r} and ${o}.`}),r=2**53-1,o=2**53-1)}}}else if(p===`number`){if(i===`4`?(H!==void 0&&(W===!0&&e<=H||e<H)&&Q.push({instanceLocation:l,keyword:`minimum`,keywordLocation:`${u}/minimum`,error:`${e} is less than ${W?`or equal to `:``} ${H}.`}),U!==void 0&&(G===!0&&e>=U||e>U)&&Q.push({instanceLocation:l,keyword:`maximum`,keywordLocation:`${u}/maximum`,error:`${e} is greater than ${G?`or equal to `:``} ${U}.`})):(H!==void 0&&e<H&&Q.push({instanceLocation:l,keyword:`minimum`,keywordLocation:`${u}/minimum`,error:`${e} is less than ${H}.`}),U!==void 0&&e>U&&Q.push({instanceLocation:l,keyword:`maximum`,keywordLocation:`${u}/maximum`,error:`${e} is greater than ${U}.`}),W!==void 0&&e<=W&&Q.push({instanceLocation:l,keyword:`exclusiveMinimum`,keywordLocation:`${u}/exclusiveMinimum`,error:`${e} is less than ${W}.`}),G!==void 0&&e>=G&&Q.push({instanceLocation:l,keyword:`exclusiveMaximum`,keywordLocation:`${u}/exclusiveMaximum`,error:`${e} is greater than or equal to ${G}.`})),K!==void 0){let t=e%K;Math.abs(0-t)>=1.1920929e-7&&Math.abs(K-t)>=1.1920929e-7&&Q.push({instanceLocation:l,keyword:`multipleOf`,keywordLocation:`${u}/multipleOf`,error:`${e} is not a multiple of ${K}.`})}}else if(p===`string`){let t=q===void 0&&J===void 0?0:se(e);q!==void 0&&t<q&&Q.push({instanceLocation:l,keyword:`minLength`,keywordLocation:`${u}/minLength`,error:`String is too short (${t} < ${q}).`}),J!==void 0&&t>J&&Q.push({instanceLocation:l,keyword:`maxLength`,keywordLocation:`${u}/maxLength`,error:`String is too long (${t} > ${J}).`}),Y!==void 0&&!new RegExp(Y,`u`).test(e)&&Q.push({instanceLocation:l,keyword:`pattern`,keywordLocation:`${u}/pattern`,error:`String does not match pattern.`}),w!==void 0&&re[w]&&!re[w](e)&&Q.push({instanceLocation:l,keyword:`format`,keywordLocation:`${u}/format`,error:`String does not match format "${w}".`})}return{valid:Q.length===0,errors:Q}}var ce=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=c(e)}validate(e){return k(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),c(e,this.lookup)}};let A=`Failed to parse input arguments`,j=`Tool was executed but the invocation failed. For example, the script function threw an error`,M=`Tool was cancelled`,N={type:`object`,properties:{}},P=[`draft-2020-12`,`draft-07`],F=Symbol(`standardValidator`),I={installed:!1,previousModelContextDescriptor:void 0,previousModelContextTestingDescriptor:void 0};var le=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;provideContextDeprecationWarned=!1;clearContextDeprecationWarned=!1;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}provideContext(e={}){this.warnProvideContextDeprecationOnce();let t=new Map;for(let n of e.tools??[]){let e=X(n,t);t.set(e.name,e)}this.tools=t,this.notifyToolsChanged()}clearContext(){this.warnClearContextDeprecationOnce(),this.tools.clear(),this.notifyToolsChanged()}registerTool(e,t){let n=t?.signal;if(n?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${e?.name??`<unknown>`}") skipped: options.signal was already aborted.`);return}let r=X(e,this.tools);this.tools.set(r.name,r),this.notifyToolsChanged(),n&&n.addEventListener(`abort`,()=>{this.tools.delete(r.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let t=B(e);this.tools.delete(t)&&this.notifyToolsChanged()}getTools(){return this.getToolInfos()}getTestingShim(){return this.testingShim||=new L(this),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{let t;try{t=JSON.stringify(e.inputSchema??{type:`object`})}catch{t=`{"type":"object"}`}return{name:e.name,description:e.description,inputSchema:t}})}async executeToolForTesting(e,t,n){if(n?.signal?.aborted)throw R(M);let r=this.tools.get(e);if(!r)throw R(`Tool not found: ${e}`);let i=z(t),a=await ue(i,r);if(a)throw R(a);let o=!0,s={requestUserInteraction:async t=>{if(!o)throw Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof t!=`function`)throw TypeError(`requestUserInteraction(callback) requires a function callback`);return t()}};try{let e=r.execute(i,s);return ve(ge(await ye(Promise.resolve(e),n?.signal)))}catch(e){throw R(e instanceof Error?`${j}: ${e.message}`:j)}finally{o=!1}}notifyToolsChanged(){queueMicrotask(()=>{let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.testingShim?.dispatchToolChange()})}warnProvideContextDeprecationOnce(){this.provideContextDeprecationWarned||(this.provideContextDeprecationWarned=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext.provideContext() is deprecated and will be removed in the next major version. Register tools individually with registerTool() instead.`))}warnClearContextDeprecationOnce(){this.clearContextDeprecationWarned||(this.clearContextDeprecationWarned=!0,console.warn(`[WebMCPPolyfill] navigator.modelContext.clearContext() is deprecated and will be removed in the next major version. Unregister individual tools instead.`))}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn(`[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.`))}},L=class extends EventTarget{context;_ontoolchange=null;constructor(e){super(),this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,t,n){return this.context.executeToolForTesting(e,t,n)}getCrossDocumentScriptToolResult(){return Promise.resolve(`[]`)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!=`function`)throw TypeError(`Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.`);this.addEventListener(`toolchange`,e)}dispatchToolChange(){let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.dispatchEvent(new Event(`toolschanged`))}};function R(e){try{return new DOMException(e,`UnknownError`)}catch{let t=Error(e);return t.name=`UnknownError`,t}}function z(e){let t;try{t=JSON.parse(e)}catch{throw R(A)}if(!t||typeof t!=`object`||Array.isArray(t))throw R(A);return t}function B(e){if(typeof e==`string`)return e;if(V(e)&&typeof e.name==`string`)return e.name;throw TypeError(`Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.`)}function V(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function H(e){if(!V(e))return null;let t=e[`~standard`];return V(t)?t:null}function U(e){let t=H(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function W(e){let t=H(e);return!t||t.version!==1||!V(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function G(e){return{"~standard":{version:1,vendor:`@mcp-b/webmcp-polyfill-json-schema`,validate(t){if(!V(t))return{issues:[{message:`expected object arguments`}]};let n=Z(t,e);return n?{issues:[n]}:{value:t}}}}}function K(e){for(let t of P)try{let n=e[`~standard`].jsonSchema.input({target:t});return J(n),n}catch(e){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,e)}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function q(e){if(e===void 0){let e=N;return{inputSchema:e,standardValidator:G(e)}}if(W(e)){let t=K(e);return{inputSchema:t,standardValidator:G(t)}}if(U(e))return{inputSchema:N,standardValidator:e};if(J(e),Object.keys(e).length===0)return{inputSchema:N,standardValidator:G(N)};let t=e.type===void 0?{type:`object`,...e}:e;return{inputSchema:t,standardValidator:G(t)}}function J(e){if(!V(e))throw Error(`inputSchema must be a JSON Schema object`);Y(e,`$`)}function Y(e,t){let n=e.type;if(n!==void 0&&typeof n!=`string`&&!(Array.isArray(n)&&n.every(e=>typeof e==`string`&&e.length>0)))throw Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);let r=e.required;if(r!==void 0&&!(Array.isArray(r)&&r.every(e=>typeof e==`string`)))throw Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);let i=e.properties;if(i!==void 0){if(!V(i))throw Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[e,n]of Object.entries(i)){if(!V(n))throw Error(`Invalid JSON Schema at ${t}.properties.${e}: expected object schema`);Y(n,`${t}.properties.${e}`)}}let a=e.items;if(a!==void 0)if(Array.isArray(a))for(let[e,n]of a.entries()){if(!V(n))throw Error(`Invalid JSON Schema at ${t}.items[${e}]: expected object schema`);Y(n,`${t}.items[${e}]`)}else if(V(a))Y(a,`${t}.items`);else throw Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(let n of[`allOf`,`anyOf`,`oneOf`]){let r=e[n];if(r!==void 0){if(!Array.isArray(r))throw Error(`Invalid JSON Schema at ${t}: "${n}" must be an array`);for(let[e,i]of r.entries()){if(!V(i))throw Error(`Invalid JSON Schema at ${t}.${n}[${e}]: expected object schema`);Y(i,`${t}.${n}[${e}]`)}}}let o=e.not;if(o!==void 0){if(!V(o))throw Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);Y(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function X(e,t){if(!e||typeof e!=`object`)throw TypeError(`registerTool(tool) requires a tool object`);if(typeof e.name!=`string`||e.name.length===0)throw TypeError(`Tool "name" must be a non-empty string`);if(typeof e.description!=`string`||e.description.length===0)throw TypeError(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`);if(t.has(e.name))throw Error(`Tool already registered: ${e.name}`);let n=q(e.inputSchema),r=e.annotations,i=r?{...r,...r.readOnlyHint===`true`?{readOnlyHint:!0}:r.readOnlyHint===`false`?{readOnlyHint:!1}:{},...r.destructiveHint===`true`?{destructiveHint:!0}:r.destructiveHint===`false`?{destructiveHint:!1}:{},...r.idempotentHint===`true`?{idempotentHint:!0}:r.idempotentHint===`false`?{idempotentHint:!1}:{},...r.openWorldHint===`true`?{openWorldHint:!0}:r.openWorldHint===`false`?{openWorldHint:!1}:{}}:void 0;return{...e,...i?{annotations:i}:{},inputSchema:n.inputSchema,[F]:n.standardValidator}}function Z(e,t){let n=new ce(t,`2020-12`,!0).validate(e);if(n.valid)return null;let r=n.errors[n.errors.length-1];return r?{message:r.error}:{message:`Input validation failed`}}function Q(e){if(!e||e.length===0)return null;let t=e.map(e=>V(e)&&`key`in e?e.key:e).map(e=>String(e)).filter(e=>e.length>0);return t.length===0?null:t.join(`.`)}async function $(e,t){let n;try{n=await Promise.resolve(t[`~standard`].validate(e))}catch(e){let t=e instanceof Error?`: ${e.message}`:``;return console.error(`[WebMCPPolyfill] Standard Schema validation threw unexpectedly:`,e),`Input validation error: schema validation failed${t}`}if(!n.issues||n.issues.length===0)return null;let r=n.issues[0];if(!r)return`Input validation error`;let i=Q(r?.path);return i?`Input validation error: ${r.message} at ${i}`:`Input validation error: ${r.message}`}async function ue(e,t){return $(e,t[F])}function de(e){return V(e)&&Array.isArray(e.content)}function fe(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function pe(e){return fe(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>pe(e)):V(e)?Object.values(e).every(e=>pe(e)):!1}function me(e){if(!(!V(e)||!pe(e)))return e}function he(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function ge(e){if(de(e))return e;let t=me(e);return{content:[{type:`text`,text:he(e)}],...t?{structuredContent:t}:{},isError:!1}}function _e(e){for(let t of e.content??[])if(t.type===`text`&&`text`in t&&typeof t.text==`string`)return t.text;return null}function ve(e){if(e.isError)throw R(_e(e)?.replace(/^Error:\s*/i,``).trim()||j);let t=e.metadata;if(t&&typeof t==`object`&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw R(j)}}function ye(e,t){return t?t.aborted?Promise.reject(R(M)):new Promise((n,r)=>{let i=()=>{a(),r(R(M))},a=()=>{t.removeEventListener(`abort`,i)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}function be(){return typeof navigator<`u`?navigator:null}function xe(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function Se(e){let t=be();if(!t||t.modelContext)return;I.installed&&Ce();let n=new le,r=n;r.__isWebMCPPolyfill=!0,I.previousModelContextDescriptor=Object.getOwnPropertyDescriptor(t,`modelContext`),I.previousModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,`modelContextTesting`),xe(t,`modelContext`,r);let i=e?.installTestingShim??`if-missing`,a=!!t.modelContextTesting;(i===`always`||(i===!0||i===`if-missing`)&&!a)&&xe(t,`modelContextTesting`,n.getTestingShim()),I.installed=!0}function Ce(){let e=be();if(!e||!I.installed)return;let t=(t,n)=>{if(n){Object.defineProperty(e,t,n);return}delete e[t]};t(`modelContext`,I.previousModelContextDescriptor),t(`modelContextTesting`,I.previousModelContextTestingDescriptor),I.installed=!1,I.previousModelContextDescriptor=void 0,I.previousModelContextTestingDescriptor=void 0}if(typeof window<`u`&&typeof document<`u`){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{Se(e)}catch(e){console.error(`[WebMCPPolyfill] Auto-initialization failed:`,e)}}return e.cleanupWebMCPPolyfill=Ce,e.initializeWebMCPPolyfill=Se,e.initializeWebModelContextPolyfill=Se,e.isPlainObject=V,e.validateArgsWithSchema=Z,e})({});
1
+ var WebMCPPolyfill=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e,n){let r=typeof e;if(r!==typeof n)return!1;if(Array.isArray(e)){if(!Array.isArray(n))return!1;let r=e.length;if(r!==n.length)return!1;for(let i=0;i<r;i++)if(!t(e[i],n[i]))return!1;return!0}if(r===`object`){if(!e||!n)return e===n;let r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;for(let i of r)if(!t(e[i],n[i]))return!1;return!0}return e===n}function n(e){return encodeURI(r(e))}function r(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}let i={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},a={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},o={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},s=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function c(e,t=Object.create(null),r=s,l=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let n=e.$id||e.id;if(n){let i=new URL(n,r.href);i.hash.length>1?t[i.href]=e:(i.hash=``,l===``?r=i:c(e,t,r))}}else if(e!==!0&&e!==!1)return t;let u=r.href+(l?`#`+l:``);if(t[u]!==void 0)throw Error(`Duplicate schema URI "${u}".`);if(t[u]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,`__absolute_uri__`,{enumerable:!1,value:u}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_ref__`,{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}if(e.$anchor){let n=new URL(`#`+e.$anchor,r.href);t[n.href]=e}for(let s in e){if(o[s])continue;let u=`${l}/${n(s)}`,d=e[s];if(Array.isArray(d)){if(i[s]){let e=d.length;for(let n=0;n<e;n++)c(d[n],t,r,`${u}/${n}`)}}else if(a[s])for(let e in d)c(d[e],t,r,`${u}/${n(e)}`);else c(d,t,r,u)}return t}let l=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,u=[0,31,28,31,30,31,30,31,31,30,31,30,31],d=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,f=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,p=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[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/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,h=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,g=/^(?:\/(?:[^~/]|~0|~1)*)*$/,_=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,v=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,te=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},ne=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,y=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,b=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function x(e){return e.test.bind(e)}let re={date:S,time:C.bind(void 0,!1),"date-time":T,duration:b,uri:oe,"uri-reference":x(p),"uri-template":x(m),url:x(ee),email:te,hostname:x(f),ipv4:x(ne),ipv6:x(y),regex:O,uuid:x(h),"json-pointer":x(g),"json-pointer-uri-fragment":x(_),"relative-json-pointer":x(v)};function ie(e){return e%4==0&&(e%100!=0||e%400==0)}function S(e){let t=e.match(l);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&ie(n)?29:u[r])}function C(e,t){let n=t.match(d);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}let w=/t|\s/i;function T(e){let t=e.split(w);return t.length==2&&S(t[0])&&C(!0,t[1])}let E=/\/|:/,ae=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function oe(e){return E.test(e)&&ae.test(e)}let D=/[^\\]\\Z/;function O(e){if(D.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function se(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function k(e,r,i=`2019-09`,a=c(r),o=!0,s=null,l=`#`,u=`#`,d=Object.create(null)){if(r===!0)return{valid:!0,errors:[]};if(r===!1)return{valid:!1,errors:[{instanceLocation:l,keyword:`false`,keywordLocation:l,error:`False boolean schema.`}]};let f=typeof e,p;switch(f){case`boolean`:case`number`:case`string`:p=f;break;case`object`:p=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${f}" type are not supported.`)}let{$ref:m,$recursiveRef:ee,$recursiveAnchor:h,type:g,const:_,enum:v,required:te,not:ne,anyOf:y,allOf:b,oneOf:x,if:ie,then:S,else:C,format:w,properties:T,patternProperties:E,additionalProperties:ae,unevaluatedProperties:oe,minProperties:D,maxProperties:O,propertyNames:ce,dependentRequired:A,dependentSchemas:j,dependencies:M,prefixItems:N,items:P,additionalItems:F,unevaluatedItems:I,contains:le,minContains:L,maxContains:R,minItems:z,maxItems:B,uniqueItems:V,minimum:H,maximum:U,exclusiveMinimum:W,exclusiveMaximum:G,multipleOf:K,minLength:q,maxLength:J,pattern:Y,__absolute_ref__:X,__absolute_recursive_ref__:ue}=r,Z=[];if(h===!0&&s===null&&(s=r),ee===`#`){let t=s===null?a[ue]:s,n=`${u}/$recursiveRef`,c=k(e,s===null?r:s,i,a,o,t,l,n,d);c.valid||Z.push({instanceLocation:l,keyword:`$recursiveRef`,keywordLocation:n,error:`A subschema had errors.`},...c.errors)}if(m!==void 0){let t=a[X||m];if(t===void 0){let e=`Unresolved $ref "${m}".`;throw X&&X!==m&&(e+=` Absolute URI "${X}".`),e+=`\nKnown schemas:\n- ${Object.keys(a).join(`
2
+ - `)}`,Error(e)}let n=`${u}/$ref`,r=k(e,t,i,a,o,s,l,n,d);if(r.valid||Z.push({instanceLocation:l,keyword:`$ref`,keywordLocation:n,error:`A subschema had errors.`},...r.errors),i===`4`||i===`7`)return{valid:Z.length===0,errors:Z}}if(Array.isArray(g)){let t=g.length,n=!1;for(let r=0;r<t;r++)if(p===g[r]||g[r]===`integer`&&p===`number`&&e%1==0&&e===e){n=!0;break}n||Z.push({instanceLocation:l,keyword:`type`,keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${g.join(`", "`)}".`})}else g===`integer`?(p!==`number`||e%1||e!==e)&&Z.push({instanceLocation:l,keyword:`type`,keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${g}".`}):g!==void 0&&p!==g&&Z.push({instanceLocation:l,keyword:`type`,keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${g}".`});if(_!==void 0&&(p===`object`||p===`array`?t(e,_)||Z.push({instanceLocation:l,keyword:`const`,keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(_)}.`}):e!==_&&Z.push({instanceLocation:l,keyword:`const`,keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(_)}.`})),v!==void 0&&(p===`object`||p===`array`?v.some(n=>t(e,n))||Z.push({instanceLocation:l,keyword:`enum`,keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`}):v.some(t=>e===t)||Z.push({instanceLocation:l,keyword:`enum`,keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(v)}.`})),ne!==void 0){let t=`${u}/not`;k(e,ne,i,a,o,s,l,t).valid&&Z.push({instanceLocation:l,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Q=[];if(y!==void 0){let t=`${u}/anyOf`,n=Z.length,r=!1;for(let n=0;n<y.length;n++){let c=y[n],u=Object.create(d),f=k(e,c,i,a,o,h===!0?s:null,l,`${t}/${n}`,u);Z.push(...f.errors),r||=f.valid,f.valid&&Q.push(u)}r?Z.length=n:Z.splice(n,0,{instanceLocation:l,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${u}/allOf`,n=Z.length,r=!0;for(let n=0;n<b.length;n++){let c=b[n],u=Object.create(d),f=k(e,c,i,a,o,h===!0?s:null,l,`${t}/${n}`,u);Z.push(...f.errors),r&&=f.valid,f.valid&&Q.push(u)}r?Z.length=n:Z.splice(n,0,{instanceLocation:l,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${u}/oneOf`,n=Z.length,r=x.filter((n,r)=>{let c=Object.create(d),u=k(e,n,i,a,o,h===!0?s:null,l,`${t}/${r}`,c);return Z.push(...u.errors),u.valid&&Q.push(c),u.valid}).length;r===1?Z.length=n:Z.splice(n,0,{instanceLocation:l,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${r} matches).`})}if((p===`object`||p===`array`)&&Object.assign(d,...Q),ie!==void 0){let t=`${u}/if`;if(k(e,ie,i,a,o,s,l,t,d).valid){if(S!==void 0){let n=k(e,S,i,a,o,s,l,`${u}/then`,d);n.valid||Z.push({instanceLocation:l,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...n.errors)}}else if(C!==void 0){let n=k(e,C,i,a,o,s,l,`${u}/else`,d);n.valid||Z.push({instanceLocation:l,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...n.errors)}}if(p===`object`){if(te!==void 0)for(let t of te)t in e||Z.push({instanceLocation:l,keyword:`required`,keywordLocation:`${u}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(D!==void 0&&t.length<D&&Z.push({instanceLocation:l,keyword:`minProperties`,keywordLocation:`${u}/minProperties`,error:`Instance does not have at least ${D} properties.`}),O!==void 0&&t.length>O&&Z.push({instanceLocation:l,keyword:`maxProperties`,keywordLocation:`${u}/maxProperties`,error:`Instance does not have at least ${O} properties.`}),ce!==void 0){let t=`${u}/propertyNames`;for(let r in e){let e=`${l}/${n(r)}`,c=k(r,ce,i,a,o,s,e,t);c.valid||Z.push({instanceLocation:l,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${r}" does not match schema.`},...c.errors)}}if(A!==void 0){let t=`${u}/dependantRequired`;for(let n in A)if(n in e){let r=A[n];for(let i of r)i in e||Z.push({instanceLocation:l,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(j!==void 0)for(let t in j){let r=`${u}/dependentSchemas`;if(t in e){let c=k(e,j[t],i,a,o,s,l,`${r}/${n(t)}`,d);c.valid||Z.push({instanceLocation:l,keyword:`dependentSchemas`,keywordLocation:r,error:`Instance has "${t}" but does not match dependant schema.`},...c.errors)}}if(M!==void 0){let t=`${u}/dependencies`;for(let r in M)if(r in e){let c=M[r];if(Array.isArray(c))for(let n of c)n in e||Z.push({instanceLocation:l,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${r}" but does not have "${n}".`});else{let u=k(e,c,i,a,o,s,l,`${t}/${n(r)}`);u.valid||Z.push({instanceLocation:l,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${r}" but does not match dependant schema.`},...u.errors)}}}let r=Object.create(null),c=!1;if(T!==void 0){let t=`${u}/properties`;for(let u in T){if(!(u in e))continue;let f=`${l}/${n(u)}`,p=k(e[u],T[u],i,a,o,s,f,`${t}/${n(u)}`);if(p.valid)d[u]=r[u]=!0;else if(c=o,Z.push({instanceLocation:l,keyword:`properties`,keywordLocation:t,error:`Property "${u}" does not match schema.`},...p.errors),c)break}}if(!c&&E!==void 0){let t=`${u}/patternProperties`;for(let u in E){let f=new RegExp(u,`u`),p=E[u];for(let m in e){if(!f.test(m))continue;let ee=`${l}/${n(m)}`,h=k(e[m],p,i,a,o,s,ee,`${t}/${n(u)}`);h.valid?d[m]=r[m]=!0:(c=o,Z.push({instanceLocation:l,keyword:`patternProperties`,keywordLocation:t,error:`Property "${m}" matches pattern "${u}" but does not match associated schema.`},...h.errors))}}}if(!c&&ae!==void 0){let t=`${u}/additionalProperties`;for(let u in e){if(r[u])continue;let f=`${l}/${n(u)}`,p=k(e[u],ae,i,a,o,s,f,t);p.valid?d[u]=!0:(c=o,Z.push({instanceLocation:l,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${u}" does not match additional properties schema.`},...p.errors))}}else if(!c&&oe!==void 0){let t=`${u}/unevaluatedProperties`;for(let r in e)if(!d[r]){let c=`${l}/${n(r)}`,u=k(e[r],oe,i,a,o,s,c,t);u.valid?d[r]=!0:Z.push({instanceLocation:l,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${r}" does not match unevaluated properties schema.`},...u.errors)}}}else if(p===`array`){B!==void 0&&e.length>B&&Z.push({instanceLocation:l,keyword:`maxItems`,keywordLocation:`${u}/maxItems`,error:`Array has too many items (${e.length} > ${B}).`}),z!==void 0&&e.length<z&&Z.push({instanceLocation:l,keyword:`minItems`,keywordLocation:`${u}/minItems`,error:`Array has too few items (${e.length} < ${z}).`});let n=e.length,r=0,c=!1;if(N!==void 0){let t=`${u}/prefixItems`,f=Math.min(N.length,n);for(;r<f;r++){let n=k(e[r],N[r],i,a,o,s,`${l}/${r}`,`${t}/${r}`);if(d[r]=!0,!n.valid&&(c=o,Z.push({instanceLocation:l,keyword:`prefixItems`,keywordLocation:t,error:`Items did not match schema.`},...n.errors),c))break}}if(P!==void 0){let t=`${u}/items`;if(Array.isArray(P)){let u=Math.min(P.length,n);for(;r<u;r++){let n=k(e[r],P[r],i,a,o,s,`${l}/${r}`,`${t}/${r}`);if(d[r]=!0,!n.valid&&(c=o,Z.push({instanceLocation:l,keyword:`items`,keywordLocation:t,error:`Items did not match schema.`},...n.errors),c))break}}else for(;r<n;r++){let n=k(e[r],P,i,a,o,s,`${l}/${r}`,t);if(d[r]=!0,!n.valid&&(c=o,Z.push({instanceLocation:l,keyword:`items`,keywordLocation:t,error:`Items did not match schema.`},...n.errors),c))break}if(!c&&F!==void 0){let t=`${u}/additionalItems`;for(;r<n;r++){let n=k(e[r],F,i,a,o,s,`${l}/${r}`,t);d[r]=!0,n.valid||(c=o,Z.push({instanceLocation:l,keyword:`additionalItems`,keywordLocation:t,error:`Items did not match additional items schema.`},...n.errors))}}}if(le!==void 0)if(n===0&&L===void 0)Z.push({instanceLocation:l,keyword:`contains`,keywordLocation:`${u}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(L!==void 0&&n<L)Z.push({instanceLocation:l,keyword:`minContains`,keywordLocation:`${u}/minContains`,error:`Array has less items (${n}) than minContains (${L}).`});else{let t=`${u}/contains`,r=Z.length,c=0;for(let r=0;r<n;r++){let n=k(e[r],le,i,a,o,s,`${l}/${r}`,t);n.valid?(d[r]=!0,c++):Z.push(...n.errors)}c>=(L||0)&&(Z.length=r),L===void 0&&R===void 0&&c===0?Z.splice(r,0,{instanceLocation:l,keyword:`contains`,keywordLocation:t,error:`Array does not contain item matching schema.`}):L!==void 0&&c<L?Z.push({instanceLocation:l,keyword:`minContains`,keywordLocation:`${u}/minContains`,error:`Array must contain at least ${L} items matching schema. Only ${c} items were found.`}):R!==void 0&&c>R&&Z.push({instanceLocation:l,keyword:`maxContains`,keywordLocation:`${u}/maxContains`,error:`Array may contain at most ${R} items matching schema. ${c} items were found.`})}if(!c&&I!==void 0){let t=`${u}/unevaluatedItems`;for(;r<n;r++){if(d[r])continue;let n=k(e[r],I,i,a,o,s,`${l}/${r}`,t);d[r]=!0,n.valid||Z.push({instanceLocation:l,keyword:`unevaluatedItems`,keywordLocation:t,error:`Items did not match unevaluated items schema.`},...n.errors)}}if(V)for(let r=0;r<n;r++){let i=e[r],a=typeof i==`object`&&!!i;for(let o=0;o<n;o++){if(r===o)continue;let n=e[o];(i===n||a&&typeof n==`object`&&n&&t(i,n))&&(Z.push({instanceLocation:l,keyword:`uniqueItems`,keywordLocation:`${u}/uniqueItems`,error:`Duplicate items at indexes ${r} and ${o}.`}),r=2**53-1,o=2**53-1)}}}else if(p===`number`){if(i===`4`?(H!==void 0&&(W===!0&&e<=H||e<H)&&Z.push({instanceLocation:l,keyword:`minimum`,keywordLocation:`${u}/minimum`,error:`${e} is less than ${W?`or equal to `:``} ${H}.`}),U!==void 0&&(G===!0&&e>=U||e>U)&&Z.push({instanceLocation:l,keyword:`maximum`,keywordLocation:`${u}/maximum`,error:`${e} is greater than ${G?`or equal to `:``} ${U}.`})):(H!==void 0&&e<H&&Z.push({instanceLocation:l,keyword:`minimum`,keywordLocation:`${u}/minimum`,error:`${e} is less than ${H}.`}),U!==void 0&&e>U&&Z.push({instanceLocation:l,keyword:`maximum`,keywordLocation:`${u}/maximum`,error:`${e} is greater than ${U}.`}),W!==void 0&&e<=W&&Z.push({instanceLocation:l,keyword:`exclusiveMinimum`,keywordLocation:`${u}/exclusiveMinimum`,error:`${e} is less than ${W}.`}),G!==void 0&&e>=G&&Z.push({instanceLocation:l,keyword:`exclusiveMaximum`,keywordLocation:`${u}/exclusiveMaximum`,error:`${e} is greater than or equal to ${G}.`})),K!==void 0){let t=e%K;Math.abs(0-t)>=1.1920929e-7&&Math.abs(K-t)>=1.1920929e-7&&Z.push({instanceLocation:l,keyword:`multipleOf`,keywordLocation:`${u}/multipleOf`,error:`${e} is not a multiple of ${K}.`})}}else if(p===`string`){let t=q===void 0&&J===void 0?0:se(e);q!==void 0&&t<q&&Z.push({instanceLocation:l,keyword:`minLength`,keywordLocation:`${u}/minLength`,error:`String is too short (${t} < ${q}).`}),J!==void 0&&t>J&&Z.push({instanceLocation:l,keyword:`maxLength`,keywordLocation:`${u}/maxLength`,error:`String is too long (${t} > ${J}).`}),Y!==void 0&&!new RegExp(Y,`u`).test(e)&&Z.push({instanceLocation:l,keyword:`pattern`,keywordLocation:`${u}/pattern`,error:`String does not match pattern.`}),w!==void 0&&re[w]&&!re[w](e)&&Z.push({instanceLocation:l,keyword:`format`,keywordLocation:`${u}/format`,error:`String does not match format "${w}".`})}return{valid:Z.length===0,errors:Z}}var ce=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=c(e)}validate(e){return k(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),c(e,this.lookup)}};let A=`Failed to parse input arguments`,j=`Tool was executed but the invocation failed. For example, the script function threw an error`,M=`Tool was cancelled`,N={type:`object`,properties:{}},P=[`draft-2020-12`,`draft-07`],F=Symbol(`standardValidator`),I={installed:!1,previousNavigatorModelContextDescriptor:void 0,previousNavigatorModelContextTestingDescriptor:void 0,previousDocumentModelContextDescriptor:void 0,installedNavigatorModelContext:!1,installedNavigatorModelContextTesting:!1,installedDocumentModelContext:!1};var le=class extends EventTarget{tools=new Map;testingShim=null;_ontoolchange=null;unregisterToolDeprecationWarned=!1;get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerTool(e,t){let n=t?.signal;if(n?.aborted){console.warn(`[WebMCPPolyfill] registerTool("${e?.name??`<unknown>`}") skipped: options.signal was already aborted.`);return}let r=X(e,this.tools);this.tools.set(r.name,r),this.notifyToolsChanged(),n&&n.addEventListener(`abort`,()=>{this.tools.delete(r.name)&&this.notifyToolsChanged()},{once:!0})}unregisterTool(e){this.warnUnregisterToolDeprecationOnce();let t=B(e);this.tools.delete(t)&&this.notifyToolsChanged()}getTools(){return Promise.resolve(this.getRegisteredToolInfos())}executeTool(e,t,n){return this.executeToolByName(e.name,t,n,!1)}getTestingShim(){return this.testingShim||=new L(this),this.testingShim}getToolInfos(){return[...this.tools.values()].map(e=>{let t;try{t=JSON.stringify(e.inputSchema??{type:`object`})}catch{t=`{"type":"object"}`}return{name:e.name,description:e.description,inputSchema:t}})}getRegisteredToolInfos(){return this.getToolInfos().map(e=>{let t=this.tools.get(e.name);return{...e,title:t?.title??``,origin:globalThis.location?.origin??``,window:globalThis.window}})}async executeToolForTesting(e,t,n){return this.executeToolByName(e,t,n,!0)}async executeToolByName(e,t,n,r){if(n?.signal?.aborted)throw R(M);let i=this.tools.get(e);if(!i)throw R(`Tool not found: ${e}`);let a=z(t),o=await de(a,i);if(o)throw R(o);let s=!0,c={requestUserInteraction:async t=>{if(!s)throw Error(`ModelContextClient for tool "${e}" is no longer active after execute() resolved`);if(typeof t!=`function`)throw TypeError(`requestUserInteraction(callback) requires a function callback`);return t()}};try{let e=i.execute(a,c),t=await be(Promise.resolve(e),n?.signal);if(r)return ye(_e(t));let o=JSON.stringify(t);return o===void 0?null:o}catch(e){throw R(e instanceof Error?`${j}: ${e.message}`:j)}finally{s=!1}}notifyToolsChanged(){queueMicrotask(()=>{let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.testingShim?.dispatchToolChange()})}warnUnregisterToolDeprecationOnce(){this.unregisterToolDeprecationWarned||(this.unregisterToolDeprecationWarned=!0,console.warn(`[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.`))}},L=class extends EventTarget{context;_ontoolchange=null;constructor(e){super(),this.context=e}listTools(){return this.context.getToolInfos()}executeTool(e,t,n){return this.context.executeToolForTesting(e,t,n)}getCrossDocumentScriptToolResult(){return Promise.resolve(`[]`)}get ontoolchange(){return this._ontoolchange}set ontoolchange(e){this._ontoolchange=e}registerToolsChangedCallback(e){if(typeof e!=`function`)throw TypeError(`Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.`);this.addEventListener(`toolchange`,e)}dispatchToolChange(){let e=new Event(`toolchange`);try{this._ontoolchange?.call(this,e)}catch(e){console.warn(`[WebMCPPolyfill] ontoolchange handler threw:`,e)}this.dispatchEvent(e),this.dispatchEvent(new Event(`toolschanged`))}};function R(e){try{return new DOMException(e,`UnknownError`)}catch{let t=Error(e);return t.name=`UnknownError`,t}}function z(e){let t;try{t=JSON.parse(e)}catch{throw R(A)}if(!t||typeof t!=`object`||Array.isArray(t))throw R(A);return t}function B(e){if(typeof e==`string`)return e;if(V(e)&&typeof e.name==`string`)return e.name;throw TypeError(`Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.`)}function V(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function H(e){if(!V(e))return null;let t=e[`~standard`];return V(t)?t:null}function U(e){let t=H(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function W(e){let t=H(e);return!t||t.version!==1||!V(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function G(e){return{"~standard":{version:1,vendor:`@mcp-b/webmcp-polyfill-json-schema`,validate(t){if(!V(t))return{issues:[{message:`expected object arguments`}]};let n=ue(t,e);return n?{issues:[n]}:{value:t}}}}}function K(e){for(let t of P)try{let n=e[`~standard`].jsonSchema.input({target:t});return J(n),n}catch(e){console.warn(`[WebMCPPolyfill] Standard JSON Schema conversion failed for target "${t}":`,e)}throw Error(`Failed to convert Standard JSON Schema inputSchema to a JSON Schema object`)}function q(e){if(e===void 0){let e=N;return{inputSchema:e,standardValidator:G(e)}}if(W(e)){let t=K(e);return{inputSchema:t,standardValidator:G(t)}}if(U(e))return{inputSchema:N,standardValidator:e};if(J(e),Object.keys(e).length===0)return{inputSchema:N,standardValidator:G(N)};let t=e.type===void 0?{type:`object`,...e}:e;return{inputSchema:t,standardValidator:G(t)}}function J(e){if(!V(e))throw Error(`inputSchema must be a JSON Schema object`);Y(e,`$`)}function Y(e,t){let n=e.type;if(n!==void 0&&typeof n!=`string`&&!(Array.isArray(n)&&n.every(e=>typeof e==`string`&&e.length>0)))throw Error(`Invalid JSON Schema at ${t}: "type" must be a string or string[]`);let r=e.required;if(r!==void 0&&!(Array.isArray(r)&&r.every(e=>typeof e==`string`)))throw Error(`Invalid JSON Schema at ${t}: "required" must be an array of strings`);let i=e.properties;if(i!==void 0){if(!V(i))throw Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[e,n]of Object.entries(i)){if(!V(n))throw Error(`Invalid JSON Schema at ${t}.properties.${e}: expected object schema`);Y(n,`${t}.properties.${e}`)}}let a=e.items;if(a!==void 0)if(Array.isArray(a))for(let[e,n]of a.entries()){if(!V(n))throw Error(`Invalid JSON Schema at ${t}.items[${e}]: expected object schema`);Y(n,`${t}.items[${e}]`)}else if(V(a))Y(a,`${t}.items`);else throw Error(`Invalid JSON Schema at ${t}: "items" must be an object or object[]`);for(let n of[`allOf`,`anyOf`,`oneOf`]){let r=e[n];if(r!==void 0){if(!Array.isArray(r))throw Error(`Invalid JSON Schema at ${t}: "${n}" must be an array`);for(let[e,i]of r.entries()){if(!V(i))throw Error(`Invalid JSON Schema at ${t}.${n}[${e}]: expected object schema`);Y(i,`${t}.${n}[${e}]`)}}}let o=e.not;if(o!==void 0){if(!V(o))throw Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);Y(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function X(e,t){if(!e||typeof e!=`object`)throw TypeError(`registerTool(tool) requires a tool object`);if(typeof e.name!=`string`||e.name.length===0)throw TypeError(`Tool "name" must be a non-empty string`);if(typeof e.description!=`string`||e.description.length===0)throw TypeError(`Tool "description" must be a non-empty string`);if(typeof e.execute!=`function`)throw TypeError(`Tool "execute" must be a function`);if(t.has(e.name))throw Error(`Tool already registered: ${e.name}`);let n=q(e.inputSchema),r=e.annotations,i=r?{...r,...r.readOnlyHint===`true`?{readOnlyHint:!0}:r.readOnlyHint===`false`?{readOnlyHint:!1}:{},...r.destructiveHint===`true`?{destructiveHint:!0}:r.destructiveHint===`false`?{destructiveHint:!1}:{},...r.idempotentHint===`true`?{idempotentHint:!0}:r.idempotentHint===`false`?{idempotentHint:!1}:{},...r.openWorldHint===`true`?{openWorldHint:!0}:r.openWorldHint===`false`?{openWorldHint:!1}:{}}:void 0;return{...e,...i?{annotations:i}:{},inputSchema:n.inputSchema,[F]:n.standardValidator}}function ue(e,t){let n=new ce(t,`2020-12`,!0).validate(e);if(n.valid)return null;let r=n.errors[n.errors.length-1];return r?{message:r.error}:{message:`Input validation failed`}}function Z(e){if(!e||e.length===0)return null;let t=e.map(e=>V(e)&&`key`in e?e.key:e).map(e=>String(e)).filter(e=>e.length>0);return t.length===0?null:t.join(`.`)}async function Q(e,t){let n;try{n=await Promise.resolve(t[`~standard`].validate(e))}catch(e){let t=e instanceof Error?`: ${e.message}`:``;return console.error(`[WebMCPPolyfill] Standard Schema validation threw unexpectedly:`,e),`Input validation error: schema validation failed${t}`}if(!n.issues||n.issues.length===0)return null;let r=n.issues[0];if(!r)return`Input validation error`;let i=Z(r?.path);return i?`Input validation error: ${r.message} at ${i}`:`Input validation error: ${r.message}`}async function de(e,t){return Q(e,t[F])}function fe(e){return V(e)&&Array.isArray(e.content)}function pe(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function me(e){return pe(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>me(e)):V(e)?Object.values(e).every(e=>me(e)):!1}function he(e){if(!(!V(e)||!me(e)))return e}function ge(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function _e(e){if(fe(e))return e;let t=he(e);return{content:[{type:`text`,text:ge(e)}],...t?{structuredContent:t}:{},isError:!1}}function ve(e){for(let t of e.content??[])if(t.type===`text`&&`text`in t&&typeof t.text==`string`)return t.text;return null}function ye(e){if(e.isError)throw R(ve(e)?.replace(/^Error:\s*/i,``).trim()||j);let t=e.metadata;if(t&&typeof t==`object`&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw R(j)}}function be(e,t){return t?t.aborted?Promise.reject(R(M)):new Promise((n,r)=>{let i=()=>{a(),r(R(M))},a=()=>{t.removeEventListener(`abort`,i)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}function xe(){return typeof navigator<`u`?navigator:null}function Se(){return typeof document<`u`?document:null}function Ce(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function we(e,t){Object.defineProperty(e,`modelContext`,{configurable:!0,enumerable:!0,writable:!1,value:t})}let $=!1;function Te(e,t){Object.defineProperty(e,`modelContext`,{configurable:!0,enumerable:!0,get(){return $||($=!0,console.warn(`[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.`)),t}})}function Ee(e){let t=xe(),n=Se();if(!t&&!n||n?.modelContext)return;let r=t?.modelContext,i=!!r;if(I.installed&&De(),n&&r){I.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(n,`modelContext`),we(n,r),I.installedDocumentModelContext=!0,I.installed=!0;return}if(i)return;let a=new le,o=a;if(o.__isWebMCPPolyfill=!0,n&&(I.previousDocumentModelContextDescriptor=Object.getOwnPropertyDescriptor(n,`modelContext`),we(n,o),I.installedDocumentModelContext=!0),t){I.previousNavigatorModelContextDescriptor=Object.getOwnPropertyDescriptor(t,`modelContext`),I.previousNavigatorModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,`modelContextTesting`),$=!1,Te(t,o),I.installedNavigatorModelContext=!0;let n=e?.installTestingShim??`if-missing`,r=!!t.modelContextTesting;(n===`always`||(n===!0||n===`if-missing`)&&!r)&&(Ce(t,`modelContextTesting`,a.getTestingShim()),I.installedNavigatorModelContextTesting=!0)}I.installed=!0}function De(){if(!I.installed)return;let e=(e,t,n)=>{if(n){Object.defineProperty(e,t,n);return}delete e[t]},t=xe(),n=Se();n&&I.installedDocumentModelContext&&e(n,`modelContext`,I.previousDocumentModelContextDescriptor),t&&I.installedNavigatorModelContext&&e(t,`modelContext`,I.previousNavigatorModelContextDescriptor),t&&I.installedNavigatorModelContextTesting&&e(t,`modelContextTesting`,I.previousNavigatorModelContextTestingDescriptor),I.installed=!1,I.previousDocumentModelContextDescriptor=void 0,I.previousNavigatorModelContextDescriptor=void 0,I.previousNavigatorModelContextTestingDescriptor=void 0,I.installedDocumentModelContext=!1,I.installedNavigatorModelContext=!1,I.installedNavigatorModelContextTesting=!1,$=!1}if(typeof window<`u`&&typeof document<`u`){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{Ee(e)}catch(e){console.error(`[WebMCPPolyfill] Auto-initialization failed:`,e)}}return e.cleanupWebMCPPolyfill=De,e.initializeWebMCPPolyfill=Ee,e.initializeWebModelContextPolyfill=Ee,e.isPlainObject=V,e.validateArgsWithSchema=ue,e})({});
package/dist/index.js CHANGED
@@ -13,15 +13,17 @@ const POLYFILL_MARKER_PROPERTY = "__isWebMCPPolyfill";
13
13
  const STANDARD_VALIDATOR_SYMBOL = Symbol("standardValidator");
14
14
  const installState = {
15
15
  installed: false,
16
- previousModelContextDescriptor: void 0,
17
- previousModelContextTestingDescriptor: void 0
16
+ previousNavigatorModelContextDescriptor: void 0,
17
+ previousNavigatorModelContextTestingDescriptor: void 0,
18
+ previousDocumentModelContextDescriptor: void 0,
19
+ installedNavigatorModelContext: false,
20
+ installedNavigatorModelContextTesting: false,
21
+ installedDocumentModelContext: false
18
22
  };
19
23
  var StrictWebMCPContext = class extends EventTarget {
20
24
  tools = /* @__PURE__ */ new Map();
21
25
  testingShim = null;
22
26
  _ontoolchange = null;
23
- provideContextDeprecationWarned = false;
24
- clearContextDeprecationWarned = false;
25
27
  unregisterToolDeprecationWarned = false;
26
28
  get ontoolchange() {
27
29
  return this._ontoolchange;
@@ -29,21 +31,6 @@ var StrictWebMCPContext = class extends EventTarget {
29
31
  set ontoolchange(handler) {
30
32
  this._ontoolchange = handler;
31
33
  }
32
- provideContext(options = {}) {
33
- this.warnProvideContextDeprecationOnce();
34
- const nextTools = /* @__PURE__ */ new Map();
35
- for (const tool of options.tools ?? []) {
36
- const normalized = normalizeToolDescriptor(tool, nextTools);
37
- nextTools.set(normalized.name, normalized);
38
- }
39
- this.tools = nextTools;
40
- this.notifyToolsChanged();
41
- }
42
- clearContext() {
43
- this.warnClearContextDeprecationOnce();
44
- this.tools.clear();
45
- this.notifyToolsChanged();
46
- }
47
34
  registerTool(tool, options) {
48
35
  const signal = options?.signal;
49
36
  if (signal?.aborted) {
@@ -63,7 +50,10 @@ var StrictWebMCPContext = class extends EventTarget {
63
50
  if (this.tools.delete(name)) this.notifyToolsChanged();
64
51
  }
65
52
  getTools() {
66
- return this.getToolInfos();
53
+ return Promise.resolve(this.getRegisteredToolInfos());
54
+ }
55
+ executeTool(tool, inputArgsJson, options) {
56
+ return this.executeToolByName(tool.name, inputArgsJson, options, false);
67
57
  }
68
58
  getTestingShim() {
69
59
  if (!this.testingShim) this.testingShim = new PolyfillTestingShim(this);
@@ -85,8 +75,23 @@ var StrictWebMCPContext = class extends EventTarget {
85
75
  };
86
76
  });
87
77
  }
78
+ /** @internal Used by getTools() */
79
+ getRegisteredToolInfos() {
80
+ return this.getToolInfos().map((toolInfo) => {
81
+ const tool = this.tools.get(toolInfo.name);
82
+ return {
83
+ ...toolInfo,
84
+ title: tool?.title ?? "",
85
+ origin: globalThis.location?.origin ?? "",
86
+ window: globalThis.window
87
+ };
88
+ });
89
+ }
88
90
  /** @internal Used by PolyfillTestingShim */
89
91
  async executeToolForTesting(toolName, inputArgsJson, options) {
92
+ return this.executeToolByName(toolName, inputArgsJson, options, true);
93
+ }
94
+ async executeToolByName(toolName, inputArgsJson, options, normalizeResult) {
90
95
  if (options?.signal?.aborted) throw createUnknownError(TOOL_CANCELLED_MESSAGE);
91
96
  const tool = this.tools.get(toolName);
92
97
  if (!tool) throw createUnknownError(`Tool not found: ${toolName}`);
@@ -101,7 +106,10 @@ var StrictWebMCPContext = class extends EventTarget {
101
106
  } };
102
107
  try {
103
108
  const execution = tool.execute(args, client);
104
- return toSerializedTestingResult(normalizeToolResponse(await withAbortSignal(Promise.resolve(execution), options?.signal)));
109
+ const rawResult = await withAbortSignal(Promise.resolve(execution), options?.signal);
110
+ if (normalizeResult) return toSerializedTestingResult(normalizeToolResponse(rawResult));
111
+ const serialized = JSON.stringify(rawResult);
112
+ return serialized === void 0 ? null : serialized;
105
113
  } catch (error) {
106
114
  throw createUnknownError(error instanceof Error ? `${TOOL_INVOCATION_FAILED_MESSAGE}: ${error.message}` : TOOL_INVOCATION_FAILED_MESSAGE);
107
115
  } finally {
@@ -120,16 +128,6 @@ var StrictWebMCPContext = class extends EventTarget {
120
128
  this.testingShim?.dispatchToolChange();
121
129
  });
122
130
  }
123
- warnProvideContextDeprecationOnce() {
124
- if (this.provideContextDeprecationWarned) return;
125
- this.provideContextDeprecationWarned = true;
126
- console.warn("[WebMCPPolyfill] navigator.modelContext.provideContext() is deprecated and will be removed in the next major version. Register tools individually with registerTool() instead.");
127
- }
128
- warnClearContextDeprecationOnce() {
129
- if (this.clearContextDeprecationWarned) return;
130
- this.clearContextDeprecationWarned = true;
131
- console.warn("[WebMCPPolyfill] navigator.modelContext.clearContext() is deprecated and will be removed in the next major version. Unregister individual tools instead.");
132
- }
133
131
  warnUnregisterToolDeprecationOnce() {
134
132
  if (this.unregisterToolDeprecationWarned) return;
135
133
  this.unregisterToolDeprecationWarned = true;
@@ -462,6 +460,10 @@ function getNavigator() {
462
460
  if (typeof navigator !== "undefined") return navigator;
463
461
  return null;
464
462
  }
463
+ function getDocument() {
464
+ if (typeof document !== "undefined") return document;
465
+ return null;
466
+ }
465
467
  function defineNavigatorProperty(target, key, value) {
466
468
  Object.defineProperty(target, key, {
467
469
  configurable: true,
@@ -470,37 +472,90 @@ function defineNavigatorProperty(target, key, value) {
470
472
  value
471
473
  });
472
474
  }
475
+ function defineDocumentModelContextProperty(target, value) {
476
+ Object.defineProperty(target, "modelContext", {
477
+ configurable: true,
478
+ enumerable: true,
479
+ writable: false,
480
+ value
481
+ });
482
+ }
483
+ let navigatorModelContextDeprecationWarned = false;
484
+ function defineDeprecatedNavigatorModelContext(target, value) {
485
+ Object.defineProperty(target, "modelContext", {
486
+ configurable: true,
487
+ enumerable: true,
488
+ get() {
489
+ if (!navigatorModelContextDeprecationWarned) {
490
+ navigatorModelContextDeprecationWarned = true;
491
+ console.warn("[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.");
492
+ }
493
+ return value;
494
+ }
495
+ });
496
+ }
473
497
  function initializeWebMCPPolyfill(options) {
474
498
  const nav = getNavigator();
475
- if (!nav) return;
476
- if (Boolean(nav.modelContext)) return;
499
+ const doc = getDocument();
500
+ if (!nav && !doc) return;
501
+ const documentModelContext = doc?.modelContext;
502
+ if (Boolean(documentModelContext)) return;
503
+ const navigatorModelContext = nav?.modelContext;
504
+ const hasNavigatorModelContext = Boolean(navigatorModelContext);
477
505
  if (installState.installed) cleanupWebMCPPolyfill();
506
+ if (doc && navigatorModelContext) {
507
+ installState.previousDocumentModelContextDescriptor = Object.getOwnPropertyDescriptor(doc, "modelContext");
508
+ defineDocumentModelContextProperty(doc, navigatorModelContext);
509
+ installState.installedDocumentModelContext = true;
510
+ installState.installed = true;
511
+ return;
512
+ }
513
+ if (hasNavigatorModelContext) return;
478
514
  const context = new StrictWebMCPContext();
479
515
  const modelContext = context;
480
516
  modelContext[POLYFILL_MARKER_PROPERTY] = true;
481
- installState.previousModelContextDescriptor = Object.getOwnPropertyDescriptor(nav, "modelContext");
482
- installState.previousModelContextTestingDescriptor = Object.getOwnPropertyDescriptor(nav, "modelContextTesting");
483
- defineNavigatorProperty(nav, "modelContext", modelContext);
484
- const installTestingShim = options?.installTestingShim ?? "if-missing";
485
- const hasModelContextTesting = Boolean(nav.modelContextTesting);
486
- if (installTestingShim === "always" || (installTestingShim === true || installTestingShim === "if-missing") && !hasModelContextTesting) defineNavigatorProperty(nav, "modelContextTesting", context.getTestingShim());
517
+ if (doc) {
518
+ installState.previousDocumentModelContextDescriptor = Object.getOwnPropertyDescriptor(doc, "modelContext");
519
+ defineDocumentModelContextProperty(doc, modelContext);
520
+ installState.installedDocumentModelContext = true;
521
+ }
522
+ if (nav) {
523
+ installState.previousNavigatorModelContextDescriptor = Object.getOwnPropertyDescriptor(nav, "modelContext");
524
+ installState.previousNavigatorModelContextTestingDescriptor = Object.getOwnPropertyDescriptor(nav, "modelContextTesting");
525
+ navigatorModelContextDeprecationWarned = false;
526
+ defineDeprecatedNavigatorModelContext(nav, modelContext);
527
+ installState.installedNavigatorModelContext = true;
528
+ const installTestingShim = options?.installTestingShim ?? "if-missing";
529
+ const hasModelContextTesting = Boolean(nav.modelContextTesting);
530
+ if (installTestingShim === "always" || (installTestingShim === true || installTestingShim === "if-missing") && !hasModelContextTesting) {
531
+ defineNavigatorProperty(nav, "modelContextTesting", context.getTestingShim());
532
+ installState.installedNavigatorModelContextTesting = true;
533
+ }
534
+ }
487
535
  installState.installed = true;
488
536
  }
489
537
  function cleanupWebMCPPolyfill() {
490
- const nav = getNavigator();
491
- if (!nav || !installState.installed) return;
492
- const restore = (key, previousDescriptor) => {
538
+ if (!installState.installed) return;
539
+ const restore = (target, key, previousDescriptor) => {
493
540
  if (previousDescriptor) {
494
- Object.defineProperty(nav, key, previousDescriptor);
541
+ Object.defineProperty(target, key, previousDescriptor);
495
542
  return;
496
543
  }
497
- delete nav[key];
544
+ delete target[key];
498
545
  };
499
- restore("modelContext", installState.previousModelContextDescriptor);
500
- restore("modelContextTesting", installState.previousModelContextTestingDescriptor);
546
+ const nav = getNavigator();
547
+ const doc = getDocument();
548
+ if (doc && installState.installedDocumentModelContext) restore(doc, "modelContext", installState.previousDocumentModelContextDescriptor);
549
+ if (nav && installState.installedNavigatorModelContext) restore(nav, "modelContext", installState.previousNavigatorModelContextDescriptor);
550
+ if (nav && installState.installedNavigatorModelContextTesting) restore(nav, "modelContextTesting", installState.previousNavigatorModelContextTestingDescriptor);
501
551
  installState.installed = false;
502
- installState.previousModelContextDescriptor = void 0;
503
- installState.previousModelContextTestingDescriptor = void 0;
552
+ installState.previousDocumentModelContextDescriptor = void 0;
553
+ installState.previousNavigatorModelContextDescriptor = void 0;
554
+ installState.previousNavigatorModelContextTestingDescriptor = void 0;
555
+ installState.installedDocumentModelContext = false;
556
+ installState.installedNavigatorModelContext = false;
557
+ installState.installedNavigatorModelContextTesting = false;
558
+ navigatorModelContextDeprecationWarned = false;
504
559
  }
505
560
  if (typeof window !== "undefined" && typeof document !== "undefined") {
506
561
  const options = window.__webMCPPolyfillOptions;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Schema, Validator } from '@cfworker/json-schema';\nimport type {\n InputSchema,\n JsonObject,\n ModelContext,\n ModelContextClient,\n ModelContextOptions,\n ModelContextRegisterToolOptions,\n ModelContextTesting,\n ModelContextTestingExecuteToolOptions,\n ModelContextTestingToolInfo,\n ModelContextToolReference,\n ToolDescriptor,\n ToolResponse,\n} from '@mcp-b/webmcp-types';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\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';\nconst DEFAULT_INPUT_SCHEMA: InputSchema = { type: 'object', properties: {} };\nconst STANDARD_JSON_SCHEMA_TARGETS = ['draft-2020-12', 'draft-07'] as const;\n\nconst POLYFILL_MARKER_PROPERTY = '__isWebMCPPolyfill' as const;\nconst STANDARD_VALIDATOR_SYMBOL = Symbol('standardValidator');\n\nexport type StandardInputValidatorSchema = StandardSchemaV1<\n Record<string, unknown>,\n Record<string, unknown>\n>;\nexport interface StandardJSONSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: { readonly input: Input; readonly output: Output } | undefined;\n readonly jsonSchema: {\n readonly input: (options: {\n readonly target: 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | ({} & string);\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }) => Record<string, unknown>;\n readonly output: (options: {\n readonly target: 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | ({} & string);\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }) => Record<string, unknown>;\n };\n };\n}\nexport type StandardInputJsonSchema = StandardJSONSchemaV1<\n Record<string, unknown>,\n Record<string, unknown>\n>;\nexport type ToolInputSchema = InputSchema | StandardInputValidatorSchema | StandardInputJsonSchema;\nexport type ToolOutputSchema = InputSchema | StandardInputJsonSchema;\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 NormalizedInputSchema {\n inputSchema: InputSchema;\n standardValidator: StandardInputValidatorSchema;\n}\n\ninterface InstallState {\n installed: boolean;\n previousModelContextDescriptor: PropertyDescriptor | undefined;\n previousModelContextTestingDescriptor: PropertyDescriptor | undefined;\n}\n\nconst installState: InstallState = {\n installed: false,\n previousModelContextDescriptor: undefined,\n previousModelContextTestingDescriptor: undefined,\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 provideContextDeprecationWarned = false;\n private clearContextDeprecationWarned = false;\n private unregisterToolDeprecationWarned = 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 provideContext(options: ModelContextOptions = {}): void {\n this.warnProvideContextDeprecationOnce();\n\n const nextTools = new Map<string, PolyfillToolDescriptor>();\n\n for (const tool of options.tools ?? []) {\n const normalized = normalizeToolDescriptor(tool, nextTools);\n nextTools.set(normalized.name, normalized);\n }\n\n this.tools = nextTools;\n this.notifyToolsChanged();\n }\n\n clearContext(): void {\n this.warnClearContextDeprecationOnce();\n\n this.tools.clear();\n this.notifyToolsChanged();\n }\n\n registerTool(tool: ToolDescriptor, options?: ModelContextRegisterToolOptions): void {\n const signal = options?.signal;\n\n if (signal?.aborted) {\n console.warn(\n `[WebMCPPolyfill] registerTool(\"${\n tool?.name ?? '<unknown>'\n }\") skipped: options.signal was already aborted.`\n );\n return;\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\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(): ModelContextTestingToolInfo[] {\n return this.getToolInfos();\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 PolyfillTestingShim */\n async executeToolForTesting(\n toolName: string,\n inputArgsJson: string,\n options?: ModelContextTestingExecuteToolOptions\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 return toSerializedTestingResult(normalizeToolResponse(rawResult));\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 queueMicrotask(() => {\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 warnProvideContextDeprecationOnce(): void {\n if (this.provideContextDeprecationWarned) {\n return;\n }\n\n this.provideContextDeprecationWarned = true;\n console.warn(\n '[WebMCPPolyfill] navigator.modelContext.provideContext() is deprecated and will be removed in the next major version. Register tools individually with registerTool() instead.'\n );\n }\n\n private warnClearContextDeprecationOnce(): void {\n if (this.clearContextDeprecationWarned) {\n return;\n }\n\n this.clearContextDeprecationWarned = true;\n console.warn(\n '[WebMCPPolyfill] navigator.modelContext.clearContext() is deprecated and will be removed in the next major version. Unregister individual tools instead.'\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 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\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction getStandardProps(value: unknown): Record<string, unknown> | null {\n if (!isPlainObject(value)) {\n return null;\n }\n\n const standard = value['~standard'];\n if (!isPlainObject(standard)) {\n return null;\n }\n\n return standard;\n}\n\nfunction isStandardInputValidatorSchema(value: unknown): value is StandardInputValidatorSchema {\n const standard = getStandardProps(value);\n return Boolean(standard && standard.version === 1 && typeof standard.validate === 'function');\n}\n\nfunction isStandardInputJsonSchema(value: unknown): value is StandardInputJsonSchema {\n const standard = getStandardProps(value);\n if (!standard || standard.version !== 1 || !isPlainObject(standard.jsonSchema)) {\n return false;\n }\n\n return typeof standard.jsonSchema.input === 'function';\n}\n\nfunction createStandardValidatorFromJsonSchema(schema: InputSchema): StandardInputValidatorSchema {\n return {\n '~standard': {\n version: 1,\n vendor: '@mcp-b/webmcp-polyfill-json-schema',\n validate(value: unknown): StandardValidationResult {\n if (!isPlainObject(value)) {\n return {\n issues: [{ message: 'expected object arguments' }],\n };\n }\n\n const issue = validateArgsWithSchema(value, schema);\n if (issue) {\n return {\n issues: [issue],\n };\n }\n\n return {\n value,\n };\n },\n },\n };\n}\n\nfunction convertStandardInputSchema(schema: StandardInputJsonSchema): InputSchema {\n for (const target of STANDARD_JSON_SCHEMA_TARGETS) {\n try {\n const converted = schema['~standard'].jsonSchema.input({ target });\n validateInputSchema(converted);\n return converted;\n } catch (error) {\n console.warn(\n `[WebMCPPolyfill] Standard JSON Schema conversion failed for target \"${target}\":`,\n error\n );\n }\n }\n\n throw new Error('Failed to convert Standard JSON Schema inputSchema to a JSON Schema object');\n}\n\nfunction normalizeInputSchema(inputSchema: ToolInputSchema | undefined): NormalizedInputSchema {\n if (inputSchema === undefined) {\n const normalized = DEFAULT_INPUT_SCHEMA;\n return {\n inputSchema: normalized,\n standardValidator: createStandardValidatorFromJsonSchema(normalized),\n };\n }\n\n if (isStandardInputJsonSchema(inputSchema)) {\n // Prefer JSON conversion for parity across JSON and Standard Schema inputs.\n const converted = convertStandardInputSchema(inputSchema);\n return {\n inputSchema: converted,\n standardValidator: createStandardValidatorFromJsonSchema(converted),\n };\n }\n\n if (isStandardInputValidatorSchema(inputSchema)) {\n return {\n inputSchema: DEFAULT_INPUT_SCHEMA,\n standardValidator: inputSchema,\n };\n }\n\n validateInputSchema(inputSchema);\n\n // Empty {} is valid JSON Schema but lacks type:\"object\" required by MCP.\n if (Object.keys(inputSchema as Record<string, unknown>).length === 0) {\n return {\n inputSchema: DEFAULT_INPUT_SCHEMA,\n standardValidator: createStandardValidatorFromJsonSchema(DEFAULT_INPUT_SCHEMA),\n };\n }\n\n const normalizedSchema =\n inputSchema.type === undefined\n ? ({ type: 'object', ...inputSchema } as InputSchema)\n : inputSchema;\n return {\n inputSchema: normalizedSchema,\n standardValidator: createStandardValidatorFromJsonSchema(normalizedSchema),\n };\n}\n\nfunction validateInputSchema(schema: unknown): asserts schema is InputSchema {\n if (!isPlainObject(schema)) {\n throw new Error('inputSchema must be a JSON Schema object');\n }\n\n validateJsonSchemaNode(schema, '$');\n}\n\nfunction validateJsonSchemaNode(node: Record<string, unknown>, path: string): void {\n const typeValue = node.type;\n if (\n typeValue !== undefined &&\n typeof typeValue !== 'string' &&\n !(\n Array.isArray(typeValue) &&\n typeValue.every((entry) => typeof entry === 'string' && entry.length > 0)\n )\n ) {\n throw new Error(`Invalid JSON Schema at ${path}: \"type\" must be a string or string[]`);\n }\n\n const requiredValue = node.required;\n if (\n requiredValue !== undefined &&\n !(Array.isArray(requiredValue) && requiredValue.every((entry) => typeof entry === 'string'))\n ) {\n throw new Error(`Invalid JSON Schema at ${path}: \"required\" must be an array of strings`);\n }\n\n const propertiesValue = node.properties;\n if (propertiesValue !== undefined) {\n if (!isPlainObject(propertiesValue)) {\n throw new Error(`Invalid JSON Schema at ${path}: \"properties\" must be an object`);\n }\n\n for (const [key, value] of Object.entries(propertiesValue)) {\n if (!isPlainObject(value)) {\n throw new Error(`Invalid JSON Schema at ${path}.properties.${key}: expected object schema`);\n }\n validateJsonSchemaNode(value, `${path}.properties.${key}`);\n }\n }\n\n const itemsValue = node.items;\n if (itemsValue !== undefined) {\n if (Array.isArray(itemsValue)) {\n for (const [index, value] of itemsValue.entries()) {\n if (!isPlainObject(value)) {\n throw new Error(`Invalid JSON Schema at ${path}.items[${index}]: expected object schema`);\n }\n validateJsonSchemaNode(value, `${path}.items[${index}]`);\n }\n } else if (isPlainObject(itemsValue)) {\n validateJsonSchemaNode(itemsValue, `${path}.items`);\n } else {\n throw new Error(`Invalid JSON Schema at ${path}: \"items\" must be an object or object[]`);\n }\n }\n\n for (const keyword of ['allOf', 'anyOf', 'oneOf'] as const) {\n const value = node[keyword];\n if (value === undefined) {\n continue;\n }\n\n if (!Array.isArray(value)) {\n throw new Error(`Invalid JSON Schema at ${path}: \"${keyword}\" must be an array`);\n }\n\n for (const [index, entry] of value.entries()) {\n if (!isPlainObject(entry)) {\n throw new Error(\n `Invalid JSON Schema at ${path}.${keyword}[${index}]: expected object schema`\n );\n }\n validateJsonSchemaNode(entry, `${path}.${keyword}[${index}]`);\n }\n }\n\n const notValue = node.not;\n if (notValue !== undefined) {\n if (!isPlainObject(notValue)) {\n throw new Error(`Invalid JSON Schema at ${path}: \"not\" must be an object schema`);\n }\n validateJsonSchemaNode(notValue, `${path}.not`);\n }\n\n try {\n JSON.stringify(node);\n } catch {\n throw new Error(`Invalid JSON Schema at ${path}: schema must be JSON-serializable`);\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 new TypeError('Tool \"name\" must be a non-empty string');\n }\n\n if (typeof tool.description !== 'string' || tool.description.length === 0) {\n throw new TypeError('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\nexport function validateArgsWithSchema(\n args: Record<string, unknown>,\n schema: InputSchema\n): StandardValidationIssue | null {\n const validator = new Validator(schema as Schema, '2020-12', true);\n const result = validator.validate(args);\n\n if (result.valid) {\n return null;\n }\n\n // Use the deepest (last) error for the most specific message.\n const error = result.errors[result.errors.length - 1];\n if (!error) {\n return { message: 'Input validation failed' };\n }\n\n return { message: error.error };\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 isCallToolResult(value: unknown): value is ToolResponse {\n return isPlainObject(value) && Array.isArray(value.content);\n}\n\nfunction isJsonPrimitive(value: unknown): value is string | number | boolean | null {\n return (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n}\n\nfunction isJsonValue(value: unknown): boolean {\n if (isJsonPrimitive(value)) {\n return Number.isFinite(value as number) || typeof value !== 'number';\n }\n\n if (Array.isArray(value)) {\n return value.every((entry) => isJsonValue(entry));\n }\n\n if (!isPlainObject(value)) {\n return false;\n }\n\n return Object.values(value).every((entry) => isJsonValue(entry));\n}\n\nfunction toStructuredContent(value: unknown): JsonObject | undefined {\n if (!isPlainObject(value) || !isJsonValue(value)) {\n return undefined;\n }\n\n return value as JsonObject;\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 = toStructuredContent(value);\n\n return {\n content: [\n {\n type: 'text',\n text: serializeTextContent(value),\n },\n ],\n ...(structuredContent ? { 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 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\nexport function initializeWebMCPPolyfill(options?: WebMCPPolyfillInitOptions): void {\n const nav = getNavigator();\n if (!nav) {\n return;\n }\n\n const hasModelContext = Boolean(nav.modelContext);\n\n if (hasModelContext) {\n return;\n }\n\n if (installState.installed) {\n cleanupWebMCPPolyfill();\n }\n\n const context = new StrictWebMCPContext();\n const modelContext = context as unknown as PolyfillModelContext;\n modelContext[POLYFILL_MARKER_PROPERTY] = true;\n\n installState.previousModelContextDescriptor = Object.getOwnPropertyDescriptor(\n nav,\n 'modelContext'\n );\n installState.previousModelContextTestingDescriptor = Object.getOwnPropertyDescriptor(\n nav,\n 'modelContextTesting'\n );\n\n defineNavigatorProperty(nav, 'modelContext', modelContext as Navigator['modelContext']);\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 }\n\n installState.installed = true;\n}\n\nexport function cleanupWebMCPPolyfill(): void {\n const nav = getNavigator();\n if (!nav || !installState.installed) {\n return;\n }\n\n const restore = <K extends keyof Navigator>(\n key: K,\n previousDescriptor: PropertyDescriptor | undefined\n ) => {\n if (previousDescriptor) {\n Object.defineProperty(nav, key, previousDescriptor);\n return;\n }\n\n delete (nav as unknown as Record<string, unknown>)[key as string];\n };\n\n restore('modelContext', installState.previousModelContextDescriptor);\n restore('modelContextTesting', installState.previousModelContextTestingDescriptor);\n\n installState.installed = false;\n installState.previousModelContextDescriptor = undefined;\n installState.previousModelContextTestingDescriptor = undefined;\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":";;;AAiBA,MAAM,0CAA0C;AAChD,MAAM,iCACJ;AACF,MAAM,yBAAyB;AAC/B,MAAM,uBAAoC;CAAE,MAAM;CAAU,YAAY,EAAE;CAAE;AAC5E,MAAM,+BAA+B,CAAC,iBAAiB,WAAW;AAElE,MAAM,2BAA2B;AACjC,MAAM,4BAA4B,OAAO,oBAAoB;AAuD7D,MAAM,eAA6B;CACjC,WAAW;CACX,gCAAgC;CAChC,uCAAuC;CACxC;AAyBD,IAAM,sBAAN,cAAkC,YAAY;CAC5C,AAAQ,wBAAQ,IAAI,KAAqC;CACzD,AAAQ,cAA0C;CAClD,AAAQ,gBAAqE;CAC7E,AAAQ,kCAAkC;CAC1C,AAAQ,gCAAgC;CACxC,AAAQ,kCAAkC;CAE1C,IAAI,eAAoE;AACtE,SAAO,KAAK;;CAGd,IAAI,aAAa,SAA8D;AAC7E,OAAK,gBAAgB;;CAGvB,eAAe,UAA+B,EAAE,EAAQ;AACtD,OAAK,mCAAmC;EAExC,MAAM,4BAAY,IAAI,KAAqC;AAE3D,OAAK,M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uBACG;AACH,MAAI,oBAAoB;AACtB,UAAO,eAAe,KAAK,KAAK,mBAAmB;AACnD;;AAGF,SAAQ,IAA2C;;AAGrD,SAAQ,gBAAgB,aAAa,+BAA+B;AACpE,SAAQ,uBAAuB,aAAa,sCAAsC;AAElF,cAAa,YAAY;AACzB,cAAa,iCAAiC;AAC9C,cAAa,wCAAwC;;AAWvD,IAAI,OAAO,WAAW,eAAe,OAAO,aAAa,aAAa;CACpE,MAAM,UAAU,OAAO;AAGvB,KAF6B,SAAS,mBAAmB,MAGvD,KAAI;AACF,2BAAyB,QAAQ;UAC1B,OAAO;AACd,UAAQ,MAAM,gDAAgD,MAAM"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Schema, Validator } from '@cfworker/json-schema';\nimport type {\n InputSchema,\n JsonObject,\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 type { StandardSchemaV1 } from '@standard-schema/spec';\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';\nconst DEFAULT_INPUT_SCHEMA: InputSchema = { type: 'object', properties: {} };\nconst STANDARD_JSON_SCHEMA_TARGETS = ['draft-2020-12', 'draft-07'] as const;\n\nconst POLYFILL_MARKER_PROPERTY = '__isWebMCPPolyfill' as const;\nconst STANDARD_VALIDATOR_SYMBOL = Symbol('standardValidator');\n\nexport type StandardInputValidatorSchema = StandardSchemaV1<\n Record<string, unknown>,\n Record<string, unknown>\n>;\nexport interface StandardJSONSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: { readonly input: Input; readonly output: Output } | undefined;\n readonly jsonSchema: {\n readonly input: (options: {\n readonly target: 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | ({} & string);\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }) => Record<string, unknown>;\n readonly output: (options: {\n readonly target: 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | ({} & string);\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }) => Record<string, unknown>;\n };\n };\n}\nexport type StandardInputJsonSchema = StandardJSONSchemaV1<\n Record<string, unknown>,\n Record<string, unknown>\n>;\nexport type ToolInputSchema = InputSchema | StandardInputValidatorSchema | StandardInputJsonSchema;\nexport type ToolOutputSchema = InputSchema | StandardInputJsonSchema;\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 NormalizedInputSchema {\n inputSchema: InputSchema;\n standardValidator: 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\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): void {\n const signal = options?.signal;\n\n if (signal?.aborted) {\n console.warn(\n `[WebMCPPolyfill] registerTool(\"${\n tool?.name ?? '<unknown>'\n }\") skipped: options.signal was already aborted.`\n );\n return;\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\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 if (normalizeResult) {\n return toSerializedTestingResult(normalizeToolResponse(rawResult));\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 queueMicrotask(() => {\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 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\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction getStandardProps(value: unknown): Record<string, unknown> | null {\n if (!isPlainObject(value)) {\n return null;\n }\n\n const standard = value['~standard'];\n if (!isPlainObject(standard)) {\n return null;\n }\n\n return standard;\n}\n\nfunction isStandardInputValidatorSchema(value: unknown): value is StandardInputValidatorSchema {\n const standard = getStandardProps(value);\n return Boolean(standard && standard.version === 1 && typeof standard.validate === 'function');\n}\n\nfunction isStandardInputJsonSchema(value: unknown): value is StandardInputJsonSchema {\n const standard = getStandardProps(value);\n if (!standard || standard.version !== 1 || !isPlainObject(standard.jsonSchema)) {\n return false;\n }\n\n return typeof standard.jsonSchema.input === 'function';\n}\n\nfunction createStandardValidatorFromJsonSchema(schema: InputSchema): StandardInputValidatorSchema {\n return {\n '~standard': {\n version: 1,\n vendor: '@mcp-b/webmcp-polyfill-json-schema',\n validate(value: unknown): StandardValidationResult {\n if (!isPlainObject(value)) {\n return {\n issues: [{ message: 'expected object arguments' }],\n };\n }\n\n const issue = validateArgsWithSchema(value, schema);\n if (issue) {\n return {\n issues: [issue],\n };\n }\n\n return {\n value,\n };\n },\n },\n };\n}\n\nfunction convertStandardInputSchema(schema: StandardInputJsonSchema): InputSchema {\n for (const target of STANDARD_JSON_SCHEMA_TARGETS) {\n try {\n const converted = schema['~standard'].jsonSchema.input({ target });\n validateInputSchema(converted);\n return converted;\n } catch (error) {\n console.warn(\n `[WebMCPPolyfill] Standard JSON Schema conversion failed for target \"${target}\":`,\n error\n );\n }\n }\n\n throw new Error('Failed to convert Standard JSON Schema inputSchema to a JSON Schema object');\n}\n\nfunction normalizeInputSchema(inputSchema: ToolInputSchema | undefined): NormalizedInputSchema {\n if (inputSchema === undefined) {\n const normalized = DEFAULT_INPUT_SCHEMA;\n return {\n inputSchema: normalized,\n standardValidator: createStandardValidatorFromJsonSchema(normalized),\n };\n }\n\n if (isStandardInputJsonSchema(inputSchema)) {\n // Prefer JSON conversion for parity across JSON and Standard Schema inputs.\n const converted = convertStandardInputSchema(inputSchema);\n return {\n inputSchema: converted,\n standardValidator: createStandardValidatorFromJsonSchema(converted),\n };\n }\n\n if (isStandardInputValidatorSchema(inputSchema)) {\n return {\n inputSchema: DEFAULT_INPUT_SCHEMA,\n standardValidator: inputSchema,\n };\n }\n\n validateInputSchema(inputSchema);\n\n // Empty {} is valid JSON Schema but lacks type:\"object\" required by MCP.\n if (Object.keys(inputSchema as Record<string, unknown>).length === 0) {\n return {\n inputSchema: DEFAULT_INPUT_SCHEMA,\n standardValidator: createStandardValidatorFromJsonSchema(DEFAULT_INPUT_SCHEMA),\n };\n }\n\n const normalizedSchema =\n inputSchema.type === undefined\n ? ({ type: 'object', ...inputSchema } as InputSchema)\n : inputSchema;\n return {\n inputSchema: normalizedSchema,\n standardValidator: createStandardValidatorFromJsonSchema(normalizedSchema),\n };\n}\n\nfunction validateInputSchema(schema: unknown): asserts schema is InputSchema {\n if (!isPlainObject(schema)) {\n throw new Error('inputSchema must be a JSON Schema object');\n }\n\n validateJsonSchemaNode(schema, '$');\n}\n\nfunction validateJsonSchemaNode(node: Record<string, unknown>, path: string): void {\n const typeValue = node.type;\n if (\n typeValue !== undefined &&\n typeof typeValue !== 'string' &&\n !(\n Array.isArray(typeValue) &&\n typeValue.every((entry) => typeof entry === 'string' && entry.length > 0)\n )\n ) {\n throw new Error(`Invalid JSON Schema at ${path}: \"type\" must be a string or string[]`);\n }\n\n const requiredValue = node.required;\n if (\n requiredValue !== undefined &&\n !(Array.isArray(requiredValue) && requiredValue.every((entry) => typeof entry === 'string'))\n ) {\n throw new Error(`Invalid JSON Schema at ${path}: \"required\" must be an array of strings`);\n }\n\n const propertiesValue = node.properties;\n if (propertiesValue !== undefined) {\n if (!isPlainObject(propertiesValue)) {\n throw new Error(`Invalid JSON Schema at ${path}: \"properties\" must be an object`);\n }\n\n for (const [key, value] of Object.entries(propertiesValue)) {\n if (!isPlainObject(value)) {\n throw new Error(`Invalid JSON Schema at ${path}.properties.${key}: expected object schema`);\n }\n validateJsonSchemaNode(value, `${path}.properties.${key}`);\n }\n }\n\n const itemsValue = node.items;\n if (itemsValue !== undefined) {\n if (Array.isArray(itemsValue)) {\n for (const [index, value] of itemsValue.entries()) {\n if (!isPlainObject(value)) {\n throw new Error(`Invalid JSON Schema at ${path}.items[${index}]: expected object schema`);\n }\n validateJsonSchemaNode(value, `${path}.items[${index}]`);\n }\n } else if (isPlainObject(itemsValue)) {\n validateJsonSchemaNode(itemsValue, `${path}.items`);\n } else {\n throw new Error(`Invalid JSON Schema at ${path}: \"items\" must be an object or object[]`);\n }\n }\n\n for (const keyword of ['allOf', 'anyOf', 'oneOf'] as const) {\n const value = node[keyword];\n if (value === undefined) {\n continue;\n }\n\n if (!Array.isArray(value)) {\n throw new Error(`Invalid JSON Schema at ${path}: \"${keyword}\" must be an array`);\n }\n\n for (const [index, entry] of value.entries()) {\n if (!isPlainObject(entry)) {\n throw new Error(\n `Invalid JSON Schema at ${path}.${keyword}[${index}]: expected object schema`\n );\n }\n validateJsonSchemaNode(entry, `${path}.${keyword}[${index}]`);\n }\n }\n\n const notValue = node.not;\n if (notValue !== undefined) {\n if (!isPlainObject(notValue)) {\n throw new Error(`Invalid JSON Schema at ${path}: \"not\" must be an object schema`);\n }\n validateJsonSchemaNode(notValue, `${path}.not`);\n }\n\n try {\n JSON.stringify(node);\n } catch {\n throw new Error(`Invalid JSON Schema at ${path}: schema must be JSON-serializable`);\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 new TypeError('Tool \"name\" must be a non-empty string');\n }\n\n if (typeof tool.description !== 'string' || tool.description.length === 0) {\n throw new TypeError('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\nexport function validateArgsWithSchema(\n args: Record<string, unknown>,\n schema: InputSchema\n): StandardValidationIssue | null {\n const validator = new Validator(schema as Schema, '2020-12', true);\n const result = validator.validate(args);\n\n if (result.valid) {\n return null;\n }\n\n // Use the deepest (last) error for the most specific message.\n const error = result.errors[result.errors.length - 1];\n if (!error) {\n return { message: 'Input validation failed' };\n }\n\n return { message: error.error };\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 isCallToolResult(value: unknown): value is ToolResponse {\n return isPlainObject(value) && Array.isArray(value.content);\n}\n\nfunction isJsonPrimitive(value: unknown): value is string | number | boolean | null {\n return (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n}\n\nfunction isJsonValue(value: unknown): boolean {\n if (isJsonPrimitive(value)) {\n return Number.isFinite(value as number) || typeof value !== 'number';\n }\n\n if (Array.isArray(value)) {\n return value.every((entry) => isJsonValue(entry));\n }\n\n if (!isPlainObject(value)) {\n return false;\n }\n\n return Object.values(value).every((entry) => isJsonValue(entry));\n}\n\nfunction toStructuredContent(value: unknown): JsonObject | undefined {\n if (!isPlainObject(value) || !isJsonValue(value)) {\n return undefined;\n }\n\n return value as JsonObject;\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 = toStructuredContent(value);\n\n return {\n content: [\n {\n type: 'text',\n text: serializeTextContent(value),\n },\n ],\n ...(structuredContent ? { 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":";;;AAiBA,MAAM,0CAA0C;AAChD,MAAM,iCACJ;AACF,MAAM,yBAAyB;AAC/B,MAAM,uBAAoC;CAAE,MAAM;CAAU,YAAY,EAAE;CAAE;AAC5E,MAAM,+BAA+B,CAAC,iBAAiB,WAAW;AAElE,MAAM,2BAA2B;AACjC,MAAM,4BAA4B,OAAO,oBAAoB;AA2D7D,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;CAE1C,IAAI,eAAoE;EACtE,OAAO,KAAK;;CAGd,IAAI,aAAa,SAA8D;EAC7E,KAAK,gBAAgB;;CAGvB,aAAa,MAAsB,SAAiD;EAClF,MAAM,SAAS,SAAS;EAExB,IAAI,QAAQ,SAAS;GACnB,QAAQ,KACN,kCACE,MAAM,QAAQ,YACf,iDACF;GACD;;EAGF,MAAM,aAAa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D,aAAa,gCAAgC;CAC7C,aAAa,iCAAiC;CAC9C,aAAa,wCAAwC;CACrD,yCAAyC;;AAW3C,IAAI,OAAO,WAAW,eAAe,OAAO,aAAa,aAAa;CACpE,MAAM,UAAU,OAAO;CAGvB,IAF6B,SAAS,mBAAmB,OAGvD,IAAI;EACF,yBAAyB,QAAQ;UAC1B,OAAO;EACd,QAAQ,MAAM,gDAAgD,MAAM"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mcp-b/webmcp-polyfill",
3
- "version": "2.3.2",
4
- "description": "Strict WebMCP core runtime polyfill for navigator.modelContext",
3
+ "version": "3.0.0",
4
+ "description": "Strict WebMCP core runtime polyfill for document.modelContext (with deprecated navigator.modelContext alias)",
5
5
  "keywords": [
6
6
  "browser",
7
7
  "model-context",
@@ -47,14 +47,14 @@
47
47
  "dependencies": {
48
48
  "@cfworker/json-schema": "^4.1.1",
49
49
  "@standard-schema/spec": "^1.1.0",
50
- "@mcp-b/webmcp-types": "2.3.2"
50
+ "@mcp-b/webmcp-types": "3.0.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@vitest/coverage-v8": "^4.1.0",
53
+ "@vitest/coverage-v8": "^4.1.7",
54
54
  "happy-dom": "^20.8.9",
55
- "playwright": "^1.58.0",
55
+ "playwright": "^1.60.0",
56
56
  "typescript": "^5.8.3",
57
- "vite-plus": "latest",
57
+ "vite-plus": "^0.1.22",
58
58
  "vitest": "npm:@voidzero-dev/vite-plus-test@latest"
59
59
  },
60
60
  "engines": {