@mcp-b/webmcp-polyfill 2.1.0 → 2.3.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 +42 -16
- package/dist/index.d.ts +1 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.iife.js +2 -2
- package/dist/index.js +122 -27
- package/dist/index.js.map +1 -1
- package/package.json +30 -32
package/README.md
CHANGED
|
@@ -4,10 +4,10 @@ Strict WebMCP core runtime polyfill for `navigator.modelContext`.
|
|
|
4
4
|
|
|
5
5
|
`@mcp-b/webmcp-polyfill` installs only the strict core API:
|
|
6
6
|
|
|
7
|
-
- `
|
|
8
|
-
- `
|
|
9
|
-
- `
|
|
10
|
-
- `clearContext()`
|
|
7
|
+
- `registerTool(tool, options?)` — pass `options.signal` (`AbortSignal`) to unregister when aborted
|
|
8
|
+
- `unregisterTool(nameOrTool)` (deprecated compatibility API)
|
|
9
|
+
- `provideContext(options?)` (deprecated compatibility API)
|
|
10
|
+
- `clearContext()` (deprecated compatibility API)
|
|
11
11
|
|
|
12
12
|
It does not install MCP bridge extensions like `callTool`, resources, or prompts.
|
|
13
13
|
|
|
@@ -15,6 +15,8 @@ Important:
|
|
|
15
15
|
|
|
16
16
|
- `navigator.modelContext` in this package does not provide `listTools()` or `callTool(...)`.
|
|
17
17
|
- 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.
|
|
19
|
+
- `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.
|
|
18
20
|
|
|
19
21
|
## Type Safety First
|
|
20
22
|
|
|
@@ -28,11 +30,11 @@ Recommended setup:
|
|
|
28
30
|
|
|
29
31
|
## Package Selection
|
|
30
32
|
|
|
31
|
-
| Package
|
|
32
|
-
|
|
|
33
|
-
| `@mcp-b/webmcp-types`
|
|
33
|
+
| Package | Use When |
|
|
34
|
+
| ------------------------ | ---------------------------------------------------------- |
|
|
35
|
+
| `@mcp-b/webmcp-types` | You only need compile-time types (no runtime) |
|
|
34
36
|
| `@mcp-b/webmcp-polyfill` | You need strict `navigator.modelContext` core runtime only |
|
|
35
|
-
| `@mcp-b/global`
|
|
37
|
+
| `@mcp-b/global` | You want full MCPB runtime (core + bridge extensions) |
|
|
36
38
|
|
|
37
39
|
## Install
|
|
38
40
|
|
|
@@ -119,11 +121,11 @@ Inference notes:
|
|
|
119
121
|
|
|
120
122
|
Installs the strict core polyfill on `navigator.modelContext`.
|
|
121
123
|
|
|
122
|
-
| Option
|
|
123
|
-
|
|
|
124
|
-
| `autoInitialize`
|
|
125
|
-
| `installTestingShim`
|
|
126
|
-
| `disableIframeTransportByDefault` | `boolean`
|
|
124
|
+
| Option | Type | Default | Notes |
|
|
125
|
+
| --------------------------------- | ------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------ |
|
|
126
|
+
| `autoInitialize` | `boolean` | `true` | Used by auto-init flows (IIFE/import side effect). Set `false` to disable auto-init and initialize manually. |
|
|
127
|
+
| `installTestingShim` | `boolean \| 'always' \| 'if-missing'` | `'if-missing'` | Controls whether `navigator.modelContextTesting` is installed. |
|
|
128
|
+
| `disableIframeTransportByDefault` | `boolean` | n/a | Deprecated no-op, kept for compatibility. |
|
|
127
129
|
|
|
128
130
|
Behavior:
|
|
129
131
|
|
|
@@ -143,22 +145,44 @@ Restores previous `navigator.modelContext` and `navigator.modelContextTesting` d
|
|
|
143
145
|
|
|
144
146
|
### `provideContext(options?)`
|
|
145
147
|
|
|
148
|
+
- Deprecated compatibility API.
|
|
146
149
|
- Replaces the active tool registry with `options.tools`.
|
|
147
150
|
- Clears previously registered tools before applying new tools.
|
|
148
151
|
|
|
149
|
-
### `registerTool(tool)`
|
|
152
|
+
### `registerTool(tool, options?)`
|
|
150
153
|
|
|
151
154
|
- Requires a non-empty `name`, non-empty `description`, and `execute` function.
|
|
152
155
|
- Throws on duplicate tool names.
|
|
153
156
|
- If `inputSchema` is omitted, runtime defaults to `{ type: 'object', properties: {} }`.
|
|
157
|
+
- `options.signal` (optional `AbortSignal`) — when the signal aborts, the tool is unregistered. If the signal is already aborted at registration time, the polyfill skips the registration and logs a warning (matching the April 23, 2026 spec step).
|
|
154
158
|
|
|
155
|
-
|
|
159
|
+
```ts
|
|
160
|
+
const ac = new AbortController();
|
|
161
|
+
navigator.modelContext.registerTool(
|
|
162
|
+
{
|
|
163
|
+
name: 'search',
|
|
164
|
+
description: 'Search docs',
|
|
165
|
+
inputSchema: { type: 'object', properties: {} },
|
|
166
|
+
async execute() {
|
|
167
|
+
return { content: [{ type: 'text', text: 'ok' }] };
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
{ signal: ac.signal }
|
|
171
|
+
);
|
|
156
172
|
|
|
157
|
-
|
|
173
|
+
// Later — unregister cleanly:
|
|
174
|
+
ac.abort();
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### `unregisterTool(nameOrTool)` (deprecated)
|
|
178
|
+
|
|
179
|
+
- Removes a tool by name. MCP-B compatibility runtimes also accept the originally registered tool object.
|
|
158
180
|
- Unknown names are a no-op.
|
|
181
|
+
- Logs a one-time deprecation warning. Prefer the `AbortSignal` form on `registerTool(tool, options)`.
|
|
159
182
|
|
|
160
183
|
### `clearContext()`
|
|
161
184
|
|
|
185
|
+
- Deprecated compatibility API.
|
|
162
186
|
- Removes all registered tools.
|
|
163
187
|
|
|
164
188
|
## Listing and Executing Tools
|
|
@@ -206,6 +230,8 @@ When enabled via `installTestingShim`, the polyfill can install a compatibility
|
|
|
206
230
|
- `registerToolsChangedCallback(callback)`
|
|
207
231
|
- `getCrossDocumentScriptToolResult()`
|
|
208
232
|
|
|
233
|
+
Older native previews also exposed `navigator.modelContextTesting.ontoolchange`; the polyfill keeps the callback-based compatibility API for now.
|
|
234
|
+
|
|
209
235
|
`executeTool(...)` accepts JSON-string arguments and returns a serialized result string or `null` (for navigation-style responses).
|
|
210
236
|
|
|
211
237
|
## Interop with `@mcp-b/global`
|
package/dist/index.d.ts
CHANGED
|
@@ -56,8 +56,7 @@ declare global {
|
|
|
56
56
|
interface Window {
|
|
57
57
|
__webMCPPolyfillOptions?: WebMCPPolyfillInitOptions;
|
|
58
58
|
}
|
|
59
|
-
}
|
|
60
|
-
//# sourceMappingURL=index.d.ts.map
|
|
59
|
+
} //# sourceMappingURL=index.d.ts.map
|
|
61
60
|
//#endregion
|
|
62
61
|
export { StandardInputJsonSchema, StandardInputValidatorSchema, StandardJSONSchemaV1, ToolInputSchema, ToolOutputSchema, WebMCPPolyfillInitOptions, cleanupWebMCPPolyfill, initializeWebMCPPolyfill, initializeWebMCPPolyfill as initializeWebModelContextPolyfill, isPlainObject, validateArgsWithSchema };
|
|
63
62
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"
|
|
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,GAA0B,WAAA,CAAY,wBAAA;AAAA,UA4B1B,yBAAA;EAvDqB;;;;;EA6DpC,cAAA;EAzDW;;;;;;;EAkEX,kBAAA;EA9De;;;EAmEf,+BAAA;AAAA;AAAA,iBAsTc,aAAA,CAAc,KAAA,YAAiB,KAAA,IAAS,MAAA;AAAA,iBAmRxC,sBAAA,CACd,IAAA,EAAM,MAAA,mBACN,MAAA,EAAQ,WAAA,GACP,uBAAA;AAAA,iBAsOa,wBAAA,CAAyB,OAAA,GAAU,yBAAA;AAAA,iBAiDnC,qBAAA,CAAA;AAAA,QA4BR,MAAA;EAAA,UACI,MAAA;IACR,uBAAA,GAA0B,yBAAA;EAAA;AAAA"}
|
package/dist/index.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var WebMCPPolyfill=(function(e){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](?:[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\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,m=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
|
|
2
|
-
- `)}`,Error(e)}let n=`${u}/$ref`,r=j(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(_)){let t=_.length,n=!1;for(let r=0;r<t;r++)if(p===_[r]||_[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 "${_.join(`", "`)}".`})}else _===`integer`?(p!==`number`||e%1||e!==e)&&Q.push({instanceLocation:l,keyword:`type`,keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${_}".`}):_!==void 0&&p!==_&&Q.push({instanceLocation:l,keyword:`type`,keywordLocation:`${u}/type`,error:`Instance type "${p}" is invalid. Expected "${_}".`});if(v!==void 0&&(p===`object`||p===`array`?t(e,v)||Q.push({instanceLocation:l,keyword:`const`,keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(v)}.`}):e!==v&&Q.push({instanceLocation:l,keyword:`const`,keywordLocation:`${u}/const`,error:`Instance does not match ${JSON.stringify(v)}.`})),y!==void 0&&(p===`object`||p===`array`?y.some(n=>t(e,n))||Q.push({instanceLocation:l,keyword:`enum`,keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`}):y.some(t=>e===t)||Q.push({instanceLocation:l,keyword:`enum`,keywordLocation:`${u}/enum`,error:`Instance does not match any of ${JSON.stringify(y)}.`})),te!==void 0){let t=`${u}/not`;j(e,te,i,a,o,s,l,t).valid&&Q.push({instanceLocation:l,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let $=[];if(b!==void 0){let t=`${u}/anyOf`,n=Q.length,r=!1;for(let n=0;n<b.length;n++){let c=b[n],u=Object.create(d),f=j(e,c,i,a,o,g===!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(x!==void 0){let t=`${u}/allOf`,n=Q.length,r=!0;for(let n=0;n<x.length;n++){let c=x[n],u=Object.create(d),f=j(e,c,i,a,o,g===!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(S!==void 0){let t=`${u}/oneOf`,n=Q.length,r=S.filter((n,r)=>{let c=Object.create(d),u=j(e,n,i,a,o,g===!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,...$),C!==void 0){let t=`${u}/if`;if(j(e,C,i,a,o,s,l,t,d).valid){if(w!==void 0){let n=j(e,w,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(T!==void 0){let n=j(e,T,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(ee!==void 0)for(let t of ee)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(k!==void 0&&t.length<k&&Q.push({instanceLocation:l,keyword:`minProperties`,keywordLocation:`${u}/minProperties`,error:`Instance does not have at least ${k} properties.`}),A!==void 0&&t.length>A&&Q.push({instanceLocation:l,keyword:`maxProperties`,keywordLocation:`${u}/maxProperties`,error:`Instance does not have at least ${A} properties.`}),oe!==void 0){let t=`${u}/propertyNames`;for(let r in e){let e=`${l}/${n(r)}`,c=j(r,oe,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(M!==void 0){let t=`${u}/dependantRequired`;for(let n in M)if(n in e){let r=M[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(N!==void 0)for(let t in N){let r=`${u}/dependentSchemas`;if(t in e){let c=j(e,N[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(P!==void 0){let t=`${u}/dependencies`;for(let r in P)if(r in e){let c=P[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=j(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(D!==void 0){let t=`${u}/properties`;for(let u in D){if(!(u in e))continue;let f=`${l}/${n(u)}`,p=j(e[u],D[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&&O!==void 0){let t=`${u}/patternProperties`;for(let u in O){let f=new RegExp(u,`u`),p=O[u];for(let m in e){if(!f.test(m))continue;let h=`${l}/${n(m)}`,g=j(e[m],p,i,a,o,s,h,`${t}/${n(u)}`);g.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.`},...g.errors))}}}if(!c&&re!==void 0){let t=`${u}/additionalProperties`;for(let u in e){if(r[u])continue;let f=`${l}/${n(u)}`,p=j(e[u],re,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&&ie!==void 0){let t=`${u}/unevaluatedProperties`;for(let r in e)if(!d[r]){let c=`${l}/${n(r)}`,u=j(e[r],ie,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`){H!==void 0&&e.length>H&&Q.push({instanceLocation:l,keyword:`maxItems`,keywordLocation:`${u}/maxItems`,error:`Array has too many items (${e.length} > ${H}).`}),V!==void 0&&e.length<V&&Q.push({instanceLocation:l,keyword:`minItems`,keywordLocation:`${u}/minItems`,error:`Array has too few items (${e.length} < ${V}).`});let n=e.length,r=0,c=!1;if(F!==void 0){let t=`${u}/prefixItems`,f=Math.min(F.length,n);for(;r<f;r++){let n=j(e[r],F[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(I!==void 0){let t=`${u}/items`;if(Array.isArray(I)){let u=Math.min(I.length,n);for(;r<u;r++){let n=j(e[r],I[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=j(e[r],I,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&&L!==void 0){let t=`${u}/additionalItems`;for(;r<n;r++){let n=j(e[r],L,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(se!==void 0)if(n===0&&z===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(z!==void 0&&n<z)Q.push({instanceLocation:l,keyword:`minContains`,keywordLocation:`${u}/minContains`,error:`Array has less items (${n}) than minContains (${z}).`});else{let t=`${u}/contains`,r=Q.length,c=0;for(let r=0;r<n;r++){let n=j(e[r],se,i,a,o,s,`${l}/${r}`,t);n.valid?(d[r]=!0,c++):Q.push(...n.errors)}c>=(z||0)&&(Q.length=r),z===void 0&&B===void 0&&c===0?Q.splice(r,0,{instanceLocation:l,keyword:`contains`,keywordLocation:t,error:`Array does not contain item matching schema.`}):z!==void 0&&c<z?Q.push({instanceLocation:l,keyword:`minContains`,keywordLocation:`${u}/minContains`,error:`Array must contain at least ${z} items matching schema. Only ${c} items were found.`}):B!==void 0&&c>B&&Q.push({instanceLocation:l,keyword:`maxContains`,keywordLocation:`${u}/maxContains`,error:`Array may contain at most ${B} items matching schema. ${c} items were found.`})}if(!c&&R!==void 0){let t=`${u}/unevaluatedItems`;for(;r<n;r++){if(d[r])continue;let n=j(e[r],R,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(ce)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`?(U!==void 0&&(G===!0&&e<=U||e<U)&&Q.push({instanceLocation:l,keyword:`minimum`,keywordLocation:`${u}/minimum`,error:`${e} is less than ${G?`or equal to `:``} ${U}.`}),W!==void 0&&(K===!0&&e>=W||e>W)&&Q.push({instanceLocation:l,keyword:`maximum`,keywordLocation:`${u}/maximum`,error:`${e} is greater than ${K?`or equal to `:``} ${W}.`})):(U!==void 0&&e<U&&Q.push({instanceLocation:l,keyword:`minimum`,keywordLocation:`${u}/minimum`,error:`${e} is less than ${U}.`}),W!==void 0&&e>W&&Q.push({instanceLocation:l,keyword:`maximum`,keywordLocation:`${u}/maximum`,error:`${e} is greater than ${W}.`}),G!==void 0&&e<=G&&Q.push({instanceLocation:l,keyword:`exclusiveMinimum`,keywordLocation:`${u}/exclusiveMinimum`,error:`${e} is less than ${G}.`}),K!==void 0&&e>=K&&Q.push({instanceLocation:l,keyword:`exclusiveMaximum`,keywordLocation:`${u}/exclusiveMaximum`,error:`${e} is greater than or equal to ${K}.`})),q!==void 0){let t=e%q;Math.abs(0-t)>=1.1920929e-7&&Math.abs(q-t)>=1.1920929e-7&&Q.push({instanceLocation:l,keyword:`multipleOf`,keywordLocation:`${u}/multipleOf`,error:`${e} is not a multiple of ${q}.`})}}else if(p===`string`){let t=J===void 0&&Y===void 0?0:ae(e);J!==void 0&&t<J&&Q.push({instanceLocation:l,keyword:`minLength`,keywordLocation:`${u}/minLength`,error:`String is too short (${t} < ${J}).`}),Y!==void 0&&t>Y&&Q.push({instanceLocation:l,keyword:`maxLength`,keywordLocation:`${u}/maxLength`,error:`String is too long (${t} > ${Y}).`}),X!==void 0&&!new RegExp(X,`u`).test(e)&&Q.push({instanceLocation:l,keyword:`pattern`,keywordLocation:`${u}/pattern`,error:`String does not match pattern.`}),E!==void 0&&ne[E]&&!ne[E](e)&&Q.push({instanceLocation:l,keyword:`format`,keywordLocation:`${u}/format`,error:`String does not match format "${E}".`})}return{valid:Q.length===0,errors:Q}}var oe=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 j(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),c(e,this.lookup)}};let M=`Failed to parse input arguments`,N=`Tool was executed but the invocation failed. For example, the script function threw an error`,P=`Tool was cancelled`,F={type:`object`,properties:{}},I=[`draft-2020-12`,`draft-07`],L=Symbol(`standardValidator`),R={installed:!1,previousModelContextDescriptor:void 0,previousModelContextTestingDescriptor:void 0};var se=class{tools=new Map;toolsChangedCallback=null;provideContext(e={}){let t=new Map;for(let n of e.tools??[]){let e=Y(n,t);t.set(e.name,e)}this.tools=t,this.notifyToolsChanged()}clearContext(){this.tools.clear(),this.notifyToolsChanged()}registerTool(e){let t=Y(e,this.tools);this.tools.set(t.name,t),this.notifyToolsChanged()}unregisterTool(e){this.tools.delete(e)&&this.notifyToolsChanged()}getTestingShim(){return{listTools:()=>[...this.tools.values()].map(e=>{let t={name:e.name,description:e.description};try{t.inputSchema=JSON.stringify(e.inputSchema)}catch{}return t}),executeTool:(e,t,n)=>this.executeToolForTesting(e,t,n),registerToolsChangedCallback:e=>{if(typeof e!=`function`)throw TypeError(`Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.`);this.toolsChangedCallback=e},getCrossDocumentScriptToolResult:async()=>`[]`}}async executeToolForTesting(e,t,n){if(n?.signal?.aborted)throw z(P);let r=this.tools.get(e);if(!r)throw z(`Tool not found: ${e}`);let i=B(t),a=await Q(i,r);if(a)throw z(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 ge(me(await _e(Promise.resolve(e),n?.signal)))}catch(e){throw z(e instanceof Error?`${N}: ${e.message}`:N)}finally{o=!1}}notifyToolsChanged(){this.toolsChangedCallback&&queueMicrotask(()=>{try{this.toolsChangedCallback?.()}catch(e){console.warn(`[WebMCPPolyfill] toolsChanged callback threw:`,e)}})}};function z(e){try{return new DOMException(e,`UnknownError`)}catch{let t=Error(e);return t.name=`UnknownError`,t}}function B(e){let t;try{t=JSON.parse(e)}catch{throw z(M)}if(!t||typeof t!=`object`||Array.isArray(t))throw z(M);return t}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 ce(e){let t=H(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function U(e){let t=H(e);return!t||t.version!==1||!V(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function W(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=X(t,e);return n?{issues:[n]}:{value:t}}}}}function G(e){for(let t of I)try{let n=e[`~standard`].jsonSchema.input({target:t});return q(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 K(e){if(e===void 0){let e=F;return{inputSchema:e,standardValidator:W(e)}}if(U(e)){let t=G(e);return{inputSchema:t,standardValidator:W(t)}}if(ce(e))return{inputSchema:F,standardValidator:e};if(q(e),Object.keys(e).length===0)return{inputSchema:F,standardValidator:W(F)};let t=e.type===void 0?{type:`object`,...e}:e;return{inputSchema:t,standardValidator:W(t)}}function q(e){if(!V(e))throw Error(`inputSchema must be a JSON Schema object`);J(e,`$`)}function J(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`);J(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`);J(n,`${t}.items[${e}]`)}else if(V(a))J(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`);J(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`);J(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function Y(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=K(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,[L]:n.standardValidator}}function X(e,t){let n=new oe(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 le(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 Q(e,t){return le(e,t[L])}function $(e){return V(e)&&Array.isArray(e.content)}function ue(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function de(e){return ue(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>de(e)):V(e)?Object.values(e).every(e=>de(e)):!1}function fe(e){if(!(!V(e)||!de(e)))return e}function pe(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function me(e){if($(e))return e;let t=fe(e);return{content:[{type:`text`,text:pe(e)}],...t?{structuredContent:t}:{},isError:!1}}function he(e){for(let t of e.content??[])if(t.type===`text`&&`text`in t&&typeof t.text==`string`)return t.text;return null}function ge(e){if(e.isError)throw z(he(e)?.replace(/^Error:\s*/i,``).trim()||N);let t=e.metadata;if(t&&typeof t==`object`&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw z(N)}}function _e(e,t){return t?t.aborted?Promise.reject(z(P)):new Promise((n,r)=>{let i=()=>{a(),r(z(P))},a=()=>{t.removeEventListener(`abort`,i)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}function ve(){return typeof navigator<`u`?navigator:null}function ye(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function be(e){let t=ve();if(!t||t.modelContext)return;R.installed&&xe();let n=new se,r=n;r.__isWebMCPPolyfill=!0,R.previousModelContextDescriptor=Object.getOwnPropertyDescriptor(t,`modelContext`),R.previousModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,`modelContextTesting`),ye(t,`modelContext`,r);let i=e?.installTestingShim??`if-missing`,a=!!t.modelContextTesting;(i===`always`||(i===!0||i===`if-missing`)&&!a)&&ye(t,`modelContextTesting`,n.getTestingShim()),R.installed=!0}function xe(){let e=ve();if(!e||!R.installed)return;let t=(t,n)=>{if(n){Object.defineProperty(e,t,n);return}delete e[t]};t(`modelContext`,R.previousModelContextDescriptor),t(`modelContextTesting`,R.previousModelContextTestingDescriptor),R.installed=!1,R.previousModelContextDescriptor=void 0,R.previousModelContextTestingDescriptor=void 0}if(typeof window<`u`&&typeof document<`u`){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{be(e)}catch(e){console.error(`[WebMCPPolyfill] Auto-initialization failed:`,e)}}return e.cleanupWebMCPPolyfill=xe,e.initializeWebMCPPolyfill=be,e.initializeWebModelContextPolyfill=be,e.isPlainObject=V,e.validateArgsWithSchema=X,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}|(?:(?:[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}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+)(?:\.(?:[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})({});
|
package/dist/index.js
CHANGED
|
@@ -16,10 +16,21 @@ const installState = {
|
|
|
16
16
|
previousModelContextDescriptor: void 0,
|
|
17
17
|
previousModelContextTestingDescriptor: void 0
|
|
18
18
|
};
|
|
19
|
-
var StrictWebMCPContext = class {
|
|
19
|
+
var StrictWebMCPContext = class extends EventTarget {
|
|
20
20
|
tools = /* @__PURE__ */ new Map();
|
|
21
|
-
|
|
21
|
+
testingShim = null;
|
|
22
|
+
_ontoolchange = null;
|
|
23
|
+
provideContextDeprecationWarned = false;
|
|
24
|
+
clearContextDeprecationWarned = false;
|
|
25
|
+
unregisterToolDeprecationWarned = false;
|
|
26
|
+
get ontoolchange() {
|
|
27
|
+
return this._ontoolchange;
|
|
28
|
+
}
|
|
29
|
+
set ontoolchange(handler) {
|
|
30
|
+
this._ontoolchange = handler;
|
|
31
|
+
}
|
|
22
32
|
provideContext(options = {}) {
|
|
33
|
+
this.warnProvideContextDeprecationOnce();
|
|
23
34
|
const nextTools = /* @__PURE__ */ new Map();
|
|
24
35
|
for (const tool of options.tools ?? []) {
|
|
25
36
|
const normalized = normalizeToolDescriptor(tool, nextTools);
|
|
@@ -29,39 +40,52 @@ var StrictWebMCPContext = class {
|
|
|
29
40
|
this.notifyToolsChanged();
|
|
30
41
|
}
|
|
31
42
|
clearContext() {
|
|
43
|
+
this.warnClearContextDeprecationOnce();
|
|
32
44
|
this.tools.clear();
|
|
33
45
|
this.notifyToolsChanged();
|
|
34
46
|
}
|
|
35
|
-
registerTool(tool) {
|
|
47
|
+
registerTool(tool, options) {
|
|
48
|
+
const signal = options?.signal;
|
|
49
|
+
if (signal?.aborted) {
|
|
50
|
+
console.warn(`[WebMCPPolyfill] registerTool("${tool?.name ?? "<unknown>"}") skipped: options.signal was already aborted.`);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
36
53
|
const normalized = normalizeToolDescriptor(tool, this.tools);
|
|
37
54
|
this.tools.set(normalized.name, normalized);
|
|
38
55
|
this.notifyToolsChanged();
|
|
56
|
+
if (signal) signal.addEventListener("abort", () => {
|
|
57
|
+
if (this.tools.delete(normalized.name)) this.notifyToolsChanged();
|
|
58
|
+
}, { once: true });
|
|
39
59
|
}
|
|
40
|
-
unregisterTool(
|
|
60
|
+
unregisterTool(nameOrTool) {
|
|
61
|
+
this.warnUnregisterToolDeprecationOnce();
|
|
62
|
+
const name = getToolNameForUnregister(nameOrTool);
|
|
41
63
|
if (this.tools.delete(name)) this.notifyToolsChanged();
|
|
42
64
|
}
|
|
65
|
+
getTools() {
|
|
66
|
+
return this.getToolInfos();
|
|
67
|
+
}
|
|
43
68
|
getTestingShim() {
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
return [...this.tools.values()].map((tool) => {
|
|
47
|
-
const output = {
|
|
48
|
-
name: tool.name,
|
|
49
|
-
description: tool.description
|
|
50
|
-
};
|
|
51
|
-
try {
|
|
52
|
-
output.inputSchema = JSON.stringify(tool.inputSchema);
|
|
53
|
-
} catch {}
|
|
54
|
-
return output;
|
|
55
|
-
});
|
|
56
|
-
},
|
|
57
|
-
executeTool: (toolName, inputArgsJson, options) => this.executeToolForTesting(toolName, inputArgsJson, options),
|
|
58
|
-
registerToolsChangedCallback: (callback) => {
|
|
59
|
-
if (typeof callback !== "function") throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");
|
|
60
|
-
this.toolsChangedCallback = callback;
|
|
61
|
-
},
|
|
62
|
-
getCrossDocumentScriptToolResult: async () => "[]"
|
|
63
|
-
};
|
|
69
|
+
if (!this.testingShim) this.testingShim = new PolyfillTestingShim(this);
|
|
70
|
+
return this.testingShim;
|
|
64
71
|
}
|
|
72
|
+
/** @internal Used by PolyfillTestingShim */
|
|
73
|
+
getToolInfos() {
|
|
74
|
+
return [...this.tools.values()].map((tool) => {
|
|
75
|
+
let inputSchema;
|
|
76
|
+
try {
|
|
77
|
+
inputSchema = JSON.stringify(tool.inputSchema ?? { type: "object" });
|
|
78
|
+
} catch {
|
|
79
|
+
inputSchema = "{\"type\":\"object\"}";
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
name: tool.name,
|
|
83
|
+
description: tool.description,
|
|
84
|
+
inputSchema
|
|
85
|
+
};
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** @internal Used by PolyfillTestingShim */
|
|
65
89
|
async executeToolForTesting(toolName, inputArgsJson, options) {
|
|
66
90
|
if (options?.signal?.aborted) throw createUnknownError(TOOL_CANCELLED_MESSAGE);
|
|
67
91
|
const tool = this.tools.get(toolName);
|
|
@@ -85,15 +109,81 @@ var StrictWebMCPContext = class {
|
|
|
85
109
|
}
|
|
86
110
|
}
|
|
87
111
|
notifyToolsChanged() {
|
|
88
|
-
if (!this.toolsChangedCallback) return;
|
|
89
112
|
queueMicrotask(() => {
|
|
113
|
+
const event = new Event("toolchange");
|
|
90
114
|
try {
|
|
91
|
-
this.
|
|
115
|
+
this._ontoolchange?.call(this, event);
|
|
92
116
|
} catch (error) {
|
|
93
|
-
console.warn("[WebMCPPolyfill]
|
|
117
|
+
console.warn("[WebMCPPolyfill] navigator.modelContext.ontoolchange handler threw:", error);
|
|
94
118
|
}
|
|
119
|
+
this.dispatchEvent(event);
|
|
120
|
+
this.testingShim?.dispatchToolChange();
|
|
95
121
|
});
|
|
96
122
|
}
|
|
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
|
+
warnUnregisterToolDeprecationOnce() {
|
|
134
|
+
if (this.unregisterToolDeprecationWarned) return;
|
|
135
|
+
this.unregisterToolDeprecationWarned = true;
|
|
136
|
+
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.");
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* EventTarget-based testing shim matching the native Chromium ModelContextTesting surface.
|
|
141
|
+
*
|
|
142
|
+
* Fires `toolchange` events and supports the `ontoolchange` handler property,
|
|
143
|
+
* matching the native Chromium 148 API. The deprecated `registerToolsChangedCallback`
|
|
144
|
+
* is kept as a compat layer that wraps `addEventListener`.
|
|
145
|
+
*/
|
|
146
|
+
var PolyfillTestingShim = class extends EventTarget {
|
|
147
|
+
context;
|
|
148
|
+
_ontoolchange = null;
|
|
149
|
+
constructor(context) {
|
|
150
|
+
super();
|
|
151
|
+
this.context = context;
|
|
152
|
+
}
|
|
153
|
+
listTools() {
|
|
154
|
+
return this.context.getToolInfos();
|
|
155
|
+
}
|
|
156
|
+
executeTool(toolName, inputArgsJson, options) {
|
|
157
|
+
return this.context.executeToolForTesting(toolName, inputArgsJson, options);
|
|
158
|
+
}
|
|
159
|
+
getCrossDocumentScriptToolResult() {
|
|
160
|
+
return Promise.resolve("[]");
|
|
161
|
+
}
|
|
162
|
+
get ontoolchange() {
|
|
163
|
+
return this._ontoolchange;
|
|
164
|
+
}
|
|
165
|
+
set ontoolchange(handler) {
|
|
166
|
+
this._ontoolchange = handler;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* @deprecated Use `addEventListener('toolchange', callback)` instead.
|
|
170
|
+
* Kept for backward compatibility with older polyfill consumers.
|
|
171
|
+
*/
|
|
172
|
+
registerToolsChangedCallback(callback) {
|
|
173
|
+
if (typeof callback !== "function") throw new TypeError("Failed to execute 'registerToolsChangedCallback' on 'ModelContextTesting': parameter 1 is not of type 'Function'.");
|
|
174
|
+
this.addEventListener("toolchange", callback);
|
|
175
|
+
}
|
|
176
|
+
/** @internal Called by StrictWebMCPContext when tools change. */
|
|
177
|
+
dispatchToolChange() {
|
|
178
|
+
const event = new Event("toolchange");
|
|
179
|
+
try {
|
|
180
|
+
this._ontoolchange?.call(this, event);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
console.warn("[WebMCPPolyfill] ontoolchange handler threw:", error);
|
|
183
|
+
}
|
|
184
|
+
this.dispatchEvent(event);
|
|
185
|
+
this.dispatchEvent(new Event("toolschanged"));
|
|
186
|
+
}
|
|
97
187
|
};
|
|
98
188
|
function createUnknownError(message) {
|
|
99
189
|
try {
|
|
@@ -114,6 +204,11 @@ function parseInputArgsJson(inputArgsJson) {
|
|
|
114
204
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw createUnknownError(FAILED_TO_PARSE_INPUT_ARGUMENTS_MESSAGE);
|
|
115
205
|
return parsed;
|
|
116
206
|
}
|
|
207
|
+
function getToolNameForUnregister(nameOrTool) {
|
|
208
|
+
if (typeof nameOrTool === "string") return nameOrTool;
|
|
209
|
+
if (isPlainObject(nameOrTool) && typeof nameOrTool.name === "string") return nameOrTool.name;
|
|
210
|
+
throw new TypeError("Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.");
|
|
211
|
+
}
|
|
117
212
|
function isPlainObject(value) {
|
|
118
213
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
119
214
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["DEFAULT_INPUT_SCHEMA: InputSchema","installState: InstallState","output: ModelContextTestingToolInfo","client: ModelContextClient","parsed: unknown","result: StandardValidationResult"],"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 ModelContextTesting,\n ModelContextTestingExecuteToolOptions,\n ModelContextTestingToolInfo,\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 {\n private tools = new Map<string, PolyfillToolDescriptor>();\n private toolsChangedCallback: (() => void) | null = null;\n\n provideContext(options: ModelContextOptions = {}): void {\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.tools.clear();\n this.notifyToolsChanged();\n }\n\n registerTool(tool: ToolDescriptor): void {\n const normalized = normalizeToolDescriptor(tool, this.tools);\n this.tools.set(normalized.name, normalized);\n this.notifyToolsChanged();\n }\n\n unregisterTool(name: string): void {\n const removed = this.tools.delete(name);\n if (removed) {\n this.notifyToolsChanged();\n }\n }\n\n getTestingShim(): ModelContextTesting {\n return {\n listTools: () => {\n return [...this.tools.values()].map((tool) => {\n const output: ModelContextTestingToolInfo = {\n name: tool.name,\n description: tool.description,\n };\n\n try {\n output.inputSchema = JSON.stringify(tool.inputSchema);\n } catch {\n // Keep inputSchema omitted when serialization fails.\n }\n\n return output;\n });\n },\n executeTool: (\n toolName: string,\n inputArgsJson: string,\n options?: ModelContextTestingExecuteToolOptions\n ) => this.executeToolForTesting(toolName, inputArgsJson, options),\n registerToolsChangedCallback: (callback: () => 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.toolsChangedCallback = callback;\n },\n getCrossDocumentScriptToolResult: async () => '[]',\n };\n }\n\n private 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 if (!this.toolsChangedCallback) {\n return;\n }\n\n queueMicrotask(() => {\n try {\n this.toolsChangedCallback?.();\n } catch (error) {\n // Callback errors are ignored to match browser event callback behavior.\n console.warn('[WebMCPPolyfill] toolsChanged callback threw:', error);\n }\n });\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\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":";;;AAeA,MAAM,0CAA0C;AAChD,MAAM,iCACJ;AACF,MAAM,yBAAyB;AAC/B,MAAMA,uBAAoC;CAAE,MAAM;CAAU,YAAY,EAAE;CAAE;AAC5E,MAAM,+BAA+B,CAAC,iBAAiB,WAAW;AAElE,MAAM,2BAA2B;AACjC,MAAM,4BAA4B,OAAO,oBAAoB;AAuD7D,MAAMC,eAA6B;CACjC,WAAW;CACX,gCAAgC;CAChC,uCAAuC;CACxC;AAyBD,IAAM,sBAAN,MAA0B;CACxB,AAAQ,wBAAQ,IAAI,KAAqC;CACzD,AAAQ,uBAA4C;CAEpD,eAAe,UAA+B,EAAE,EAAQ;EACtD,MAAM,4BAAY,IAAI,KAAqC;AAE3D,OAAK,MAAM,QAAQ,QAAQ,SAAS,EAAE,EAAE;GACtC,MAAM,aAAa,wBAAwB,MAAM,UAAU;AAC3D,aAAU,IAAI,WAAW,MAAM,WAAW;;AAG5C,OAAK,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AAM"}
|
|
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;AAyB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ACD;AAED,yBAAwB,KAAK,gBAAgB,aAA0C;CAEvF,MAAM,qBAAqB,SAAS,sBAAsB;CAC1D,MAAM,yBAAyB,QAAQ,IAAI,oBAAoB;AAM/D,KAJE,uBAAuB,aACrB,uBAAuB,QAAQ,uBAAuB,iBACtD,CAAC,uBAGH,yBACE,KACA,uBACA,QAAQ,gBAAgB,CACzB;AAGH,cAAa,YAAY;;AAG3B,SAAgB,wBAA8B;CAC5C,MAAM,MAAM,cAAc;AAC1B,KAAI,CAAC,OAAO,CAAC,aAAa,UACxB;CAGF,MAAM,WACJ,KACA,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"}
|
package/package.json
CHANGED
|
@@ -1,27 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcp-b/webmcp-polyfill",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "Strict WebMCP core runtime polyfill for navigator.modelContext",
|
|
5
5
|
"keywords": [
|
|
6
|
-
"
|
|
6
|
+
"browser",
|
|
7
7
|
"model-context",
|
|
8
8
|
"navigator-modelcontext",
|
|
9
9
|
"polyfill",
|
|
10
|
-
"
|
|
10
|
+
"webmcp"
|
|
11
11
|
],
|
|
12
12
|
"homepage": "https://docs.mcp-b.ai/packages/webmcp-polyfill",
|
|
13
13
|
"bugs": {
|
|
14
14
|
"url": "https://github.com/WebMCP-org/npm-packages/issues"
|
|
15
15
|
},
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"author": "Alex Nahas",
|
|
16
18
|
"repository": {
|
|
17
19
|
"type": "git",
|
|
18
20
|
"url": "git+https://github.com/WebMCP-org/npm-packages.git",
|
|
19
21
|
"directory": "packages/webmcp-polyfill"
|
|
20
22
|
},
|
|
21
|
-
"
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
24
26
|
"type": "module",
|
|
27
|
+
"sideEffects": true,
|
|
28
|
+
"main": "./dist/index.js",
|
|
29
|
+
"module": "./dist/index.js",
|
|
30
|
+
"browser": "./dist/index.iife.js",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
25
32
|
"exports": {
|
|
26
33
|
".": {
|
|
27
34
|
"types": "./dist/index.d.ts",
|
|
@@ -33,46 +40,37 @@
|
|
|
33
40
|
"default": "./dist/index.iife.js"
|
|
34
41
|
}
|
|
35
42
|
},
|
|
36
|
-
"
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
"files": [
|
|
41
|
-
"dist"
|
|
42
|
-
],
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public",
|
|
45
|
+
"registry": "https://registry.npmjs.org/"
|
|
46
|
+
},
|
|
43
47
|
"dependencies": {
|
|
44
48
|
"@cfworker/json-schema": "^4.1.1",
|
|
45
49
|
"@standard-schema/spec": "^1.1.0",
|
|
46
|
-
"@mcp-b/webmcp-types": "2.
|
|
50
|
+
"@mcp-b/webmcp-types": "2.3.0"
|
|
47
51
|
},
|
|
48
52
|
"devDependencies": {
|
|
49
|
-
"@vitest/
|
|
50
|
-
"@vitest/browser-playwright": "^4.0.18",
|
|
51
|
-
"@vitest/coverage-v8": "^4.0.18",
|
|
53
|
+
"@vitest/coverage-v8": "^4.1.0",
|
|
52
54
|
"happy-dom": "^20.0.0",
|
|
53
55
|
"playwright": "^1.58.0",
|
|
54
|
-
"tsdown": "^0.15.10",
|
|
55
56
|
"typescript": "^5.8.3",
|
|
56
|
-
"
|
|
57
|
+
"vite-plus": "latest",
|
|
58
|
+
"vitest": "npm:@voidzero-dev/vite-plus-test@latest"
|
|
57
59
|
},
|
|
58
60
|
"engines": {
|
|
59
61
|
"node": ">=18"
|
|
60
62
|
},
|
|
61
|
-
"publishConfig": {
|
|
62
|
-
"access": "public",
|
|
63
|
-
"registry": "https://registry.npmjs.org/"
|
|
64
|
-
},
|
|
65
63
|
"scripts": {
|
|
66
|
-
"build": "pnpm --filter @mcp-b/webmcp-types build &&
|
|
67
|
-
"check": "
|
|
68
|
-
"clean": "rm -rf dist
|
|
69
|
-
"format": "
|
|
70
|
-
"lint": "
|
|
64
|
+
"build": "pnpm --filter @mcp-b/webmcp-types build && vp pack",
|
|
65
|
+
"check": "vp check --fix",
|
|
66
|
+
"clean": "rm -rf dist",
|
|
67
|
+
"format": "vp fmt --write",
|
|
68
|
+
"lint": "vp lint --fix",
|
|
71
69
|
"publish:dry": "pnpm publish --access public --dry-run",
|
|
72
70
|
"publish:npm": "pnpm publish --access public",
|
|
73
|
-
"test": "
|
|
74
|
-
"test:browser": "
|
|
75
|
-
"test:browser:ui": "
|
|
76
|
-
"typecheck": "pnpm --filter @mcp-b/webmcp-types build && tsc --noEmit &&
|
|
71
|
+
"test": "vp test run",
|
|
72
|
+
"test:browser": "vp test run --config vitest.browser.config.ts --browser.headless",
|
|
73
|
+
"test:browser:ui": "vp test --config vitest.browser.config.ts --browser",
|
|
74
|
+
"typecheck": "pnpm --filter @mcp-b/webmcp-types build && tsc --noEmit && vp test run --typecheck --silent"
|
|
77
75
|
}
|
|
78
76
|
}
|