@mcp-b/global 2.1.0 → 2.2.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 +92 -102
- package/dist/index.iife.js +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
| **Drop-in IIFE** | Add AI capabilities with a single `<script>` tag - no build step |
|
|
21
21
|
| **Native Chromium Support** | Auto-detects and uses native browser implementation when available |
|
|
22
22
|
| **Dual Transport** | Works with both same-window clients AND parent pages (iframe support) |
|
|
23
|
-
| **
|
|
23
|
+
| **Spec-Aware Compatibility** | `provideContext()` / `clearContext()` remain temporarily for compatibility, and MCP-B wrappers still return a deprecated unregister handle from `registerTool()` |
|
|
24
24
|
| **Works with Any AI** | Claude, ChatGPT, Gemini, Cursor, Copilot, and any MCP client |
|
|
25
25
|
|
|
26
26
|
## Package Selection
|
|
@@ -43,19 +43,15 @@
|
|
|
43
43
|
<h1>My AI-Powered App</h1>
|
|
44
44
|
|
|
45
45
|
<script>
|
|
46
|
-
navigator.modelContext.
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
]
|
|
46
|
+
navigator.modelContext.registerTool({
|
|
47
|
+
name: "get-page-title",
|
|
48
|
+
description: "Get the current page title",
|
|
49
|
+
inputSchema: { type: "object", properties: {} },
|
|
50
|
+
async execute() {
|
|
51
|
+
return {
|
|
52
|
+
content: [{ type: "text", text: document.title }]
|
|
53
|
+
};
|
|
54
|
+
}
|
|
59
55
|
});
|
|
60
56
|
</script>
|
|
61
57
|
</body>
|
|
@@ -71,7 +67,7 @@
|
|
|
71
67
|
```html
|
|
72
68
|
<script type="module">
|
|
73
69
|
import '@mcp-b/global';
|
|
74
|
-
navigator.modelContext.
|
|
70
|
+
navigator.modelContext.registerTool({ /* your tool */ });
|
|
75
71
|
</script>
|
|
76
72
|
```
|
|
77
73
|
|
|
@@ -86,9 +82,7 @@ npm install @mcp-b/global
|
|
|
86
82
|
```javascript
|
|
87
83
|
import '@mcp-b/global';
|
|
88
84
|
|
|
89
|
-
navigator.modelContext.
|
|
90
|
-
tools: [/* your tools */]
|
|
91
|
-
});
|
|
85
|
+
navigator.modelContext.registerTool({ /* your tool */ });
|
|
92
86
|
```
|
|
93
87
|
|
|
94
88
|
## API Reference
|
|
@@ -137,6 +131,8 @@ After initialization, `navigator.modelContext` exposes these methods:
|
|
|
137
131
|
|
|
138
132
|
#### `provideContext(options?)`
|
|
139
133
|
|
|
134
|
+
Deprecated compatibility API. The upstream WebMCP spec removed `provideContext()` on March 5, 2026. `@mcp-b/global` keeps it functional for now, but logs a deprecation warning and will remove it in the next major version.
|
|
135
|
+
|
|
140
136
|
Replaces all currently registered tools with a new set. This is an atomic replacement - all previous tools are removed first.
|
|
141
137
|
|
|
142
138
|
```typescript
|
|
@@ -176,10 +172,10 @@ navigator.modelContext.provideContext({
|
|
|
176
172
|
|
|
177
173
|
#### `registerTool(tool)`
|
|
178
174
|
|
|
179
|
-
Registers a single tool. The tool name must be unique - throws if a tool with the same name already exists.
|
|
175
|
+
Registers a single tool. The tool name must be unique - throws if a tool with the same name already exists. `@mcp-b/global` still returns a deprecated compatibility handle with `unregister()` so existing MCP-B integrations do not break, even though current Chromium returns `undefined`.
|
|
180
176
|
|
|
181
177
|
```typescript
|
|
182
|
-
navigator.modelContext.registerTool({
|
|
178
|
+
const registration = navigator.modelContext.registerTool({
|
|
183
179
|
name: 'add-to-cart',
|
|
184
180
|
description: 'Add a product to the shopping cart',
|
|
185
181
|
inputSchema: {
|
|
@@ -197,11 +193,13 @@ navigator.modelContext.registerTool({
|
|
|
197
193
|
};
|
|
198
194
|
},
|
|
199
195
|
});
|
|
196
|
+
|
|
197
|
+
registration.unregister();
|
|
200
198
|
```
|
|
201
199
|
|
|
202
|
-
#### `unregisterTool(
|
|
200
|
+
#### `unregisterTool(nameOrTool)`
|
|
203
201
|
|
|
204
|
-
Removes a tool by name.
|
|
202
|
+
Removes a tool by name. Current Chrome Beta 147 and Chromium `main` expose string-name unregistration. MCP-B wrappers also accept the originally registered tool object as a temporary compatibility input.
|
|
205
203
|
|
|
206
204
|
```typescript
|
|
207
205
|
navigator.modelContext.unregisterTool('add-to-cart');
|
|
@@ -209,6 +207,8 @@ navigator.modelContext.unregisterTool('add-to-cart');
|
|
|
209
207
|
|
|
210
208
|
#### `clearContext()`
|
|
211
209
|
|
|
210
|
+
Deprecated compatibility API. The upstream WebMCP spec removed `clearContext()` on March 5, 2026. `@mcp-b/global` keeps it functional for now, but logs a deprecation warning and will remove it in the next major version.
|
|
211
|
+
|
|
212
212
|
Removes all registered tools.
|
|
213
213
|
|
|
214
214
|
```typescript
|
|
@@ -364,7 +364,7 @@ const result = await navigator.modelContextTesting?.executeTool(
|
|
|
364
364
|
|
|
365
365
|
```javascript
|
|
366
366
|
if ('modelContext' in navigator) {
|
|
367
|
-
navigator.modelContext.
|
|
367
|
+
navigator.modelContext.registerTool({ /* your tool */ });
|
|
368
368
|
}
|
|
369
369
|
```
|
|
370
370
|
|
|
@@ -375,45 +375,42 @@ if ('modelContext' in navigator) {
|
|
|
375
375
|
```typescript
|
|
376
376
|
import '@mcp-b/global';
|
|
377
377
|
|
|
378
|
-
navigator.modelContext.
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
category: { type: 'string', description: 'Product category' },
|
|
388
|
-
maxPrice: { type: 'number', description: 'Maximum price filter' },
|
|
389
|
-
},
|
|
390
|
-
required: ['query'],
|
|
391
|
-
},
|
|
392
|
-
async execute(args) {
|
|
393
|
-
const results = await fetch(`/api/products?q=${args.query}&cat=${args.category ?? ''}&max=${args.maxPrice ?? ''}`);
|
|
394
|
-
return { content: [{ type: 'text', text: await results.text() }] };
|
|
395
|
-
},
|
|
378
|
+
navigator.modelContext.registerTool({
|
|
379
|
+
name: 'search-products',
|
|
380
|
+
description: 'Search products by keyword, category, or price range',
|
|
381
|
+
inputSchema: {
|
|
382
|
+
type: 'object',
|
|
383
|
+
properties: {
|
|
384
|
+
query: { type: 'string', description: 'Search terms' },
|
|
385
|
+
category: { type: 'string', description: 'Product category' },
|
|
386
|
+
maxPrice: { type: 'number', description: 'Maximum price filter' },
|
|
396
387
|
},
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
return { content: [{ type: 'text', text: `Added to cart` }] };
|
|
414
|
-
},
|
|
388
|
+
required: ['query'],
|
|
389
|
+
},
|
|
390
|
+
async execute(args) {
|
|
391
|
+
const results = await fetch(`/api/products?q=${args.query}&cat=${args.category ?? ''}&max=${args.maxPrice ?? ''}`);
|
|
392
|
+
return { content: [{ type: 'text', text: await results.text() }] };
|
|
393
|
+
},
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
navigator.modelContext.registerTool({
|
|
397
|
+
name: 'add-to-cart',
|
|
398
|
+
description: 'Add a product to the shopping cart',
|
|
399
|
+
inputSchema: {
|
|
400
|
+
type: 'object',
|
|
401
|
+
properties: {
|
|
402
|
+
productId: { type: 'string' },
|
|
403
|
+
quantity: { type: 'integer' },
|
|
415
404
|
},
|
|
416
|
-
|
|
405
|
+
required: ['productId'],
|
|
406
|
+
},
|
|
407
|
+
async execute(args) {
|
|
408
|
+
await fetch('/api/cart', {
|
|
409
|
+
method: 'POST',
|
|
410
|
+
body: JSON.stringify({ productId: args.productId, quantity: args.quantity ?? 1 }),
|
|
411
|
+
});
|
|
412
|
+
return { content: [{ type: 'text', text: `Added to cart` }] };
|
|
413
|
+
},
|
|
417
414
|
});
|
|
418
415
|
```
|
|
419
416
|
|
|
@@ -423,17 +420,13 @@ navigator.modelContext.provideContext({
|
|
|
423
420
|
import '@mcp-b/global';
|
|
424
421
|
|
|
425
422
|
// Start with base tools
|
|
426
|
-
navigator.modelContext.
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
return { content: [{ type: 'text', text: JSON.stringify(currentUser) }] };
|
|
434
|
-
},
|
|
435
|
-
},
|
|
436
|
-
],
|
|
423
|
+
navigator.modelContext.registerTool({
|
|
424
|
+
name: 'get-user',
|
|
425
|
+
description: 'Get current user info',
|
|
426
|
+
inputSchema: { type: 'object', properties: {} },
|
|
427
|
+
async execute() {
|
|
428
|
+
return { content: [{ type: 'text', text: JSON.stringify(currentUser) }] };
|
|
429
|
+
},
|
|
437
430
|
});
|
|
438
431
|
|
|
439
432
|
// Add tools dynamically based on user role
|
|
@@ -455,7 +448,7 @@ if (currentUser.isAdmin) {
|
|
|
455
448
|
|
|
456
449
|
// Remove tools when permissions change
|
|
457
450
|
function onLogout() {
|
|
458
|
-
navigator.modelContext.
|
|
451
|
+
navigator.modelContext.unregisterTool('get-user');
|
|
459
452
|
}
|
|
460
453
|
```
|
|
461
454
|
|
|
@@ -464,37 +457,34 @@ function onLogout() {
|
|
|
464
457
|
```typescript
|
|
465
458
|
import '@mcp-b/global';
|
|
466
459
|
|
|
467
|
-
navigator.modelContext.
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
email: { type: 'string' },
|
|
477
|
-
message: { type: 'string' },
|
|
478
|
-
},
|
|
479
|
-
required: ['name', 'email', 'message'],
|
|
480
|
-
},
|
|
481
|
-
async execute(args) {
|
|
482
|
-
document.querySelector('#name').value = args.name;
|
|
483
|
-
document.querySelector('#email').value = args.email;
|
|
484
|
-
document.querySelector('#message').value = args.message;
|
|
485
|
-
return { content: [{ type: 'text', text: 'Form filled' }] };
|
|
486
|
-
},
|
|
487
|
-
},
|
|
488
|
-
{
|
|
489
|
-
name: 'submit-form',
|
|
490
|
-
description: 'Submit the contact form',
|
|
491
|
-
inputSchema: { type: 'object', properties: {} },
|
|
492
|
-
async execute() {
|
|
493
|
-
document.querySelector('#contact-form').submit();
|
|
494
|
-
return { content: [{ type: 'text', text: 'Form submitted' }] };
|
|
495
|
-
},
|
|
460
|
+
navigator.modelContext.registerTool({
|
|
461
|
+
name: 'fill-contact-form',
|
|
462
|
+
description: 'Fill the contact form with provided details',
|
|
463
|
+
inputSchema: {
|
|
464
|
+
type: 'object',
|
|
465
|
+
properties: {
|
|
466
|
+
name: { type: 'string' },
|
|
467
|
+
email: { type: 'string' },
|
|
468
|
+
message: { type: 'string' },
|
|
496
469
|
},
|
|
497
|
-
|
|
470
|
+
required: ['name', 'email', 'message'],
|
|
471
|
+
},
|
|
472
|
+
async execute(args) {
|
|
473
|
+
document.querySelector('#name').value = args.name;
|
|
474
|
+
document.querySelector('#email').value = args.email;
|
|
475
|
+
document.querySelector('#message').value = args.message;
|
|
476
|
+
return { content: [{ type: 'text', text: 'Form filled' }] };
|
|
477
|
+
},
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
navigator.modelContext.registerTool({
|
|
481
|
+
name: 'submit-form',
|
|
482
|
+
description: 'Submit the contact form',
|
|
483
|
+
inputSchema: { type: 'object', properties: {} },
|
|
484
|
+
async execute() {
|
|
485
|
+
document.querySelector('#contact-form').submit();
|
|
486
|
+
return { content: [{ type: 'text', text: 'Form submitted' }] };
|
|
487
|
+
},
|
|
498
488
|
});
|
|
499
489
|
```
|
|
500
490
|
|
package/dist/index.iife.js
CHANGED
|
@@ -39,4 +39,4 @@ var WebMCP=(function(e){var t;(function(e){e.assertEqual=e=>{};function t(e){}e.
|
|
|
39
39
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Ra(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(a[e.defId]=e.def)}e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?i.$defs=a:i.definitions=a);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:Ba(t,`input`,e.processors),output:Ba(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function O(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return O(r.element,n);if(r.type===`set`)return O(r.valueType,n);if(r.type===`lazy`)return O(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return O(r.innerType,n);if(r.type===`intersection`)return O(r.left,n)||O(r.right,n);if(r.type===`record`||r.type===`map`)return O(r.keyType,n)||O(r.valueType,n);if(r.type===`pipe`)return O(r.in,n)||O(r.out,n);if(r.type===`object`){for(let e in r.shape)if(O(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(O(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(O(e,n))return!0;return!!(r.rest&&O(r.rest,n))}return!1}let za=(e,t={})=>n=>{let r=Ia({...n,processors:t});return D(e,r),La(r,e),Ra(r,e)},Ba=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Ia({...i??{},target:a,io:t,processors:n});return D(e,o),La(o,e),Ra(o,e)},Va={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Ha=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Va[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Ua=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;typeof s==`string`&&s.includes(`int`)?i.type=`integer`:i.type=`number`,typeof u==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u),typeof a==`number`&&(i.minimum=a,typeof u==`number`&&t.target!==`draft-04`&&(u>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof l==`number`&&(t.target===`draft-04`||t.target===`openapi-3.0`?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l),typeof o==`number`&&(i.maximum=o,typeof l==`number`&&t.target!==`draft-04`&&(l<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c==`number`&&(i.multipleOf=c)},Wa=(e,t,n,r)=>{n.type=`boolean`},Ga=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`BigInt cannot be represented in JSON Schema`)},Ka=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Symbols cannot be represented in JSON Schema`)},qa=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Ja=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Undefined cannot be represented in JSON Schema`)},Ya=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Void cannot be represented in JSON Schema`)},Xa=(e,t,n,r)=>{n.not={}},Za=(e,t,n,r)=>{},Qa=(e,t,n,r)=>{},$a=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Date cannot be represented in JSON Schema`)},eo=(e,t,n,r)=>{let i=e._zod.def,a=bt(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},to=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0)if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a},no=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`NaN cannot be represented in JSON Schema`)},ro=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},io=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},ao=(e,t,n,r)=>{n.type=`boolean`},oo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},so=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Function types cannot be represented in JSON Schema`)},co=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},lo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Map cannot be represented in JSON Schema`)},uo=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Set cannot be represented in JSON Schema`)},fo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=D(a.element,t,{...r,path:[...r.path,`items`]})},po=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=D(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=D(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},mo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>D(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},ho=(e,t,n,r)=>{let i=e._zod.def,a=D(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=D(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>D(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?D(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},_o=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=D(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=D(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=D(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},vo=(e,t,n,r)=>{let i=e._zod.def,a=D(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},yo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},bo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},xo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},So=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},Co=(e,t,n,r)=>{let i=e._zod.def,a=t.io===`input`?i.in._zod.def.type===`transform`?i.out:i.in:i.out;D(a,t,r);let o=t.seen.get(e);o.ref=a},wo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},To=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Eo=(e,t,n,r)=>{let i=e._zod.def;D(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Do={string:Ha,number:Ua,boolean:Wa,bigint:Ga,symbol:Ka,null:qa,undefined:Ja,void:Ya,never:Xa,any:Za,unknown:Qa,date:$a,enum:eo,literal:to,nan:no,template_literal:ro,file:io,success:ao,custom:oo,function:so,transform:co,map:lo,set:uo,array:fo,object:po,union:mo,intersection:ho,tuple:go,record:_o,nullable:vo,nonoptional:yo,default:bo,prefault:xo,catch:So,pipe:Co,readonly:wo,promise:To,optional:Eo,lazy:(e,t,n,r)=>{let i=e._zod.innerType;D(i,t,r);let a=t.seen.get(e);a.ref=i}};function Oo(e,t){if(`_idmap`in e){let n=e,r=Ia({...t,processors:Do}),i={};for(let e of n._idmap.entries()){let[t,n]=e;D(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;La(r,n),a[t]=Ra(r,n)}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Ia({...t,processors:Do});return D(e,n),La(n,e),Ra(n,e)}let ko=x(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);T.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>sn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>dn(e,t,n),e.parseAsync=async(t,n)=>ln(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>pn(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>Rt(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Ao=x(`ZodMiniObject`,(e,t)=>{ei.init(e,t),ko.init(e,t),S(e,`shape`,()=>t.shape)});function jo(e,t){return new Ao({type:`object`,shape:e??{},...C(t)})}let Mo=x(`ZodISODateTime`,(e,t)=>{Or.init(e,t),j.init(e,t)});function No(e){return ta(Mo,e)}let Po=x(`ZodISODate`,(e,t)=>{kr.init(e,t),j.init(e,t)});function Fo(e){return na(Po,e)}let Io=x(`ZodISOTime`,(e,t)=>{Ar.init(e,t),j.init(e,t)});function Lo(e){return ra(Io,e)}let Ro=x(`ZodISODuration`,(e,t)=>{jr.init(e,t),j.init(e,t)});function zo(e){return ia(Ro,e)}let Bo=(e,t)=>{tn.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>an(e,t)},flatten:{value:t=>rn(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,xt,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,xt,2)}},isEmpty:{get(){return e.issues.length===0}}})};x(`ZodError`,Bo);let Vo=x(`ZodError`,Bo,{Parent:Error}),Ho=on(Vo),Uo=cn(Vo),Wo=un(Vo),Go=fn(Vo),Ko=mn(Vo),qo=hn(Vo),Jo=gn(Vo),Yo=_n(Vo),Xo=vn(Vo),Zo=yn(Vo),Qo=bn(Vo),$o=xn(Vo),k=x(`ZodType`,(e,t)=>(T.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Ba(e,`input`),output:Ba(e,`output`)}}),e.toJSONSchema=za(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.check=(...n)=>e.clone(Ot(t,{checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>Rt(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>Ho(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Wo(e,t,n),e.parseAsync=async(t,n)=>Uo(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Go(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ko(e,t,n),e.decode=(t,n)=>qo(e,t,n),e.encodeAsync=async(t,n)=>Jo(e,t,n),e.decodeAsync=async(t,n)=>Yo(e,t,n),e.safeEncode=(t,n)=>Xo(e,t,n),e.safeDecode=(t,n)=>Zo(e,t,n),e.safeEncodeAsync=async(t,n)=>Qo(e,t,n),e.safeDecodeAsync=async(t,n)=>$o(e,t,n),e.refine=(t,n)=>e.check(sc(t,n)),e.superRefine=t=>e.check(cc(t)),e.overwrite=t=>e.check(Ta(t)),e.optional=()=>H(e),e.exactOptional=()=>Ws(e),e.nullable=()=>Ks(e),e.nullish=()=>H(Ks(e)),e.nonoptional=t=>Qs(e,t),e.array=()=>F(e),e.or=t=>R([e,t]),e.and=t=>Is(e,t),e.transform=t=>nc(e,Vs(t)),e.default=t=>Js(e,t),e.prefault=t=>Xs(e,t),e.catch=t=>ec(e,t),e.pipe=t=>nc(e,t),e.readonly=()=>ic(e),e.describe=t=>{let n=e.clone();return ji.add(n,{description:t}),n},Object.defineProperty(e,`description`,{get(){return ji.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return ji.get(e);let n=e.clone();return ji.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),es=x(`_ZodString`,(e,t)=>{gr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ha(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(ya(...t)),e.includes=(...t)=>e.check(Sa(...t)),e.startsWith=(...t)=>e.check(Ca(...t)),e.endsWith=(...t)=>e.check(wa(...t)),e.min=(...t)=>e.check(_a(...t)),e.max=(...t)=>e.check(ga(...t)),e.length=(...t)=>e.check(va(...t)),e.nonempty=(...t)=>e.check(_a(1,...t)),e.lowercase=t=>e.check(ba(t)),e.uppercase=t=>e.check(xa(t)),e.trim=()=>e.check(Da()),e.normalize=(...t)=>e.check(Ea(...t)),e.toLowerCase=()=>e.check(Oa()),e.toUpperCase=()=>e.check(ka()),e.slugify=()=>e.check(Aa())}),ts=x(`ZodString`,(e,t)=>{gr.init(e,t),es.init(e,t),e.email=t=>e.check(Ni(ns,t)),e.url=t=>e.check(zi(as,t)),e.jwt=t=>e.check(ea(bs,t)),e.emoji=t=>e.check(Bi(os,t)),e.guid=t=>e.check(Pi(rs,t)),e.uuid=t=>e.check(Fi(is,t)),e.uuidv4=t=>e.check(Ii(is,t)),e.uuidv6=t=>e.check(Li(is,t)),e.uuidv7=t=>e.check(Ri(is,t)),e.nanoid=t=>e.check(Vi(ss,t)),e.guid=t=>e.check(Pi(rs,t)),e.cuid=t=>e.check(Hi(cs,t)),e.cuid2=t=>e.check(Ui(ls,t)),e.ulid=t=>e.check(Wi(us,t)),e.base64=t=>e.check(Zi(_s,t)),e.base64url=t=>e.check(Qi(vs,t)),e.xid=t=>e.check(Gi(ds,t)),e.ksuid=t=>e.check(Ki(fs,t)),e.ipv4=t=>e.check(qi(ps,t)),e.ipv6=t=>e.check(Ji(ms,t)),e.cidrv4=t=>e.check(Yi(hs,t)),e.cidrv6=t=>e.check(Xi(gs,t)),e.e164=t=>e.check($i(ys,t)),e.datetime=t=>e.check(No(t)),e.date=t=>e.check(Fo(t)),e.time=t=>e.check(Lo(t)),e.duration=t=>e.check(zo(t))});function A(e){return Mi(ts,e)}let j=x(`ZodStringFormat`,(e,t)=>{E.init(e,t),es.init(e,t)}),ns=x(`ZodEmail`,(e,t)=>{yr.init(e,t),j.init(e,t)}),rs=x(`ZodGUID`,(e,t)=>{_r.init(e,t),j.init(e,t)}),is=x(`ZodUUID`,(e,t)=>{vr.init(e,t),j.init(e,t)}),as=x(`ZodURL`,(e,t)=>{br.init(e,t),j.init(e,t)}),os=x(`ZodEmoji`,(e,t)=>{xr.init(e,t),j.init(e,t)}),ss=x(`ZodNanoID`,(e,t)=>{Sr.init(e,t),j.init(e,t)}),cs=x(`ZodCUID`,(e,t)=>{Cr.init(e,t),j.init(e,t)}),ls=x(`ZodCUID2`,(e,t)=>{wr.init(e,t),j.init(e,t)}),us=x(`ZodULID`,(e,t)=>{Tr.init(e,t),j.init(e,t)}),ds=x(`ZodXID`,(e,t)=>{Er.init(e,t),j.init(e,t)}),fs=x(`ZodKSUID`,(e,t)=>{Dr.init(e,t),j.init(e,t)}),ps=x(`ZodIPv4`,(e,t)=>{Mr.init(e,t),j.init(e,t)}),ms=x(`ZodIPv6`,(e,t)=>{Nr.init(e,t),j.init(e,t)}),hs=x(`ZodCIDRv4`,(e,t)=>{Pr.init(e,t),j.init(e,t)}),gs=x(`ZodCIDRv6`,(e,t)=>{Fr.init(e,t),j.init(e,t)}),_s=x(`ZodBase64`,(e,t)=>{Lr.init(e,t),j.init(e,t)}),vs=x(`ZodBase64URL`,(e,t)=>{zr.init(e,t),j.init(e,t)}),ys=x(`ZodE164`,(e,t)=>{Br.init(e,t),j.init(e,t)}),bs=x(`ZodJWT`,(e,t)=>{Hr.init(e,t),j.init(e,t)}),xs=x(`ZodNumber`,(e,t)=>{Ur.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ua(e,t,n,r),e.gt=(t,n)=>e.check(pa(t,n)),e.gte=(t,n)=>e.check(ma(t,n)),e.min=(t,n)=>e.check(ma(t,n)),e.lt=(t,n)=>e.check(da(t,n)),e.lte=(t,n)=>e.check(fa(t,n)),e.max=(t,n)=>e.check(fa(t,n)),e.int=t=>e.check(Cs(t)),e.safe=t=>e.check(Cs(t)),e.positive=t=>e.check(pa(0,t)),e.nonnegative=t=>e.check(ma(0,t)),e.negative=t=>e.check(da(0,t)),e.nonpositive=t=>e.check(fa(0,t)),e.multipleOf=(t,n)=>e.check(ha(t,n)),e.step=(t,n)=>e.check(ha(t,n)),e.finite=()=>e;let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function M(e){return aa(xs,e)}let Ss=x(`ZodNumberFormat`,(e,t)=>{Wr.init(e,t),xs.init(e,t)});function Cs(e){return oa(Ss,e)}let ws=x(`ZodBoolean`,(e,t)=>{Gr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wa(e,t,n,r)});function N(e){return sa(ws,e)}let Ts=x(`ZodNull`,(e,t)=>{Kr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qa(e,t,n,r)});function Es(e){return ca(Ts,e)}let Ds=x(`ZodUnknown`,(e,t)=>{qr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function P(){return la(Ds)}let Os=x(`ZodNever`,(e,t)=>{Jr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xa(e,t,n,r)});function ks(e){return ua(Os,e)}let As=x(`ZodArray`,(e,t)=>{Xr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fo(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(_a(t,n)),e.nonempty=t=>e.check(_a(1,t)),e.max=(t,n)=>e.check(ga(t,n)),e.length=(t,n)=>e.check(va(t,n)),e.unwrap=()=>e.element});function F(e,t){return ja(As,e,t)}let js=x(`ZodObject`,(e,t)=>{ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>po(e,t,n,r),S(e,`shape`,()=>t.shape),e.keyof=()=>B(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:P()}),e.loose=()=>e.clone({...e._zod.def,catchall:P()}),e.strict=()=>e.clone({...e._zod.def,catchall:ks()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>Ut(e,t),e.safeExtend=t=>Wt(e,t),e.merge=t=>Gt(e,t),e.pick=t=>Vt(e,t),e.omit=t=>Ht(e,t),e.partial=(...t)=>Kt(Hs,e,t[0]),e.required=(...t)=>qt(Zs,e,t[0])});function I(e,t){return new js({type:`object`,shape:e??{},...C(t)})}function L(e,t){return new js({type:`object`,shape:e,catchall:P(),...C(t)})}let Ms=x(`ZodUnion`,(e,t)=>{ri.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mo(e,t,n,r),e.options=t.options});function R(e,t){return new Ms({type:`union`,options:e,...C(t)})}let Ns=x(`ZodDiscriminatedUnion`,(e,t)=>{Ms.init(e,t),ii.init(e,t)});function Ps(e,t,n){return new Ns({type:`union`,options:t,discriminator:e,...C(n)})}let Fs=x(`ZodIntersection`,(e,t)=>{ai.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ho(e,t,n,r)});function Is(e,t){return new Fs({type:`intersection`,left:e,right:t})}let Ls=x(`ZodRecord`,(e,t)=>{ci.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_o(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return new Ls({type:`record`,keyType:e,valueType:t,...C(n)})}let Rs=x(`ZodEnum`,(e,t)=>{li.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eo(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Rs({...t,checks:[],...C(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Rs({...t,checks:[],...C(r),entries:i})}});function B(e,t){return new Rs({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...C(t)})}let zs=x(`ZodLiteral`,(e,t)=>{ui.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>to(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,`value`,{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function V(e,t){return new zs({type:`literal`,values:Array.isArray(e)?e:[e],...C(t)})}let Bs=x(`ZodTransform`,(e,t)=>{di.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>co(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new _t(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push($t(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push($t(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Vs(e){return new Bs({type:`transform`,transform:e})}let Hs=x(`ZodOptional`,(e,t)=>{pi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Eo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function H(e){return new Hs({type:`optional`,innerType:e})}let Us=x(`ZodExactOptional`,(e,t)=>{mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Eo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ws(e){return new Us({type:`optional`,innerType:e})}let Gs=x(`ZodNullable`,(e,t)=>{hi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ks(e){return new Gs({type:`nullable`,innerType:e})}let qs=x(`ZodDefault`,(e,t)=>{gi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Js(e,t){return new qs({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ft(t)}})}let Ys=x(`ZodPrefault`,(e,t)=>{vi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xs(e,t){return new Ys({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ft(t)}})}let Zs=x(`ZodNonOptional`,(e,t)=>{yi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qs(e,t){return new Zs({type:`nonoptional`,innerType:e,...C(t)})}let $s=x(`ZodCatch`,(e,t)=>{xi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>So(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function ec(e,t){return new $s({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let tc=x(`ZodPipe`,(e,t)=>{Si.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Co(e,t,n,r),e.in=t.in,e.out=t.out});function nc(e,t){return new tc({type:`pipe`,in:e,out:t})}let rc=x(`ZodReadonly`,(e,t)=>{wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ic(e){return new rc({type:`readonly`,innerType:e})}let ac=x(`ZodCustom`,(e,t)=>{Ei.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oo(e,t,n,r)});function oc(e,t){return Ma(ac,e??(()=>!0),t)}function sc(e,t={}){return Na(ac,e,t)}function cc(e){return Pa(e)}function lc(e,t){return nc(Vs(e),t)}let uc=Symbol(`Let zodToJsonSchema decide on which parser to use`),dc={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},fc=e=>typeof e==`string`?{...dc,name:e}:{...dc,...e},pc=e=>{let t=fc(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function mc(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function U(e,t,n,r,i){e[t]=n,mc(e,t,r,i)}let hc=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function W(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?hc(t,e.currentPath):t.join(`/`)}}function gc(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==b.ZodAny&&(n.items=K(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&U(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&U(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(U(n,`minItems`,e.exactLength.value,e.exactLength.message,t),U(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function _c(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?U(n,`minimum`,r.value,r.message,t):U(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),U(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?U(n,`maximum`,r.value,r.message,t):U(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),U(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:U(n,`multipleOf`,r.value,r.message,t);break}return n}function vc(){return{type:`boolean`}}function yc(e,t){return K(e.type._def,t)}let bc=(e,t)=>K(e.innerType._def,t);function xc(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>xc(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Sc(e,t)}}let Sc=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:U(n,`minimum`,r.value,r.message,t);break;case`max`:U(n,`maximum`,r.value,r.message,t);break}return n};function Cc(e,t){return{...K(e.innerType._def,t),default:e.defaultValue()}}function wc(e,t){return t.effectStrategy===`input`?K(e.schema._def,t):W(t)}function Tc(e){return{type:`string`,enum:Array.from(e.values)}}let Ec=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Dc(e,t){let n=[K(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),K(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Ec(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Oc(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let kc,Ac={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(kc===void 0&&(kc=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),kc),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function jc(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:U(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:U(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Fc(n,`email`,r.message,t);break;case`format:idn-email`:Fc(n,`idn-email`,r.message,t);break;case`pattern:zod`:G(n,Ac.email,r.message,t);break}break;case`url`:Fc(n,`uri`,r.message,t);break;case`uuid`:Fc(n,`uuid`,r.message,t);break;case`regex`:G(n,r.regex,r.message,t);break;case`cuid`:G(n,Ac.cuid,r.message,t);break;case`cuid2`:G(n,Ac.cuid2,r.message,t);break;case`startsWith`:G(n,RegExp(`^${Mc(r.value,t)}`),r.message,t);break;case`endsWith`:G(n,RegExp(`${Mc(r.value,t)}$`),r.message,t);break;case`datetime`:Fc(n,`date-time`,r.message,t);break;case`date`:Fc(n,`date`,r.message,t);break;case`time`:Fc(n,`time`,r.message,t);break;case`duration`:Fc(n,`duration`,r.message,t);break;case`length`:U(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),U(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:G(n,RegExp(Mc(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Fc(n,`ipv4`,r.message,t),r.version!==`v4`&&Fc(n,`ipv6`,r.message,t);break;case`base64url`:G(n,Ac.base64url,r.message,t);break;case`jwt`:G(n,Ac.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&G(n,Ac.ipv4Cidr,r.message,t),r.version!==`v4`&&G(n,Ac.ipv6Cidr,r.message,t);break;case`emoji`:G(n,Ac.emoji(),r.message,t);break;case`ulid`:G(n,Ac.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Fc(n,`binary`,r.message,t);break;case`contentEncoding:base64`:U(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:G(n,Ac.base64,r.message,t);break}break;case`nanoid`:G(n,Ac.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function Mc(e,t){return t.patternStrategy===`escape`?Pc(e):e}let Nc=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Pc(e){let t=``;for(let n=0;n<e.length;n++)Nc.has(e[n])||(t+=`\\`),t+=e[n];return t}function Fc(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):U(e,`format`,t,n,r)}function G(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Ic(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):U(e,`pattern`,Ic(t,r),n,r)}function Ic(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
40
40
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
41
41
|
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Lc(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===b.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:K(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??W(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:K(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===b.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=jc(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===b.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===b.ZodBranded&&e.keyType._def.type._def.typeName===b.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=yc(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Rc(e,t){return t.mapStrategy===`record`?Lc(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[K(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||W(t),K(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||W(t)],minItems:2,maxItems:2}}}function zc(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function Bc(e){return e.target===`openAi`?void 0:{not:W({...e,currentPath:[...e.currentPath,`not`]})}}function Vc(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}let Hc={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Uc(e,t){if(t.target===`openApi3`)return Wc(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Hc&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Hc[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];case`symbol`:case`undefined`:case`function`:default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Wc(e,t)}let Wc=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>K(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Gc(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Hc[e.innerType._def.typeName],nullable:!0}:{type:[Hc[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=K(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=K(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Kc(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,mc(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?U(n,`minimum`,r.value,r.message,t):U(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),U(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?U(n,`maximum`,r.value,r.message,t):U(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),U(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:U(n,`multipleOf`,r.value,r.message,t);break}return n}function qc(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=Yc(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=K(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=Jc(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Jc(e,t){if(e.catchall._def.typeName!==`ZodNever`)return K(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Yc(e){try{return e.isOptional()}catch{return!0}}let Xc=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return K(e.innerType._def,t);let n=K(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:W(t)},n]}:W(t)},Zc=(e,t)=>{if(t.pipeStrategy===`input`)return K(e.in._def,t);if(t.pipeStrategy===`output`)return K(e.out._def,t);let n=K(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,K(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Qc(e,t){return K(e.type._def,t)}function $c(e,t){let n={type:`array`,uniqueItems:!0,items:K(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&U(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&U(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function el(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>K(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:K(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>K(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function tl(e){return{not:W(e)}}function nl(e){return W(e)}let rl=(e,t)=>K(e.innerType._def,t),il=(e,t,n)=>{switch(t){case b.ZodString:return jc(e,n);case b.ZodNumber:return Kc(e,n);case b.ZodObject:return qc(e,n);case b.ZodBigInt:return _c(e,n);case b.ZodBoolean:return vc();case b.ZodDate:return xc(e,n);case b.ZodUndefined:return tl(n);case b.ZodNull:return Vc(n);case b.ZodArray:return gc(e,n);case b.ZodUnion:case b.ZodDiscriminatedUnion:return Uc(e,n);case b.ZodIntersection:return Dc(e,n);case b.ZodTuple:return el(e,n);case b.ZodRecord:return Lc(e,n);case b.ZodLiteral:return Oc(e,n);case b.ZodEnum:return Tc(e);case b.ZodNativeEnum:return zc(e);case b.ZodNullable:return Gc(e,n);case b.ZodOptional:return Xc(e,n);case b.ZodMap:return Rc(e,n);case b.ZodSet:return $c(e,n);case b.ZodLazy:return()=>e.getter()._def;case b.ZodPromise:return Qc(e,n);case b.ZodNaN:case b.ZodNever:return Bc(n);case b.ZodEffects:return wc(e,n);case b.ZodAny:return W(n);case b.ZodUnknown:return nl(n);case b.ZodDefault:return Cc(e,n);case b.ZodBranded:return yc(e,n);case b.ZodReadonly:return rl(e,n);case b.ZodCatch:return bc(e,n);case b.ZodPipeline:return Zc(e,n);case b.ZodFunction:case b.ZodVoid:case b.ZodSymbol:return;default:return(e=>void 0)(t)}};function K(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==uc)return i}if(r&&!n){let e=al(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=il(e,e.typeName,t),o=typeof a==`function`?K(a(),t):a;if(o&&ol(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}let al=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:hc(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),W(t)):t.$refStrategy===`seen`?W(t):void 0}},ol=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),sl=(e,t)=>{let n=pc(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:K(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??W(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=K(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??W(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function cl(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!cl(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!cl(e[r],t[r]))return!1;return!0}return e===t}function ll(e){return encodeURI(ul(e))}function ul(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}let dl={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},fl={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},pl={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},ml=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 hl(e,t=Object.create(null),n=ml,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:hl(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,`__absolute_uri__`,{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.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,n.href);t.hash=t.hash,Object.defineProperty(e,`__absolute_recursive_ref__`,{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(pl[i])continue;let a=`${r}/${ll(i)}`,o=e[i];if(Array.isArray(o)){if(dl[i]){let e=o.length;for(let r=0;r<e;r++)hl(o[r],t,n,`${a}/${r}`)}}else if(fl[i])for(let e in o)hl(o[e],t,n,`${a}/${ll(e)}`);else hl(o,t,n,a)}return t}let gl=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_l=[0,31,28,31,30,31,30,31,31,30,31,30,31],vl=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,yl=/^(?=.{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,bl=/^(?:[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,xl=/^(?:(?:[^\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,Sl=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Cl=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,wl=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Tl=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,El=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Dl=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))},Ol=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,kl=/^((([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,Al=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 jl(e){return e.test.bind(e)}let Ml={date:Pl,time:Fl.bind(void 0,!1),"date-time":Ll,duration:Al,uri:Bl,"uri-reference":jl(bl),"uri-template":jl(xl),url:jl(Sl),email:Dl,hostname:jl(yl),ipv4:jl(Ol),ipv6:jl(kl),regex:Hl,uuid:jl(Cl),"json-pointer":jl(wl),"json-pointer-uri-fragment":jl(Tl),"relative-json-pointer":jl(El)};function Nl(e){return e%4==0&&(e%100!=0||e%400==0)}function Pl(e){let t=e.match(gl);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Nl(n)?29:_l[r])}function Fl(e,t){let n=t.match(vl);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 Il=/t|\s/i;function Ll(e){let t=e.split(Il);return t.length==2&&Pl(t[0])&&Fl(!0,t[1])}let Rl=/\/|:/,zl=/^(?:[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 Bl(e){return Rl.test(e)&&zl.test(e)}let Vl=/[^\\]\\Z/;function Hl(e){if(Vl.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function Ul(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 q(e,t,n=`2019-09`,r=hl(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:ee,required:te,not:ne,anyOf:re,allOf:g,oneOf:ie,if:ae,then:_,else:v,format:oe,properties:se,patternProperties:ce,additionalProperties:le,unevaluatedProperties:ue,minProperties:de,maxProperties:fe,propertyNames:pe,dependentRequired:me,dependentSchemas:he,dependencies:ge,prefixItems:_e,items:ve,additionalItems:ye,unevaluatedItems:be,contains:xe,minContains:Se,maxContains:Ce,minItems:we,maxItems:Te,uniqueItems:Ee,minimum:De,maximum:Oe,exclusiveMinimum:ke,exclusiveMaximum:Ae,multipleOf:je,minLength:Me,maxLength:Ne,pattern:Pe,__absolute_ref__:Fe,__absolute_recursive_ref__:Ie}=t,y=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[Ie]:a,u=`${s}/$recursiveRef`,d=q(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||y.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[Fe||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw Fe&&Fe!==d&&(e+=` Absolute URI "${Fe}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
42
|
-
- `)}`,Error(e)}let l=`${s}/$ref`,u=q(e,t,n,r,i,a,o,l,c);if(u.valid||y.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:y.length===0,errors:y}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?cl(e,h)||y.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&y.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),ee!==void 0&&(u===`object`||u===`array`?ee.some(t=>cl(e,t))||y.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(ee)}.`}):ee.some(t=>e===t)||y.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(ee)}.`})),ne!==void 0){let t=`${s}/not`;q(e,ne,n,r,i,a,o,t).valid&&y.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Le=[];if(re!==void 0){let t=`${s}/anyOf`,l=y.length,u=!1;for(let s=0;s<re.length;s++){let l=re[s],d=Object.create(c),f=q(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);y.push(...f.errors),u||=f.valid,f.valid&&Le.push(d)}u?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(g!==void 0){let t=`${s}/allOf`,l=y.length,u=!0;for(let s=0;s<g.length;s++){let l=g[s],d=Object.create(c),f=q(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);y.push(...f.errors),u&&=f.valid,f.valid&&Le.push(d)}u?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(ie!==void 0){let t=`${s}/oneOf`,l=y.length,u=ie.filter((s,l)=>{let u=Object.create(c),d=q(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return y.push(...d.errors),d.valid&&Le.push(u),d.valid}).length;u===1?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Le),ae!==void 0){let t=`${s}/if`;if(q(e,ae,n,r,i,a,o,t,c).valid){if(_!==void 0){let l=q(e,_,n,r,i,a,o,`${s}/then`,c);l.valid||y.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(v!==void 0){let l=q(e,v,n,r,i,a,o,`${s}/else`,c);l.valid||y.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(te!==void 0)for(let t of te)t in e||y.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(de!==void 0&&t.length<de&&y.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${de} properties.`}),fe!==void 0&&t.length>fe&&y.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${fe} properties.`}),pe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${ll(s)}`,c=q(s,pe,n,r,i,a,e,t);c.valid||y.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(me!==void 0){let t=`${s}/dependantRequired`;for(let n in me)if(n in e){let r=me[n];for(let i of r)i in e||y.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(he!==void 0)for(let t in he){let l=`${s}/dependentSchemas`;if(t in e){let s=q(e,he[t],n,r,i,a,o,`${l}/${ll(t)}`,c);s.valid||y.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ge!==void 0){let t=`${s}/dependencies`;for(let s in ge)if(s in e){let c=ge[s];if(Array.isArray(c))for(let n of c)n in e||y.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=q(e,c,n,r,i,a,o,`${t}/${ll(s)}`);l.valid||y.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(se!==void 0){let t=`${s}/properties`;for(let s in se){if(!(s in e))continue;let d=`${o}/${ll(s)}`,f=q(e[s],se[s],n,r,i,a,d,`${t}/${ll(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,y.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&ce!==void 0){let t=`${s}/patternProperties`;for(let s in ce){let d=new RegExp(s,`u`),f=ce[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${ll(p)}`,h=q(e[p],f,n,r,i,a,m,`${t}/${ll(s)}`);h.valid?c[p]=l[p]=!0:(u=i,y.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&le!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${ll(s)}`,f=q(e[s],le,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,y.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ue!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${ll(s)}`,u=q(e[s],ue,n,r,i,a,l,t);u.valid?c[s]=!0:y.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){Te!==void 0&&e.length>Te&&y.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${Te}).`}),we!==void 0&&e.length<we&&y.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${we}).`});let t=e.length,l=0,u=!1;if(_e!==void 0){let d=`${s}/prefixItems`,f=Math.min(_e.length,t);for(;l<f;l++){let t=q(e[l],_e[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ve!==void 0){let d=`${s}/items`;if(Array.isArray(ve)){let s=Math.min(ve.length,t);for(;l<s;l++){let t=q(e[l],ve[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=q(e[l],ve,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ye!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=q(e[l],ye,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,y.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(xe!==void 0)if(t===0&&Se===void 0)y.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(Se!==void 0&&t<Se)y.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${Se}).`});else{let l=`${s}/contains`,u=y.length,d=0;for(let s=0;s<t;s++){let t=q(e[s],xe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):y.push(...t.errors)}d>=(Se||0)&&(y.length=u),Se===void 0&&Ce===void 0&&d===0?y.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):Se!==void 0&&d<Se?y.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${Se} items matching schema. Only ${d} items were found.`}):Ce!==void 0&&d>Ce&&y.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${d} items were found.`})}if(!u&&be!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=q(e[l],be,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||y.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(Ee)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&cl(r,t))&&(y.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(De!==void 0&&(ke===!0&&e<=De||e<De)&&y.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ke?`or equal to `:``} ${De}.`}),Oe!==void 0&&(Ae===!0&&e>=Oe||e>Oe)&&y.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Ae?`or equal to `:``} ${Oe}.`})):(De!==void 0&&e<De&&y.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${De}.`}),Oe!==void 0&&e>Oe&&y.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Oe}.`}),ke!==void 0&&e<=ke&&y.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${ke}.`}),Ae!==void 0&&e>=Ae&&y.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ae}.`})),je!==void 0){let t=e%je;Math.abs(0-t)>=1.1920929e-7&&Math.abs(je-t)>=1.1920929e-7&&y.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${je}.`})}}else if(u===`string`){let t=Me===void 0&&Ne===void 0?0:Ul(e);Me!==void 0&&t<Me&&y.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Me}).`}),Ne!==void 0&&t>Ne&&y.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${Ne}).`}),Pe!==void 0&&!new RegExp(Pe,`u`).test(e)&&y.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),oe!==void 0&&Ml[oe]&&!Ml[oe](e)&&y.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${oe}".`})}return{valid:y.length===0,errors:y}}var Wl=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=hl(e)}validate(e){return q(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),hl(e,this.lookup)}};let Gl=`Failed to parse input arguments`,Kl=`Tool was executed but the invocation failed. For example, the script function threw an error`,ql=`Tool was cancelled`,Jl={type:`object`,properties:{}},Yl=[`draft-2020-12`,`draft-07`],Xl=Symbol(`standardValidator`),Zl={installed:!1,previousModelContextDescriptor:void 0,previousModelContextTestingDescriptor:void 0};var Ql=class{tools=new Map;toolsChangedCallback=null;provideContext(e={}){let t=new Map;for(let n of e.tools??[]){let e=lu(n,t);t.set(e.name,e)}this.tools=t,this.notifyToolsChanged()}clearContext(){this.tools.clear(),this.notifyToolsChanged()}registerTool(e){let t=lu(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 $l(ql);let r=this.tools.get(e);if(!r)throw $l(`Tool not found: ${e}`);let i=eu(t),a=await pu(i,r);if(a)throw $l(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 xu(yu(await Su(Promise.resolve(e),n?.signal)))}catch(e){throw $l(e instanceof Error?`${Kl}: ${e.message}`:Kl)}finally{o=!1}}notifyToolsChanged(){this.toolsChangedCallback&&queueMicrotask(()=>{try{this.toolsChangedCallback?.()}catch(e){console.warn(`[WebMCPPolyfill] toolsChanged callback threw:`,e)}})}};function $l(e){try{return new DOMException(e,`UnknownError`)}catch{let t=Error(e);return t.name=`UnknownError`,t}}function eu(e){let t;try{t=JSON.parse(e)}catch{throw $l(Gl)}if(!t||typeof t!=`object`||Array.isArray(t))throw $l(Gl);return t}function J(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function tu(e){if(!J(e))return null;let t=e[`~standard`];return J(t)?t:null}function nu(e){let t=tu(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function ru(e){let t=tu(e);return!t||t.version!==1||!J(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function iu(e){return{"~standard":{version:1,vendor:`@mcp-b/webmcp-polyfill-json-schema`,validate(t){if(!J(t))return{issues:[{message:`expected object arguments`}]};let n=uu(t,e);return n?{issues:[n]}:{value:t}}}}}function au(e){for(let t of Yl)try{let n=e[`~standard`].jsonSchema.input({target:t});return su(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 ou(e){if(e===void 0){let e=Jl;return{inputSchema:e,standardValidator:iu(e)}}if(ru(e)){let t=au(e);return{inputSchema:t,standardValidator:iu(t)}}if(nu(e))return{inputSchema:Jl,standardValidator:e};if(su(e),Object.keys(e).length===0)return{inputSchema:Jl,standardValidator:iu(Jl)};let t=e.type===void 0?{type:`object`,...e}:e;return{inputSchema:t,standardValidator:iu(t)}}function su(e){if(!J(e))throw Error(`inputSchema must be a JSON Schema object`);cu(e,`$`)}function cu(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(!J(i))throw Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[e,n]of Object.entries(i)){if(!J(n))throw Error(`Invalid JSON Schema at ${t}.properties.${e}: expected object schema`);cu(n,`${t}.properties.${e}`)}}let a=e.items;if(a!==void 0)if(Array.isArray(a))for(let[e,n]of a.entries()){if(!J(n))throw Error(`Invalid JSON Schema at ${t}.items[${e}]: expected object schema`);cu(n,`${t}.items[${e}]`)}else if(J(a))cu(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(!J(i))throw Error(`Invalid JSON Schema at ${t}.${n}[${e}]: expected object schema`);cu(i,`${t}.${n}[${e}]`)}}}let o=e.not;if(o!==void 0){if(!J(o))throw Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);cu(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function lu(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=ou(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,[Xl]:n.standardValidator}}function uu(e,t){let n=new Wl(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 du(e){if(!e||e.length===0)return null;let t=e.map(e=>J(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 fu(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=du(r?.path);return i?`Input validation error: ${r.message} at ${i}`:`Input validation error: ${r.message}`}async function pu(e,t){return fu(e,t[Xl])}function mu(e){return J(e)&&Array.isArray(e.content)}function hu(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function gu(e){return hu(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>gu(e)):J(e)?Object.values(e).every(e=>gu(e)):!1}function _u(e){if(!(!J(e)||!gu(e)))return e}function vu(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function yu(e){if(mu(e))return e;let t=_u(e);return{content:[{type:`text`,text:vu(e)}],...t?{structuredContent:t}:{},isError:!1}}function bu(e){for(let t of e.content??[])if(t.type===`text`&&`text`in t&&typeof t.text==`string`)return t.text;return null}function xu(e){if(e.isError)throw $l(bu(e)?.replace(/^Error:\s*/i,``).trim()||Kl);let t=e.metadata;if(t&&typeof t==`object`&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw $l(Kl)}}function Su(e,t){return t?t.aborted?Promise.reject($l(ql)):new Promise((n,r)=>{let i=()=>{a(),r($l(ql))},a=()=>{t.removeEventListener(`abort`,i)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}function Cu(){return typeof navigator<`u`?navigator:null}function wu(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function Tu(e){let t=Cu();if(!t||t.modelContext)return;Zl.installed&&Eu();let n=new Ql,r=n;r.__isWebMCPPolyfill=!0,Zl.previousModelContextDescriptor=Object.getOwnPropertyDescriptor(t,`modelContext`),Zl.previousModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,`modelContextTesting`),wu(t,`modelContext`,r);let i=e?.installTestingShim??`if-missing`,a=!!t.modelContextTesting;(i===`always`||(i===!0||i===`if-missing`)&&!a)&&wu(t,`modelContextTesting`,n.getTestingShim()),Zl.installed=!0}function Eu(){let e=Cu();if(!e||!Zl.installed)return;let t=(t,n)=>{if(n){Object.defineProperty(e,t,n);return}delete e[t]};t(`modelContext`,Zl.previousModelContextDescriptor),t(`modelContextTesting`,Zl.previousModelContextTestingDescriptor),Zl.installed=!1,Zl.previousModelContextDescriptor=void 0,Zl.previousModelContextTestingDescriptor=void 0}if(typeof window<`u`&&typeof document<`u`){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{Tu(e)}catch(e){console.error(`[WebMCPPolyfill] Auto-initialization failed:`,e)}}function Du(e){return!!e._zod}function Ou(e){let t=Object.values(e);if(t.length===0)return jo({});let n=t.every(Du),r=t.every(e=>!Du(e));if(n)return jo(e);if(r)return ht(e);throw Error(`Mixed Zod versions detected in object shape.`)}function ku(e,t){return Du(e)?dn(e,t):e.safeParse(t)}async function Au(e,t){return Du(e)?await pn(e,t):await e.safeParseAsync(t)}function ju(e){if(!e)return;let t;if(t=Du(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Mu(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return Ou(e)}}if(Du(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Nu(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Pu(e){return e.description}function Fu(e){if(Du(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Iu(e){if(Du(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}let Lu=`2025-11-25`,Ru=[Lu,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],zu=`io.modelcontextprotocol/related-task`,Y=oc(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Bu=R([A(),M().int()]),Vu=A();L({ttl:R([M(),Es()]).optional(),pollInterval:M().optional()});let Hu=I({ttl:M().optional()}),Uu=I({taskId:A()}),Wu=L({progressToken:Bu.optional(),[zu]:Uu.optional()}),Gu=I({_meta:Wu.optional()}),Ku=Gu.extend({task:Hu.optional()}),qu=e=>Ku.safeParse(e).success,X=I({method:A(),params:Gu.loose().optional()}),Ju=I({_meta:Wu.optional()}),Yu=I({method:A(),params:Ju.loose().optional()}),Z=L({_meta:Wu.optional()}),Xu=R([A(),M().int()]),Zu=I({jsonrpc:V(`2.0`),id:Xu,...X.shape}).strict(),Qu=e=>Zu.safeParse(e).success,$u=I({jsonrpc:V(`2.0`),...Yu.shape}).strict(),ed=e=>$u.safeParse(e).success,td=I({jsonrpc:V(`2.0`),id:Xu,result:Z}).strict(),nd=e=>td.safeParse(e).success;var Q;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Q||={});let rd=I({jsonrpc:V(`2.0`),id:Xu.optional(),error:I({code:M().int(),message:A(),data:P().optional()})}).strict(),id=e=>rd.safeParse(e).success,ad=R([Zu,$u,td,rd]);R([td,rd]);let od=Z.strict(),sd=Ju.extend({requestId:Xu.optional(),reason:A().optional()}),cd=Yu.extend({method:V(`notifications/cancelled`),params:sd}),ld=I({icons:F(I({src:A(),mimeType:A().optional(),sizes:F(A()).optional(),theme:B([`light`,`dark`]).optional()})).optional()}),ud=I({name:A(),title:A().optional()}),dd=ud.extend({...ud.shape,...ld.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),fd=lc(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Is(I({form:Is(I({applyDefaults:N().optional()}),z(A(),P())).optional(),url:Y.optional()}),z(A(),P()).optional())),pd=L({list:Y.optional(),cancel:Y.optional(),requests:L({sampling:L({createMessage:Y.optional()}).optional(),elicitation:L({create:Y.optional()}).optional()}).optional()}),md=L({list:Y.optional(),cancel:Y.optional(),requests:L({tools:L({call:Y.optional()}).optional()}).optional()}),hd=I({experimental:z(A(),Y).optional(),sampling:I({context:Y.optional(),tools:Y.optional()}).optional(),elicitation:fd.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:pd.optional()}),gd=Gu.extend({protocolVersion:A(),capabilities:hd,clientInfo:dd}),_d=X.extend({method:V(`initialize`),params:gd}),vd=I({experimental:z(A(),Y).optional(),logging:Y.optional(),completions:Y.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:md.optional()}),yd=Z.extend({protocolVersion:A(),capabilities:vd,serverInfo:dd,instructions:A().optional()}),bd=Yu.extend({method:V(`notifications/initialized`),params:Ju.optional()}),xd=X.extend({method:V(`ping`),params:Gu.optional()}),Sd=I({progress:M(),total:H(M()),message:H(A())}),Cd=I({...Ju.shape,...Sd.shape,progressToken:Bu}),wd=Yu.extend({method:V(`notifications/progress`),params:Cd}),Td=Gu.extend({cursor:Vu.optional()}),Ed=X.extend({params:Td.optional()}),Dd=Z.extend({nextCursor:Vu.optional()}),Od=B([`working`,`input_required`,`completed`,`failed`,`cancelled`]),kd=I({taskId:A(),status:Od,ttl:R([M(),Es()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:H(M()),statusMessage:H(A())}),Ad=Z.extend({task:kd}),jd=Ju.merge(kd),Md=Yu.extend({method:V(`notifications/tasks/status`),params:jd}),Nd=X.extend({method:V(`tasks/get`),params:Gu.extend({taskId:A()})}),Pd=Z.merge(kd),Fd=X.extend({method:V(`tasks/result`),params:Gu.extend({taskId:A()})});Z.loose();let Id=Ed.extend({method:V(`tasks/list`)}),Ld=Dd.extend({tasks:F(kd)}),Rd=X.extend({method:V(`tasks/cancel`),params:Gu.extend({taskId:A()})}),zd=Z.merge(kd),Bd=I({uri:A(),mimeType:H(A()),_meta:z(A(),P()).optional()}),Vd=Bd.extend({text:A()}),Hd=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Ud=Bd.extend({blob:Hd}),Wd=B([`user`,`assistant`]),Gd=I({audience:F(Wd).optional(),priority:M().min(0).max(1).optional(),lastModified:No({offset:!0}).optional()}),Kd=I({...ud.shape,...ld.shape,uri:A(),description:H(A()),mimeType:H(A()),annotations:Gd.optional(),_meta:H(L({}))}),qd=I({...ud.shape,...ld.shape,uriTemplate:A(),description:H(A()),mimeType:H(A()),annotations:Gd.optional(),_meta:H(L({}))}),Jd=Ed.extend({method:V(`resources/list`)}),Yd=Dd.extend({resources:F(Kd)}),Xd=Ed.extend({method:V(`resources/templates/list`)}),Zd=Dd.extend({resourceTemplates:F(qd)}),Qd=Gu.extend({uri:A()}),$d=Qd,ef=X.extend({method:V(`resources/read`),params:$d}),tf=Z.extend({contents:F(R([Vd,Ud]))}),nf=Yu.extend({method:V(`notifications/resources/list_changed`),params:Ju.optional()}),rf=Qd,af=X.extend({method:V(`resources/subscribe`),params:rf}),of=Qd,sf=X.extend({method:V(`resources/unsubscribe`),params:of}),cf=Ju.extend({uri:A()}),lf=Yu.extend({method:V(`notifications/resources/updated`),params:cf}),uf=I({name:A(),description:H(A()),required:H(N())}),df=I({...ud.shape,...ld.shape,description:H(A()),arguments:H(F(uf)),_meta:H(L({}))}),ff=Ed.extend({method:V(`prompts/list`)}),pf=Dd.extend({prompts:F(df)}),mf=Gu.extend({name:A(),arguments:z(A(),A()).optional()}),hf=X.extend({method:V(`prompts/get`),params:mf}),gf=I({type:V(`text`),text:A(),annotations:Gd.optional(),_meta:z(A(),P()).optional()}),_f=I({type:V(`image`),data:Hd,mimeType:A(),annotations:Gd.optional(),_meta:z(A(),P()).optional()}),vf=I({type:V(`audio`),data:Hd,mimeType:A(),annotations:Gd.optional(),_meta:z(A(),P()).optional()}),yf=I({type:V(`tool_use`),name:A(),id:A(),input:z(A(),P()),_meta:z(A(),P()).optional()}),bf=I({type:V(`resource`),resource:R([Vd,Ud]),annotations:Gd.optional(),_meta:z(A(),P()).optional()}),xf=R([gf,_f,vf,Kd.extend({type:V(`resource_link`)}),bf]),Sf=I({role:Wd,content:xf}),Cf=Z.extend({description:A().optional(),messages:F(Sf)}),wf=Yu.extend({method:V(`notifications/prompts/list_changed`),params:Ju.optional()}),Tf=I({title:A().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Ef=I({taskSupport:B([`required`,`optional`,`forbidden`]).optional()}),Df=I({...ud.shape,...ld.shape,description:A().optional(),inputSchema:I({type:V(`object`),properties:z(A(),Y).optional(),required:F(A()).optional()}).catchall(P()),outputSchema:I({type:V(`object`),properties:z(A(),Y).optional(),required:F(A()).optional()}).catchall(P()).optional(),annotations:Tf.optional(),execution:Ef.optional(),_meta:z(A(),P()).optional()}),Of=Ed.extend({method:V(`tools/list`)}),kf=Dd.extend({tools:F(Df)}),Af=Z.extend({content:F(xf).default([]),structuredContent:z(A(),P()).optional(),isError:N().optional()});Af.or(Z.extend({toolResult:P()}));let jf=Ku.extend({name:A(),arguments:z(A(),P()).optional()}),Mf=X.extend({method:V(`tools/call`),params:jf}),Nf=Yu.extend({method:V(`notifications/tools/list_changed`),params:Ju.optional()});I({autoRefresh:N().default(!0),debounceMs:M().int().nonnegative().default(300)});let Pf=B([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Ff=Gu.extend({level:Pf}),If=X.extend({method:V(`logging/setLevel`),params:Ff}),Lf=Ju.extend({level:Pf,logger:A().optional(),data:P()}),Rf=Yu.extend({method:V(`notifications/message`),params:Lf}),zf=I({hints:F(I({name:A().optional()})).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),Bf=I({mode:B([`auto`,`required`,`none`]).optional()}),Vf=I({type:V(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:F(xf).default([]),structuredContent:I({}).loose().optional(),isError:N().optional(),_meta:z(A(),P()).optional()}),Hf=Ps(`type`,[gf,_f,vf]),Uf=Ps(`type`,[gf,_f,vf,yf,Vf]),Wf=I({role:Wd,content:R([Uf,F(Uf)]),_meta:z(A(),P()).optional()}),Gf=Ku.extend({messages:F(Wf),modelPreferences:zf.optional(),systemPrompt:A().optional(),includeContext:B([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(A()).optional(),metadata:Y.optional(),tools:F(Df).optional(),toolChoice:Bf.optional()}),Kf=X.extend({method:V(`sampling/createMessage`),params:Gf}),qf=Z.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:Wd,content:Hf}),Jf=Z.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:Wd,content:R([Uf,F(Uf)])}),Yf=I({type:V(`boolean`),title:A().optional(),description:A().optional(),default:N().optional()}),Xf=I({type:V(`string`),title:A().optional(),description:A().optional(),minLength:M().optional(),maxLength:M().optional(),format:B([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),Zf=I({type:B([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),Qf=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),default:A().optional()}),$f=I({type:V(`string`),title:A().optional(),description:A().optional(),oneOf:F(I({const:A(),title:A()})),default:A().optional()}),ep=R([R([I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),enumNames:F(A()).optional(),default:A().optional()}),R([Qf,$f]),R([I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:V(`string`),enum:F(A())}),default:F(A()).optional()}),I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:A(),title:A()}))}),default:F(A()).optional()})])]),Yf,Xf,Zf]),tp=R([Ku.extend({mode:V(`form`).optional(),message:A(),requestedSchema:I({type:V(`object`),properties:z(A(),ep),required:F(A()).optional()})}),Ku.extend({mode:V(`url`),message:A(),elicitationId:A(),url:A().url()})]),np=X.extend({method:V(`elicitation/create`),params:tp}),rp=Ju.extend({elicitationId:A()}),ip=Yu.extend({method:V(`notifications/elicitation/complete`),params:rp}),ap=Z.extend({action:B([`accept`,`decline`,`cancel`]),content:lc(e=>e===null?void 0:e,z(A(),R([A(),M(),N(),F(A())])).optional())}),op=I({type:V(`ref/resource`),uri:A()}),sp=I({type:V(`ref/prompt`),name:A()}),cp=Gu.extend({ref:R([sp,op]),argument:I({name:A(),value:A()}),context:I({arguments:z(A(),A()).optional()}).optional()}),lp=X.extend({method:V(`completion/complete`),params:cp});function up(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function dp(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}let fp=Z.extend({completion:L({values:F(A()).max(100),total:H(M().int()),hasMore:H(N())})}),pp=I({uri:A().startsWith(`file://`),name:A().optional(),_meta:z(A(),P()).optional()}),mp=X.extend({method:V(`roots/list`),params:Gu.optional()}),hp=Z.extend({roots:F(pp)}),gp=Yu.extend({method:V(`notifications/roots/list_changed`),params:Ju.optional()});R([xd,_d,lp,If,hf,ff,Jd,Xd,ef,af,sf,Mf,Of,Nd,Fd,Id,Rd]),R([cd,wd,bd,gp,Md]),R([od,qf,Jf,ap,hp,Pd,Ld,Ad]),R([xd,Kf,np,mp,Nd,Fd,Id,Rd]),R([cd,wd,Rf,lf,nf,Nf,wf,Md,ip]),R([od,yd,fp,Cf,pf,Yd,Zd,tf,Af,kf,Pd,Ld,Ad]);var $=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Q.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new _p(e.elicitations,n)}return new e(t,n,r)}},_p=class extends ${constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Q.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function vp(e){return e===`completed`||e===`failed`||e===`cancelled`}function yp(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function bp(e,t){return Du(e)?Oo(e,{target:yp(t?.target),io:t?.pipeStrategy??`input`}):sl(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function xp(e){let t=ju(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Iu(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Sp(e,t){let n=ku(e,t);if(!n.success)throw n.error;return n.data}var Cp=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(cd,e=>{this._oncancel(e)}),this.setNotificationHandler(wd,e=>{this._onprogress(e)}),this.setRequestHandler(xd,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Nd,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new $(Q.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Fd,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new $(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new $(Q.InvalidParams,`Task not found: ${r}`);if(!vp(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(vp(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[zu]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Id,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new $(Q.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Rd,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new $(Q.InvalidParams,`Task not found: ${e.params.taskId}`);if(vp(n.status))throw new $(Q.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new $(Q.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof $?e:new $(Q.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),$.fromError(Q.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),nd(e)||id(e)?this._onresponse(e):Qu(e)?this._onrequest(e,t):ed(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=$.fromError(Q.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[zu]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Q.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=qu(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new $(Q.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Q.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),nd(e)?n(e):n(new $(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(nd(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),nd(e)?r(e):r($.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof $?e:new $(Q.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Ad,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new $(Q.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},vp(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new $(Q.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new $(Q.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof $?e:new $(Q.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[zu]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof $?e:new $(Q.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=ku(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p($.fromError(Q.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Pd,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Ld,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},zd,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[zu]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[zu]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[zu]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=xp(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Sp(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=xp(e);this._notificationHandlers.set(n,n=>{let r=Sp(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&Qu(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new $(Q.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new $(Q.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new $(Q.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new $(Q.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Md.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),vp(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new $(Q.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(vp(a.status))throw new $(Q.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Md.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),vp(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function wp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Tp(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];wp(a)&&wp(i)?n[r]={...a,...i}:n[r]=i}return n}var Ep=class{compile(e){throw Error(`[WebMCP] Ajv stub was invoked. This indicates the MCP SDK is bypassing PolyfillJsonSchemaValidator. Please report this as a bug.`)}getSchema(e){}errorsText(e){return``}};function Dp(){return new Ep({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0})}var Op=class{constructor(e){this._ajv=e??Dp()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};function kp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function Ap(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var jp=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}},Mp=class extends Cp{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Pf.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Op,this.setRequestHandler(_d,e=>this._oninitialize(e)),this.setNotificationHandler(bd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(If,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Pf.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new jp(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Tp(this._capabilities,e)}setRequestHandler(e,t){let n=ju(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(Du(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=ku(Mf,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new $(Q.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=ku(Ad,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new $(Q.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=ku(Af,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new $(Q.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){Ap(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&kp(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Ru.includes(t)?t:Lu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},od)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},Jf,t):this.request({method:`sampling/createMessage`,params:e},qf,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},ap,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},ap,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new $(Q.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof $?e:new $(Q.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},hp,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};let Np=Symbol.for(`mcp.completable`);function Pp(e){return!!e&&typeof e==`object`&&Np in e}function Fp(e){return e[Np]?.complete}var Ip;(function(e){e.Completable=`McpCompletable`})(Ip||={});let Lp=/^[A-Za-z0-9._-]{1,128}$/;function Rp(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Lp.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function zp(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Bp(e){let t=Rp(e);return zp(e,t.warnings),t.isValid}var Vp=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Hp=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Mp(e,t)}get experimental(){return this._experimental||={tasks:new Vp(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Yp(Of)),this.server.assertCanSetRequestHandler(Yp(Mf)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Of,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=Mu(t.inputSchema);return e?bp(e,{strictUnions:!0,pipeStrategy:`input`}):Up})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=Mu(t.outputSchema);e&&(n.outputSchema=bp(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Mf,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new $(Q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new $(Q.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new $(Q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof $&&e.code===Q.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Au(Mu(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=Nu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new $(Q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Au(Mu(e.outputSchema),t.structuredContent);if(!r.success){let e=Nu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new $(Q.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Yp(lp)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(lp,async e=>{switch(e.params.ref.type){case`ref/prompt`:return up(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return dp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new $(Q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Zp;let r=ju(n.argsSchema)?.[e.params.argument.name];if(!Pp(r))return Zp;let i=Fp(r);return i?Xp(await i(e.params.argument.value,e.params.context)):Zp}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Zp;throw new $(Q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Xp(await r(e.params.argument.value,e.params.context)):Zp}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Yp(Jd)),this.server.assertCanSetRequestHandler(Yp(Xd)),this.server.assertCanSetRequestHandler(Yp(ef)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Jd,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Xd,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(ef,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new $(Q.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new $(Q.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Yp(ff)),this.server.assertCanSetRequestHandler(Yp(hf)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ff,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Jp(t.argsSchema):void 0}))})),this.server.setRequestHandler(hf,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await Au(Mu(n.argsSchema),e.params.arguments);if(!r.success){let t=Nu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:Ou(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=Ou(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Pp(e instanceof Hs?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Bp(e);let l={title:t,description:n,inputSchema:qp(r),outputSchema:qp(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Bp(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=Ou(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=Ou(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let e=t[0];Kp(e)?(r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Kp(t[0])&&(i=t.shift())):typeof e==`object`&&e&&(i=t.shift())}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};let Up={type:`object`,properties:{}};function Wp(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Gp(e){return`_def`in e||`_zod`in e||Wp(e)}function Kp(e){return typeof e!=`object`||!e||Gp(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Wp)}function qp(e){if(e)return Kp(e)?Ou(e):e}function Jp(e){let t=ju(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:Pu(t),required:!Fu(t)})):[]}function Yp(e){let t=ju(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Iu(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Xp(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let Zp={completion:{values:[],hasMore:!1}};var Qp=class{getValidator(e){return t=>{if(!J(t))return{valid:!1,data:void 0,errorMessage:`expected object arguments`};let n=uu(t,e);return n?{valid:!1,data:void 0,errorMessage:n.message}:{valid:!0,data:t,errorMessage:void 0}}}};let $p={type:`object`,properties:{}},em=`__isBrowserMcpServer`;function tm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function nm(e){return tm(e)&&Array.isArray(e.content)}function rm(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function im(e){return rm(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>im(e)):tm(e)?Object.values(e).every(e=>im(e)):!1}function am(e){if(!(!tm(e)||!im(e)))return e}function om(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function sm(e){if(nm(e))return e;let t=am(e);return{content:[{type:`text`,text:om(e)}],...t?{structuredContent:t}:{},isError:!1}}function cm(e){return e?.signal?e:{...e,signal:AbortSignal.timeout(1e4)}}var lm=class extends Hp{[em]=!0;native;_promptSchemas=new Map;_jsonValidator;_publicMethodsBound=!1;constructor(e,t){let n=new Qp,r={capabilities:Tp(t?.capabilities||{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}}),jsonSchemaValidator:t?.jsonSchemaValidator??n};super(e,r),this._jsonValidator=n,this.native=t?.native,this.bindPublicApiMethods()}bindPublicApiMethods(){this._publicMethodsBound||=(this.registerTool=this.registerTool.bind(this),this.unregisterTool=this.unregisterTool.bind(this),this.provideContext=this.provideContext.bind(this),this.clearContext=this.clearContext.bind(this),this.listTools=this.listTools.bind(this),this.callTool=this.callTool.bind(this),this.executeTool=this.executeTool.bind(this),this.registerResource=this.registerResource.bind(this),this.listResources=this.listResources.bind(this),this.readResource=this.readResource.bind(this),this.registerPrompt=this.registerPrompt.bind(this),this.listPrompts=this.listPrompts.bind(this),this.getPrompt=this.getPrompt.bind(this),this.createMessage=this.createMessage.bind(this),this.elicitInput=this.elicitInput.bind(this),!0)}get _parentTools(){return this._registeredTools}get _parentResources(){return this._registeredResources}get _parentPrompts(){return this._registeredPrompts}toTransportSchema(e,t=!0){if(!e||typeof e!=`object`)return t?(console.warn(`[BrowserMcpServer] toTransportSchema received non-object schema (${typeof e}), using default`),$p):{};let n=Mu(e),r=n?bp(n,{strictUnions:!0,pipeStrategy:`input`}):e;return Object.keys(r).length===0?t?$p:r:t&&r.type===void 0?{type:`object`,...r}:r}isZodSchema(e){if(!e||typeof e!=`object`)return!1;let t=e;return`_zod`in t||`_def`in t}getNativeToolsApi(){if(!this.native)return;let e=this.native;if(!(typeof e.listTools!=`function`||typeof e.callTool!=`function`))return e}registerToolInServer(e){let t=this.toTransportSchema(e.inputSchema);return super.registerTool(e.name,{description:e.description,inputSchema:t,...e.outputSchema?{outputSchema:e.outputSchema}:{},...e.annotations?{annotations:e.annotations}:{}},async t=>sm(await e.execute(t,{requestUserInteraction:async e=>e()}))),{unregister:()=>this.unregisterTool(e.name)}}backfillTools(e,t){let n=0;for(let r of e){if(!r?.name||this._parentTools[r.name])continue;let e={name:r.name,description:r.description??``,inputSchema:r.inputSchema??$p,execute:async e=>t(r.name,e)};r.outputSchema&&(e.outputSchema=r.outputSchema),r.annotations&&(e.annotations=r.annotations),this.registerToolInServer(e),n++}return n}registerTool(e){this.native&&this.native.registerTool(e);try{return this.registerToolInServer(e)}catch(t){if(this.native)try{this.native.unregisterTool(e.name)}catch(e){console.error(`[BrowserMcpServer] Rollback of native tool registration failed:`,e)}throw t}}syncNativeTools(){let e=this.getNativeToolsApi();if(!e)return 0;let t=e.callTool.bind(e);return this.backfillTools(e.listTools(),async(e,n)=>t({name:e,arguments:n}))}unregisterTool(e){this._parentTools[e]?.remove(),this.native&&this.native.unregisterTool(e)}registerResource(e){let t=super.registerResource(e.name,e.uri,{...e.description!==void 0&&{description:e.description},...e.mimeType!==void 0&&{mimeType:e.mimeType}},async t=>({contents:(await e.read(t)).contents}));return{unregister:()=>t.remove()}}registerPrompt(e){e.argsSchema&&this._promptSchemas.set(e.name,e.argsSchema);let t=super.registerPrompt(e.name,{...e.description!==void 0&&{description:e.description}},async t=>({messages:(await e.get(t)).messages}));return{unregister:()=>{this._promptSchemas.delete(e.name),t.remove()}}}provideContext(e){for(let e of Object.values(this._parentTools))e.remove();this.native&&this.native.clearContext();for(let t of e?.tools??[])this.registerTool(t)}clearContext(){for(let e of Object.values(this._parentTools))e.remove();this.native&&this.native.clearContext()}listResources(){return Object.entries(this._parentResources).filter(([,e])=>e.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata}))}async readResource(e){let t=this._parentResources[e];if(!t)throw Error(`Resource not found: ${e}`);return t.readCallback(new URL(e),{})}listPrompts(){return Object.entries(this._parentPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{let n=this._promptSchemas.get(e);return{name:e,...t.description!==void 0&&{description:t.description},...n?.properties?{arguments:Object.entries(n.properties).map(([e,t])=>({name:e,...typeof t==`object`&&t&&`description`in t?{description:t.description}:{},...n.required?.includes(e)?{required:!0}:{}}))}:{}}})}async getPrompt(e,t={}){let n=this._parentPrompts[e];if(!n)throw Error(`Prompt not found: ${e}`);let r=this._promptSchemas.get(e);if(r){let n=this._jsonValidator.getValidator(r)(t);if(!n.valid)throw Error(`Invalid arguments for prompt ${e}: ${n.errorMessage}`)}return n.callback(t,{})}listTools(){return Object.entries(this._parentTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,description:t.description??``,inputSchema:this.toTransportSchema(t.inputSchema??$p)};return t.outputSchema&&(n.outputSchema=this.toTransportSchema(t.outputSchema,!1)),t.annotations&&(n.annotations=t.annotations),n})}async validateToolInput(e,t,n){if(!e.inputSchema)return;if(this.isZodSchema(e.inputSchema)){let r=await Au(e.inputSchema,t??{});if(!r.success)throw Error(`Invalid arguments for tool ${n}: ${Nu(r.error)}`);return r.data}let r=this._jsonValidator.getValidator(e.inputSchema)(t??{});if(!r.valid)throw Error(`Invalid arguments for tool ${n}: ${r.errorMessage}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;let r=t;if(!(`content`in r)||r.isError||!r.structuredContent)return;if(this.isZodSchema(e.outputSchema)){let t=await Au(e.outputSchema,r.structuredContent);if(!t.success)throw Error(`Output validation error: Invalid structured content for tool ${n}: ${Nu(t.error)}`);return}let i=this._jsonValidator.getValidator(e.outputSchema)(r.structuredContent);if(!i.valid)throw Error(`Output validation error: Invalid structured content for tool ${n}: ${i.errorMessage}`)}async callTool(e){let t=this._parentTools[e.name];if(!t)throw Error(`Tool not found: ${e.name}`);return t.handler(e.arguments??{},{})}async executeTool(e,t={}){return this.callTool({name:e,arguments:t})}async connect(e){return this.setToolRequestHandlers(),this.setResourceRequestHandlers(),this.setPromptRequestHandlers(),this.server.setRequestHandler(Of,()=>({tools:this.listTools()})),this.server.setRequestHandler(ff,()=>({prompts:this.listPrompts()})),this.server.setRequestHandler(hf,async e=>{let t=this._parentPrompts[e.params.name];if(!t)throw Error(`Prompt ${e.params.name} not found`);if(!t.enabled)throw Error(`Prompt ${e.params.name} disabled`);let n=this._promptSchemas.get(e.params.name);if(n){let r=this._jsonValidator.getValidator(n)(e.params.arguments??{});if(!r.valid)throw Error(`Invalid arguments for prompt ${e.params.name}: ${r.errorMessage}`);return t.callback(e.params.arguments,{})}return t.callback({},{})}),super.connect(e)}async createMessage(e,t){return this.server.createMessage(e,cm(t))}async elicitInput(e,t){return this.server.elicitInput(e,cm(t))}};(function(e){return e.START=`start`,e.STARTED=`started`,e.STOP=`stop`,e.STOPPED=`stopped`,e.PING=`ping`,e.PONG=`pong`,e.ERROR=`error`,e.LIST_TOOLS=`list_tools`,e.CALL_TOOL=`call_tool`,e.TOOL_LIST_UPDATED=`tool_list_updated`,e.TOOL_LIST_UPDATED_ACK=`tool_list_updated_ack`,e.PROCESS_DATA=`process_data`,e.SERVER_STARTED=`server_started`,e.SERVER_STOPPED=`server_stopped`,e.ERROR_FROM_NATIVE_HOST=`error_from_native_host`,e.CONNECT_NATIVE=`connectNative`,e.PING_NATIVE=`ping_native`,e.DISCONNECT_NATIVE=`disconnect_native`,e})({}),{NAME:`com.chromemcp.nativehost`,DEFAULT_PORT:12306}.NAME;var um=class{_started=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;_serverReadyTimeout;_serverReadyRetryMs;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins||e.allowedOrigins.length===0)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=e.allowedOrigins,this._channelId=e.channelId||`mcp-iframe`,this._serverReadyRetryMs=e.serverReadyRetryMs??250}async start(){if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(!this._allowedOrigins.includes(e.origin)&&!this._allowedOrigins.includes(`*`)||e.data?.channel!==this._channelId||e.data?.type!==`mcp`||e.data?.direction!==`client-to-server`)return;this._clientOrigin=e.origin;let t=e.data.payload;if(typeof t==`string`&&t===`mcp-check-ready`){this.broadcastServerReady();return}try{let e=ad.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this.broadcastServerReady()}broadcastServerReady(){window.parent&&window.parent!==window?(window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},`*`),this.clearServerReadyRetry()):this.scheduleServerReadyRetry()}scheduleServerReadyRetry(){this._serverReadyTimeout||=setTimeout(()=>{this._serverReadyTimeout=void 0,this._started&&this.broadcastServerReady()},this._serverReadyRetryMs)}clearServerReadyRetry(){this._serverReadyTimeout&&=(clearTimeout(this._serverReadyTimeout),void 0)}async send(e){if(!this._started)throw Error(`Transport not started`);if(!this._clientOrigin){console.debug(`[IframeChildTransport] No client connected, message not sent`);return}window.parent&&window.parent!==window?window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this._clientOrigin):console.debug(`[IframeChildTransport] Not running in an iframe, message not sent`)}async close(){this._messageHandler&&window.removeEventListener(`message`,this._messageHandler),this._started=!1,this._clientOrigin&&window.parent&&window.parent!==window&&window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-stopped`},`*`),this.clearServerReadyRetry(),this.onclose?.()}},dm=class{_started=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;_beforeUnloadHandler;_cleanupInterval;_pendingRequests=new Map;REQUEST_TIMEOUT_MS=3e5;onclose;onerror;onmessage;_resolveTargetOrigin(e){return e&&e!==`null`?e:`*`}constructor(e){if(!e.allowedOrigins||e.allowedOrigins.length===0)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=e.allowedOrigins,this._channelId=e.channelId||`mcp-default`}async start(){if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(!this._allowedOrigins.includes(e.origin)&&!this._allowedOrigins.includes(`*`)||e.data?.channel!==this._channelId||e.data?.type!==`mcp`||e.data?.direction!==`client-to-server`)return;this._clientOrigin=e.origin;let t=e.data.payload;if(typeof t==`string`&&t===`mcp-check-ready`){window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},this._resolveTargetOrigin(this._clientOrigin));return}try{let e=ad.parse(t);`method`in e&&`id`in e&&e.id!==void 0&&this._pendingRequests.set(e.id,{request:e,receivedAt:Date.now(),interruptedSent:!1}),this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this._beforeUnloadHandler=()=>{this._handleBeforeUnload()},window.addEventListener(`beforeunload`,this._beforeUnloadHandler),this._cleanupInterval=setInterval(()=>{this._cleanupStaleRequests()},6e4),window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},`*`)}async send(e){if(!this._started)throw Error(`Transport not started`);if((`result`in e||`error`in e)&&e.id!==void 0){if(this._pendingRequests.get(e.id)?.interruptedSent){console.debug(`[TabServerTransport] Suppressing response for ${e.id} - interrupted response already sent`),this._pendingRequests.delete(e.id);return}this._pendingRequests.delete(e.id)}let t=this._resolveTargetOrigin(this._clientOrigin);window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},t)}_handleBeforeUnload(){let e=Array.from(this._pendingRequests.entries()).reverse();for(let[t,n]of e){n.interruptedSent=!0;let e={jsonrpc:`2.0`,id:t,result:{content:[{type:`text`,text:`Tool execution interrupted by page navigation`}],metadata:{navigationInterrupted:!0,originalMethod:`method`in n.request?n.request.method:`unknown`,timestamp:Date.now()}}};try{window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this._resolveTargetOrigin(this._clientOrigin))}catch(e){console.error(`[TabServerTransport] Failed to send beforeunload response:`,e)}}this._pendingRequests.clear()}_cleanupStaleRequests(){let e=Date.now(),t=[];for(let[n,r]of this._pendingRequests)e-r.receivedAt>this.REQUEST_TIMEOUT_MS&&t.push(n);if(t.length>0){console.warn(`[TabServerTransport] Cleaning up ${t.length} stale requests`);for(let e of t)this._pendingRequests.delete(e)}}async close(){this._messageHandler&&window.removeEventListener(`message`,this._messageHandler),this._beforeUnloadHandler&&window.removeEventListener(`beforeunload`,this._beforeUnloadHandler),this._cleanupInterval!==void 0&&clearInterval(this._cleanupInterval),this._pendingRequests.clear(),this._started=!1,window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-stopped`},`*`),this.onclose?.()}};let fm=null;function pm(){return typeof window<`u`&&window.navigator!==void 0}function mm(e){try{Object.defineProperty(navigator,`modelContext`,{configurable:!0,enumerable:!0,writable:!1,value:e})}catch{Object.defineProperty(Object.getPrototypeOf(navigator),`modelContext`,{configurable:!0,enumerable:!0,get(){return e}})}navigator.modelContext!==e&&console.error(`[WebModelContext] Failed to replace navigator.modelContext.`,`Descriptor:`,Object.getOwnPropertyDescriptor(navigator,`modelContext`))}function hm(e){if(window.parent!==window&&e?.iframeServer!==!1){let{allowedOrigins:t,...n}=typeof e?.iframeServer==`object`?e.iframeServer:{};return new um({allowedOrigins:t??[`*`],...n})}if(e?.tabServer===!1)throw Error(`tabServer transport is disabled and iframe transport was not selected`);let{allowedOrigins:t,...n}=typeof e?.tabServer==`object`?e.tabServer:{};return new dm({allowedOrigins:t??[`*`],...n})}function gm(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch(e){console.warn(`[WebMCP] Failed to parse testing inputSchema JSON:`,e);return}}function _m(){let e=navigator.modelContextTesting;if(e){if(typeof e.getRegisteredTools==`function`)return{testingShim:e,tools:e.getRegisteredTools()};if(typeof e.listTools==`function`)return{testingShim:e,tools:e.listTools().map(e=>({name:e.name,description:e.description??``,inputSchema:gm(e.inputSchema)??{type:`object`,properties:{}}}))}}}function vm(e){let t=_m();if(!t)return 0;let{testingShim:n,tools:r}=t;return e.backfillTools(r,async(e,t)=>{let r=await n.executeTool(e,JSON.stringify(t??{}));if(r===null)return{content:[{type:`text`,text:`Tool execution interrupted by navigation`}],isError:!0};let i;try{i=JSON.parse(r)}catch(t){throw Error(`Failed to parse serialized tool response for ${e}: ${t instanceof Error?t.message:String(t)}`)}if(!i||typeof i!=`object`||Array.isArray(i))throw Error(`Invalid serialized tool response for ${e}`);return i})}function ym(e){if(!pm()||fm||navigator.modelContext?.[em])return;Tu({installTestingShim:e?.installTestingShim??`if-missing`});let t=navigator.modelContext;if(!t)throw Error(`navigator.modelContext is not available`);let n=new lm({name:`${window.location.hostname||`localhost`}-webmcp`,version:`1.0.0`},{native:t});n.syncNativeTools(),vm(n),mm(n);let r=hm(e?.transport);fm={native:t,server:n,transport:r},n.connect(r).catch(e=>{console.error(`[WebModelContext] Failed to connect MCP transport:`,e)})}function bm(){if(!fm)return;let{native:e,server:t,transport:n}=fm;fm=null,t.close(),n.close(),mm(e)}if(typeof window<`u`&&typeof document<`u`){let e=window.__webModelContextOptions;if(e?.autoInitialize!==!1)try{ym(e)}catch(e){console.error(`[WebModelContext] Auto-initialization failed:`,e)}}return e.cleanupWebModelContext=bm,e.initializeWebModelContext=ym,e})({});
|
|
42
|
+
- `)}`,Error(e)}let l=`${s}/$ref`,u=q(e,t,n,r,i,a,o,l,c);if(u.valid||y.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:y.length===0,errors:y}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&y.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?cl(e,h)||y.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&y.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),ee!==void 0&&(u===`object`||u===`array`?ee.some(t=>cl(e,t))||y.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(ee)}.`}):ee.some(t=>e===t)||y.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(ee)}.`})),ne!==void 0){let t=`${s}/not`;q(e,ne,n,r,i,a,o,t).valid&&y.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Le=[];if(re!==void 0){let t=`${s}/anyOf`,l=y.length,u=!1;for(let s=0;s<re.length;s++){let l=re[s],d=Object.create(c),f=q(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);y.push(...f.errors),u||=f.valid,f.valid&&Le.push(d)}u?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(g!==void 0){let t=`${s}/allOf`,l=y.length,u=!0;for(let s=0;s<g.length;s++){let l=g[s],d=Object.create(c),f=q(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);y.push(...f.errors),u&&=f.valid,f.valid&&Le.push(d)}u?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(ie!==void 0){let t=`${s}/oneOf`,l=y.length,u=ie.filter((s,l)=>{let u=Object.create(c),d=q(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return y.push(...d.errors),d.valid&&Le.push(u),d.valid}).length;u===1?y.length=l:y.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Le),ae!==void 0){let t=`${s}/if`;if(q(e,ae,n,r,i,a,o,t,c).valid){if(_!==void 0){let l=q(e,_,n,r,i,a,o,`${s}/then`,c);l.valid||y.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(v!==void 0){let l=q(e,v,n,r,i,a,o,`${s}/else`,c);l.valid||y.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(te!==void 0)for(let t of te)t in e||y.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(de!==void 0&&t.length<de&&y.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${de} properties.`}),fe!==void 0&&t.length>fe&&y.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${fe} properties.`}),pe!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${ll(s)}`,c=q(s,pe,n,r,i,a,e,t);c.valid||y.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(me!==void 0){let t=`${s}/dependantRequired`;for(let n in me)if(n in e){let r=me[n];for(let i of r)i in e||y.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(he!==void 0)for(let t in he){let l=`${s}/dependentSchemas`;if(t in e){let s=q(e,he[t],n,r,i,a,o,`${l}/${ll(t)}`,c);s.valid||y.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ge!==void 0){let t=`${s}/dependencies`;for(let s in ge)if(s in e){let c=ge[s];if(Array.isArray(c))for(let n of c)n in e||y.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=q(e,c,n,r,i,a,o,`${t}/${ll(s)}`);l.valid||y.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(se!==void 0){let t=`${s}/properties`;for(let s in se){if(!(s in e))continue;let d=`${o}/${ll(s)}`,f=q(e[s],se[s],n,r,i,a,d,`${t}/${ll(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,y.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&ce!==void 0){let t=`${s}/patternProperties`;for(let s in ce){let d=new RegExp(s,`u`),f=ce[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${ll(p)}`,h=q(e[p],f,n,r,i,a,m,`${t}/${ll(s)}`);h.valid?c[p]=l[p]=!0:(u=i,y.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&le!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${ll(s)}`,f=q(e[s],le,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,y.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ue!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${ll(s)}`,u=q(e[s],ue,n,r,i,a,l,t);u.valid?c[s]=!0:y.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){Te!==void 0&&e.length>Te&&y.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${Te}).`}),we!==void 0&&e.length<we&&y.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${we}).`});let t=e.length,l=0,u=!1;if(_e!==void 0){let d=`${s}/prefixItems`,f=Math.min(_e.length,t);for(;l<f;l++){let t=q(e[l],_e[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ve!==void 0){let d=`${s}/items`;if(Array.isArray(ve)){let s=Math.min(ve.length,t);for(;l<s;l++){let t=q(e[l],ve[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=q(e[l],ve,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,y.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ye!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=q(e[l],ye,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,y.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(xe!==void 0)if(t===0&&Se===void 0)y.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(Se!==void 0&&t<Se)y.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${Se}).`});else{let l=`${s}/contains`,u=y.length,d=0;for(let s=0;s<t;s++){let t=q(e[s],xe,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):y.push(...t.errors)}d>=(Se||0)&&(y.length=u),Se===void 0&&Ce===void 0&&d===0?y.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):Se!==void 0&&d<Se?y.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${Se} items matching schema. Only ${d} items were found.`}):Ce!==void 0&&d>Ce&&y.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${d} items were found.`})}if(!u&&be!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=q(e[l],be,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||y.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(Ee)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&cl(r,t))&&(y.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(De!==void 0&&(ke===!0&&e<=De||e<De)&&y.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ke?`or equal to `:``} ${De}.`}),Oe!==void 0&&(Ae===!0&&e>=Oe||e>Oe)&&y.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Ae?`or equal to `:``} ${Oe}.`})):(De!==void 0&&e<De&&y.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${De}.`}),Oe!==void 0&&e>Oe&&y.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${Oe}.`}),ke!==void 0&&e<=ke&&y.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${ke}.`}),Ae!==void 0&&e>=Ae&&y.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${Ae}.`})),je!==void 0){let t=e%je;Math.abs(0-t)>=1.1920929e-7&&Math.abs(je-t)>=1.1920929e-7&&y.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${je}.`})}}else if(u===`string`){let t=Me===void 0&&Ne===void 0?0:Ul(e);Me!==void 0&&t<Me&&y.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Me}).`}),Ne!==void 0&&t>Ne&&y.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${Ne}).`}),Pe!==void 0&&!new RegExp(Pe,`u`).test(e)&&y.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),oe!==void 0&&Ml[oe]&&!Ml[oe](e)&&y.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${oe}".`})}return{valid:y.length===0,errors:y}}var Wl=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=hl(e)}validate(e){return q(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),hl(e,this.lookup)}};let Gl=`Failed to parse input arguments`,Kl=`Tool was executed but the invocation failed. For example, the script function threw an error`,ql=`Tool was cancelled`,Jl={type:`object`,properties:{}},Yl=[`draft-2020-12`,`draft-07`],Xl=Symbol(`standardValidator`),Zl={installed:!1,previousModelContextDescriptor:void 0,previousModelContextTestingDescriptor:void 0};var Ql=class{tools=new Map;toolsChangedCallback=null;provideContextDeprecationWarned=!1;clearContextDeprecationWarned=!1;provideContext(e={}){this.warnProvideContextDeprecationOnce();let t=new Map;for(let n of e.tools??[]){let e=uu(n,t);t.set(e.name,e)}this.tools=t,this.notifyToolsChanged()}clearContext(){this.warnClearContextDeprecationOnce(),this.tools.clear(),this.notifyToolsChanged()}registerTool(e){let t=uu(e,this.tools);this.tools.set(t.name,t),this.notifyToolsChanged()}unregisterTool(e){let t=tu(e);this.tools.delete(t)&&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 $l(ql);let r=this.tools.get(e);if(!r)throw $l(`Tool not found: ${e}`);let i=eu(t),a=await mu(i,r);if(a)throw $l(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 Su(bu(await Cu(Promise.resolve(e),n?.signal)))}catch(e){throw $l(e instanceof Error?`${Kl}: ${e.message}`:Kl)}finally{o=!1}}notifyToolsChanged(){this.toolsChangedCallback&&queueMicrotask(()=>{try{this.toolsChangedCallback?.()}catch(e){console.warn(`[WebMCPPolyfill] toolsChanged callback threw:`,e)}})}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.`))}};function $l(e){try{return new DOMException(e,`UnknownError`)}catch{let t=Error(e);return t.name=`UnknownError`,t}}function eu(e){let t;try{t=JSON.parse(e)}catch{throw $l(Gl)}if(!t||typeof t!=`object`||Array.isArray(t))throw $l(Gl);return t}function tu(e){if(typeof e==`string`)return e;if(J(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 J(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function nu(e){if(!J(e))return null;let t=e[`~standard`];return J(t)?t:null}function ru(e){let t=nu(e);return!!(t&&t.version===1&&typeof t.validate==`function`)}function iu(e){let t=nu(e);return!t||t.version!==1||!J(t.jsonSchema)?!1:typeof t.jsonSchema.input==`function`}function au(e){return{"~standard":{version:1,vendor:`@mcp-b/webmcp-polyfill-json-schema`,validate(t){if(!J(t))return{issues:[{message:`expected object arguments`}]};let n=du(t,e);return n?{issues:[n]}:{value:t}}}}}function ou(e){for(let t of Yl)try{let n=e[`~standard`].jsonSchema.input({target:t});return cu(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 su(e){if(e===void 0){let e=Jl;return{inputSchema:e,standardValidator:au(e)}}if(iu(e)){let t=ou(e);return{inputSchema:t,standardValidator:au(t)}}if(ru(e))return{inputSchema:Jl,standardValidator:e};if(cu(e),Object.keys(e).length===0)return{inputSchema:Jl,standardValidator:au(Jl)};let t=e.type===void 0?{type:`object`,...e}:e;return{inputSchema:t,standardValidator:au(t)}}function cu(e){if(!J(e))throw Error(`inputSchema must be a JSON Schema object`);lu(e,`$`)}function lu(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(!J(i))throw Error(`Invalid JSON Schema at ${t}: "properties" must be an object`);for(let[e,n]of Object.entries(i)){if(!J(n))throw Error(`Invalid JSON Schema at ${t}.properties.${e}: expected object schema`);lu(n,`${t}.properties.${e}`)}}let a=e.items;if(a!==void 0)if(Array.isArray(a))for(let[e,n]of a.entries()){if(!J(n))throw Error(`Invalid JSON Schema at ${t}.items[${e}]: expected object schema`);lu(n,`${t}.items[${e}]`)}else if(J(a))lu(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(!J(i))throw Error(`Invalid JSON Schema at ${t}.${n}[${e}]: expected object schema`);lu(i,`${t}.${n}[${e}]`)}}}let o=e.not;if(o!==void 0){if(!J(o))throw Error(`Invalid JSON Schema at ${t}: "not" must be an object schema`);lu(o,`${t}.not`)}try{JSON.stringify(e)}catch{throw Error(`Invalid JSON Schema at ${t}: schema must be JSON-serializable`)}}function uu(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=su(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,[Xl]:n.standardValidator}}function du(e,t){let n=new Wl(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 fu(e){if(!e||e.length===0)return null;let t=e.map(e=>J(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 pu(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=fu(r?.path);return i?`Input validation error: ${r.message} at ${i}`:`Input validation error: ${r.message}`}async function mu(e,t){return pu(e,t[Xl])}function hu(e){return J(e)&&Array.isArray(e.content)}function gu(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function _u(e){return gu(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>_u(e)):J(e)?Object.values(e).every(e=>_u(e)):!1}function vu(e){if(!(!J(e)||!_u(e)))return e}function yu(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function bu(e){if(hu(e))return e;let t=vu(e);return{content:[{type:`text`,text:yu(e)}],...t?{structuredContent:t}:{},isError:!1}}function xu(e){for(let t of e.content??[])if(t.type===`text`&&`text`in t&&typeof t.text==`string`)return t.text;return null}function Su(e){if(e.isError)throw $l(xu(e)?.replace(/^Error:\s*/i,``).trim()||Kl);let t=e.metadata;if(t&&typeof t==`object`&&t.willNavigate)return null;try{return JSON.stringify(e)}catch{throw $l(Kl)}}function Cu(e,t){return t?t.aborted?Promise.reject($l(ql)):new Promise((n,r)=>{let i=()=>{a(),r($l(ql))},a=()=>{t.removeEventListener(`abort`,i)};t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})}):e}function wu(){return typeof navigator<`u`?navigator:null}function Tu(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!1,value:n})}function Eu(e){let t=wu();if(!t||t.modelContext)return;Zl.installed&&Du();let n=new Ql,r=n;r.__isWebMCPPolyfill=!0,Zl.previousModelContextDescriptor=Object.getOwnPropertyDescriptor(t,`modelContext`),Zl.previousModelContextTestingDescriptor=Object.getOwnPropertyDescriptor(t,`modelContextTesting`),Tu(t,`modelContext`,r);let i=e?.installTestingShim??`if-missing`,a=!!t.modelContextTesting;(i===`always`||(i===!0||i===`if-missing`)&&!a)&&Tu(t,`modelContextTesting`,n.getTestingShim()),Zl.installed=!0}function Du(){let e=wu();if(!e||!Zl.installed)return;let t=(t,n)=>{if(n){Object.defineProperty(e,t,n);return}delete e[t]};t(`modelContext`,Zl.previousModelContextDescriptor),t(`modelContextTesting`,Zl.previousModelContextTestingDescriptor),Zl.installed=!1,Zl.previousModelContextDescriptor=void 0,Zl.previousModelContextTestingDescriptor=void 0}if(typeof window<`u`&&typeof document<`u`){let e=window.__webMCPPolyfillOptions;if(e?.autoInitialize!==!1)try{Eu(e)}catch(e){console.error(`[WebMCPPolyfill] Auto-initialization failed:`,e)}}function Ou(e){return!!e._zod}function ku(e){let t=Object.values(e);if(t.length===0)return jo({});let n=t.every(Ou),r=t.every(e=>!Ou(e));if(n)return jo(e);if(r)return ht(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Au(e,t){return Ou(e)?dn(e,t):e.safeParse(t)}async function ju(e,t){return Ou(e)?await pn(e,t):await e.safeParseAsync(t)}function Mu(e){if(!e)return;let t;if(t=Ou(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Nu(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return ku(e)}}if(Ou(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Pu(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Fu(e){return e.description}function Iu(e){if(Ou(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Lu(e){if(Ou(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}let Ru=`2025-11-25`,zu=[Ru,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Bu=`io.modelcontextprotocol/related-task`,Y=oc(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Vu=R([A(),M().int()]),Hu=A();L({ttl:R([M(),Es()]).optional(),pollInterval:M().optional()});let Uu=I({ttl:M().optional()}),Wu=I({taskId:A()}),Gu=L({progressToken:Vu.optional(),[Bu]:Wu.optional()}),Ku=I({_meta:Gu.optional()}),qu=Ku.extend({task:Uu.optional()}),Ju=e=>qu.safeParse(e).success,X=I({method:A(),params:Ku.loose().optional()}),Yu=I({_meta:Gu.optional()}),Xu=I({method:A(),params:Yu.loose().optional()}),Z=L({_meta:Gu.optional()}),Zu=R([A(),M().int()]),Qu=I({jsonrpc:V(`2.0`),id:Zu,...X.shape}).strict(),$u=e=>Qu.safeParse(e).success,ed=I({jsonrpc:V(`2.0`),...Xu.shape}).strict(),td=e=>ed.safeParse(e).success,nd=I({jsonrpc:V(`2.0`),id:Zu,result:Z}).strict(),rd=e=>nd.safeParse(e).success;var Q;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(Q||={});let id=I({jsonrpc:V(`2.0`),id:Zu.optional(),error:I({code:M().int(),message:A(),data:P().optional()})}).strict(),ad=e=>id.safeParse(e).success,od=R([Qu,ed,nd,id]);R([nd,id]);let sd=Z.strict(),cd=Yu.extend({requestId:Zu.optional(),reason:A().optional()}),ld=Xu.extend({method:V(`notifications/cancelled`),params:cd}),ud=I({icons:F(I({src:A(),mimeType:A().optional(),sizes:F(A()).optional(),theme:B([`light`,`dark`]).optional()})).optional()}),dd=I({name:A(),title:A().optional()}),fd=dd.extend({...dd.shape,...ud.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),pd=lc(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Is(I({form:Is(I({applyDefaults:N().optional()}),z(A(),P())).optional(),url:Y.optional()}),z(A(),P()).optional())),md=L({list:Y.optional(),cancel:Y.optional(),requests:L({sampling:L({createMessage:Y.optional()}).optional(),elicitation:L({create:Y.optional()}).optional()}).optional()}),hd=L({list:Y.optional(),cancel:Y.optional(),requests:L({tools:L({call:Y.optional()}).optional()}).optional()}),gd=I({experimental:z(A(),Y).optional(),sampling:I({context:Y.optional(),tools:Y.optional()}).optional(),elicitation:pd.optional(),roots:I({listChanged:N().optional()}).optional(),tasks:md.optional()}),_d=Ku.extend({protocolVersion:A(),capabilities:gd,clientInfo:fd}),vd=X.extend({method:V(`initialize`),params:_d}),yd=I({experimental:z(A(),Y).optional(),logging:Y.optional(),completions:Y.optional(),prompts:I({listChanged:N().optional()}).optional(),resources:I({subscribe:N().optional(),listChanged:N().optional()}).optional(),tools:I({listChanged:N().optional()}).optional(),tasks:hd.optional()}),bd=Z.extend({protocolVersion:A(),capabilities:yd,serverInfo:fd,instructions:A().optional()}),xd=Xu.extend({method:V(`notifications/initialized`),params:Yu.optional()}),Sd=X.extend({method:V(`ping`),params:Ku.optional()}),Cd=I({progress:M(),total:H(M()),message:H(A())}),wd=I({...Yu.shape,...Cd.shape,progressToken:Vu}),Td=Xu.extend({method:V(`notifications/progress`),params:wd}),Ed=Ku.extend({cursor:Hu.optional()}),Dd=X.extend({params:Ed.optional()}),Od=Z.extend({nextCursor:Hu.optional()}),kd=B([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Ad=I({taskId:A(),status:kd,ttl:R([M(),Es()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:H(M()),statusMessage:H(A())}),jd=Z.extend({task:Ad}),Md=Yu.merge(Ad),Nd=Xu.extend({method:V(`notifications/tasks/status`),params:Md}),Pd=X.extend({method:V(`tasks/get`),params:Ku.extend({taskId:A()})}),Fd=Z.merge(Ad),Id=X.extend({method:V(`tasks/result`),params:Ku.extend({taskId:A()})});Z.loose();let Ld=Dd.extend({method:V(`tasks/list`)}),Rd=Od.extend({tasks:F(Ad)}),zd=X.extend({method:V(`tasks/cancel`),params:Ku.extend({taskId:A()})}),Bd=Z.merge(Ad),Vd=I({uri:A(),mimeType:H(A()),_meta:z(A(),P()).optional()}),Hd=Vd.extend({text:A()}),Ud=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Wd=Vd.extend({blob:Ud}),Gd=B([`user`,`assistant`]),Kd=I({audience:F(Gd).optional(),priority:M().min(0).max(1).optional(),lastModified:No({offset:!0}).optional()}),qd=I({...dd.shape,...ud.shape,uri:A(),description:H(A()),mimeType:H(A()),annotations:Kd.optional(),_meta:H(L({}))}),Jd=I({...dd.shape,...ud.shape,uriTemplate:A(),description:H(A()),mimeType:H(A()),annotations:Kd.optional(),_meta:H(L({}))}),Yd=Dd.extend({method:V(`resources/list`)}),Xd=Od.extend({resources:F(qd)}),Zd=Dd.extend({method:V(`resources/templates/list`)}),Qd=Od.extend({resourceTemplates:F(Jd)}),$d=Ku.extend({uri:A()}),ef=$d,tf=X.extend({method:V(`resources/read`),params:ef}),nf=Z.extend({contents:F(R([Hd,Wd]))}),rf=Xu.extend({method:V(`notifications/resources/list_changed`),params:Yu.optional()}),af=$d,of=X.extend({method:V(`resources/subscribe`),params:af}),sf=$d,cf=X.extend({method:V(`resources/unsubscribe`),params:sf}),lf=Yu.extend({uri:A()}),uf=Xu.extend({method:V(`notifications/resources/updated`),params:lf}),df=I({name:A(),description:H(A()),required:H(N())}),ff=I({...dd.shape,...ud.shape,description:H(A()),arguments:H(F(df)),_meta:H(L({}))}),pf=Dd.extend({method:V(`prompts/list`)}),mf=Od.extend({prompts:F(ff)}),hf=Ku.extend({name:A(),arguments:z(A(),A()).optional()}),gf=X.extend({method:V(`prompts/get`),params:hf}),_f=I({type:V(`text`),text:A(),annotations:Kd.optional(),_meta:z(A(),P()).optional()}),vf=I({type:V(`image`),data:Ud,mimeType:A(),annotations:Kd.optional(),_meta:z(A(),P()).optional()}),yf=I({type:V(`audio`),data:Ud,mimeType:A(),annotations:Kd.optional(),_meta:z(A(),P()).optional()}),bf=I({type:V(`tool_use`),name:A(),id:A(),input:z(A(),P()),_meta:z(A(),P()).optional()}),xf=I({type:V(`resource`),resource:R([Hd,Wd]),annotations:Kd.optional(),_meta:z(A(),P()).optional()}),Sf=R([_f,vf,yf,qd.extend({type:V(`resource_link`)}),xf]),Cf=I({role:Gd,content:Sf}),wf=Z.extend({description:A().optional(),messages:F(Cf)}),Tf=Xu.extend({method:V(`notifications/prompts/list_changed`),params:Yu.optional()}),Ef=I({title:A().optional(),readOnlyHint:N().optional(),destructiveHint:N().optional(),idempotentHint:N().optional(),openWorldHint:N().optional()}),Df=I({taskSupport:B([`required`,`optional`,`forbidden`]).optional()}),Of=I({...dd.shape,...ud.shape,description:A().optional(),inputSchema:I({type:V(`object`),properties:z(A(),Y).optional(),required:F(A()).optional()}).catchall(P()),outputSchema:I({type:V(`object`),properties:z(A(),Y).optional(),required:F(A()).optional()}).catchall(P()).optional(),annotations:Ef.optional(),execution:Df.optional(),_meta:z(A(),P()).optional()}),kf=Dd.extend({method:V(`tools/list`)}),Af=Od.extend({tools:F(Of)}),jf=Z.extend({content:F(Sf).default([]),structuredContent:z(A(),P()).optional(),isError:N().optional()});jf.or(Z.extend({toolResult:P()}));let Mf=qu.extend({name:A(),arguments:z(A(),P()).optional()}),Nf=X.extend({method:V(`tools/call`),params:Mf}),Pf=Xu.extend({method:V(`notifications/tools/list_changed`),params:Yu.optional()});I({autoRefresh:N().default(!0),debounceMs:M().int().nonnegative().default(300)});let Ff=B([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),If=Ku.extend({level:Ff}),Lf=X.extend({method:V(`logging/setLevel`),params:If}),Rf=Yu.extend({level:Ff,logger:A().optional(),data:P()}),zf=Xu.extend({method:V(`notifications/message`),params:Rf}),Bf=I({hints:F(I({name:A().optional()})).optional(),costPriority:M().min(0).max(1).optional(),speedPriority:M().min(0).max(1).optional(),intelligencePriority:M().min(0).max(1).optional()}),Vf=I({mode:B([`auto`,`required`,`none`]).optional()}),Hf=I({type:V(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:F(Sf).default([]),structuredContent:I({}).loose().optional(),isError:N().optional(),_meta:z(A(),P()).optional()}),Uf=Ps(`type`,[_f,vf,yf]),Wf=Ps(`type`,[_f,vf,yf,bf,Hf]),Gf=I({role:Gd,content:R([Wf,F(Wf)]),_meta:z(A(),P()).optional()}),Kf=qu.extend({messages:F(Gf),modelPreferences:Bf.optional(),systemPrompt:A().optional(),includeContext:B([`none`,`thisServer`,`allServers`]).optional(),temperature:M().optional(),maxTokens:M().int(),stopSequences:F(A()).optional(),metadata:Y.optional(),tools:F(Of).optional(),toolChoice:Vf.optional()}),qf=X.extend({method:V(`sampling/createMessage`),params:Kf}),Jf=Z.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:Gd,content:Uf}),Yf=Z.extend({model:A(),stopReason:H(B([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:Gd,content:R([Wf,F(Wf)])}),Xf=I({type:V(`boolean`),title:A().optional(),description:A().optional(),default:N().optional()}),Zf=I({type:V(`string`),title:A().optional(),description:A().optional(),minLength:M().optional(),maxLength:M().optional(),format:B([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),Qf=I({type:B([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:M().optional(),maximum:M().optional(),default:M().optional()}),$f=I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),default:A().optional()}),ep=I({type:V(`string`),title:A().optional(),description:A().optional(),oneOf:F(I({const:A(),title:A()})),default:A().optional()}),tp=R([R([I({type:V(`string`),title:A().optional(),description:A().optional(),enum:F(A()),enumNames:F(A()).optional(),default:A().optional()}),R([$f,ep]),R([I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({type:V(`string`),enum:F(A())}),default:F(A()).optional()}),I({type:V(`array`),title:A().optional(),description:A().optional(),minItems:M().optional(),maxItems:M().optional(),items:I({anyOf:F(I({const:A(),title:A()}))}),default:F(A()).optional()})])]),Xf,Zf,Qf]),np=R([qu.extend({mode:V(`form`).optional(),message:A(),requestedSchema:I({type:V(`object`),properties:z(A(),tp),required:F(A()).optional()})}),qu.extend({mode:V(`url`),message:A(),elicitationId:A(),url:A().url()})]),rp=X.extend({method:V(`elicitation/create`),params:np}),ip=Yu.extend({elicitationId:A()}),ap=Xu.extend({method:V(`notifications/elicitation/complete`),params:ip}),op=Z.extend({action:B([`accept`,`decline`,`cancel`]),content:lc(e=>e===null?void 0:e,z(A(),R([A(),M(),N(),F(A())])).optional())}),sp=I({type:V(`ref/resource`),uri:A()}),cp=I({type:V(`ref/prompt`),name:A()}),lp=Ku.extend({ref:R([cp,sp]),argument:I({name:A(),value:A()}),context:I({arguments:z(A(),A()).optional()}).optional()}),up=X.extend({method:V(`completion/complete`),params:lp});function dp(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function fp(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}let pp=Z.extend({completion:L({values:F(A()).max(100),total:H(M().int()),hasMore:H(N())})}),mp=I({uri:A().startsWith(`file://`),name:A().optional(),_meta:z(A(),P()).optional()}),hp=X.extend({method:V(`roots/list`),params:Ku.optional()}),gp=Z.extend({roots:F(mp)}),_p=Xu.extend({method:V(`notifications/roots/list_changed`),params:Yu.optional()});R([Sd,vd,up,Lf,gf,pf,Yd,Zd,tf,of,cf,Nf,kf,Pd,Id,Ld,zd]),R([ld,Td,xd,_p,Nd]),R([sd,Jf,Yf,op,gp,Fd,Rd,jd]),R([Sd,qf,rp,hp,Pd,Id,Ld,zd]),R([ld,Td,zf,uf,rf,Pf,Tf,Nd,ap]),R([sd,bd,pp,wf,mf,Xd,Qd,nf,jf,Af,Fd,Rd,jd]);var $=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===Q.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new vp(e.elicitations,n)}return new e(t,n,r)}},vp=class extends ${constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(Q.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function yp(e){return e===`completed`||e===`failed`||e===`cancelled`}function bp(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function xp(e,t){return Ou(e)?Oo(e,{target:bp(t?.target),io:t?.pipeStrategy??`input`}):sl(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Sp(e){let t=Mu(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Lu(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Cp(e,t){let n=Au(e,t);if(!n.success)throw n.error;return n.data}var wp=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ld,e=>{this._oncancel(e)}),this.setNotificationHandler(Td,e=>{this._onprogress(e)}),this.setRequestHandler(Sd,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Pd,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new $(Q.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Id,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new $(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new $(Q.InvalidParams,`Task not found: ${r}`);if(!yp(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(yp(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[Bu]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Ld,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new $(Q.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(zd,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new $(Q.InvalidParams,`Task not found: ${e.params.taskId}`);if(yp(n.status))throw new $(Q.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new $(Q.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof $?e:new $(Q.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),$.fromError(Q.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),rd(e)||ad(e)?this._onresponse(e):$u(e)?this._onrequest(e,t):td(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=$.fromError(Q.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Bu]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:Q.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=Ju(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new $(Q.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Q.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),rd(e)?n(e):n(new $(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(rd(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),rd(e)?r(e):r($.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof $?e:new $(Q.InternalError,String(e))}}return}let i;try{let r=await this.request(e,jd,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new $(Q.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},yp(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new $(Q.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new $(Q.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof $?e:new $(Q.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Bu]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof $?e:new $(Q.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Au(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p($.fromError(Q.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Fd,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Rd,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Bd,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Bu]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Bu]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Bu]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Sp(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Cp(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Sp(e);this._notificationHandlers.set(n,n=>{let r=Cp(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&$u(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new $(Q.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new $(Q.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new $(Q.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new $(Q.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Nd.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),yp(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new $(Q.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(yp(a.status))throw new $(Q.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Nd.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),yp(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Tp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ep(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];Tp(a)&&Tp(i)?n[r]={...a,...i}:n[r]=i}return n}var Dp=class{compile(e){throw Error(`[WebMCP] Ajv stub was invoked. This indicates the MCP SDK is bypassing PolyfillJsonSchemaValidator. Please report this as a bug.`)}getSchema(e){}errorsText(e){return``}};function Op(){return new Dp({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0})}var kp=class{constructor(e){this._ajv=e??Op()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};function Ap(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function jp(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Mp=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}},Np=class extends wp{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ff.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new kp,this.setRequestHandler(vd,e=>this._oninitialize(e)),this.setNotificationHandler(xd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Lf,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Ff.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Mp(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Ep(this._capabilities,e)}setRequestHandler(e,t){let n=Mu(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(Ou(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Au(Nf,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new $(Q.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Au(jd,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new $(Q.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Au(jf,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new $(Q.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){jp(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Ap(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:zu.includes(t)?t:Ru,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},sd)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},Yf,t):this.request({method:`sampling/createMessage`,params:e},Jf,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},op,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},op,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new $(Q.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof $?e:new $(Q.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},gp,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};let Pp=Symbol.for(`mcp.completable`);function Fp(e){return!!e&&typeof e==`object`&&Pp in e}function Ip(e){return e[Pp]?.complete}var Lp;(function(e){e.Completable=`McpCompletable`})(Lp||={});let Rp=/^[A-Za-z0-9._-]{1,128}$/;function zp(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Rp.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Bp(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Vp(e){let t=zp(e);return Bp(e,t.warnings),t.isValid}var Hp=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},Up=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Np(e,t)}get experimental(){return this._experimental||={tasks:new Hp(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Xp(kf)),this.server.assertCanSetRequestHandler(Xp(Nf)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(kf,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=Nu(t.inputSchema);return e?xp(e,{strictUnions:!0,pipeStrategy:`input`}):Wp})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=Nu(t.outputSchema);e&&(n.outputSchema=xp(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Nf,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new $(Q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new $(Q.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new $(Q.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof $&&e.code===Q.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await ju(Nu(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=Pu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new $(Q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await ju(Nu(e.outputSchema),t.structuredContent);if(!r.success){let e=Pu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new $(Q.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Xp(up)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(up,async e=>{switch(e.params.ref.type){case`ref/prompt`:return dp(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return fp(e),this.handleResourceCompletion(e,e.params.ref);default:throw new $(Q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Qp;let r=Mu(n.argsSchema)?.[e.params.argument.name];if(!Fp(r))return Qp;let i=Ip(r);return i?Zp(await i(e.params.argument.value,e.params.context)):Qp}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Qp;throw new $(Q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Zp(await r(e.params.argument.value,e.params.context)):Qp}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Xp(Yd)),this.server.assertCanSetRequestHandler(Xp(Zd)),this.server.assertCanSetRequestHandler(Xp(tf)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Yd,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Zd,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(tf,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new $(Q.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new $(Q.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Xp(pf)),this.server.assertCanSetRequestHandler(Xp(gf)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(pf,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Yp(t.argsSchema):void 0}))})),this.server.setRequestHandler(gf,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new $(Q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new $(Q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await ju(Nu(n.argsSchema),e.params.arguments);if(!r.success){let t=Pu(`error`in r?r.error:`Unknown error`);throw new $(Q.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:ku(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=ku(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>Fp(e instanceof Hs?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Vp(e);let l={title:t,description:n,inputSchema:Jp(r),outputSchema:Jp(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Vp(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=ku(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=ku(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let e=t[0];qp(e)?(r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!qp(t[0])&&(i=t.shift())):typeof e==`object`&&e&&(i=t.shift())}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};let Wp={type:`object`,properties:{}};function Gp(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Kp(e){return`_def`in e||`_zod`in e||Gp(e)}function qp(e){return typeof e!=`object`||!e||Kp(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Gp)}function Jp(e){if(e)return qp(e)?ku(e):e}function Yp(e){let t=Mu(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:Fu(t),required:!Iu(t)})):[]}function Xp(e){let t=Mu(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Lu(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Zp(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}let Qp={completion:{values:[],hasMore:!1}};var $p=class{getValidator(e){return t=>{if(!J(t))return{valid:!1,data:void 0,errorMessage:`expected object arguments`};let n=du(t,e);return n?{valid:!1,data:void 0,errorMessage:n.message}:{valid:!0,data:t,errorMessage:void 0}}}};let em={type:`object`,properties:{}},tm=`__isBrowserMcpServer`;function nm(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function rm(e){return nm(e)&&Array.isArray(e.content)}function im(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function am(e){return im(e)?Number.isFinite(e)||typeof e!=`number`:Array.isArray(e)?e.every(e=>am(e)):nm(e)?Object.values(e).every(e=>am(e)):!1}function om(e){if(!(!nm(e)||!am(e)))return e}function sm(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function cm(e){if(rm(e))return e;let t=om(e);return{content:[{type:`text`,text:sm(e)}],...t?{structuredContent:t}:{},isError:!1}}function lm(e){return e?.signal?e:{...e,signal:AbortSignal.timeout(1e4)}}var um=class extends Up{[tm]=!0;native;_promptSchemas=new Map;_jsonValidator;_publicMethodsBound=!1;_provideContextDeprecationWarned=!1;_clearContextDeprecationWarned=!1;constructor(e,t){let n=new $p,r={capabilities:Ep(t?.capabilities||{},{tools:{listChanged:!0},resources:{listChanged:!0},prompts:{listChanged:!0}}),jsonSchemaValidator:t?.jsonSchemaValidator??n};super(e,r),this._jsonValidator=n,this.native=t?.native,this.bindPublicApiMethods()}bindPublicApiMethods(){this._publicMethodsBound||=(this.registerTool=this.registerTool.bind(this),this.unregisterTool=this.unregisterTool.bind(this),this.provideContext=this.provideContext.bind(this),this.clearContext=this.clearContext.bind(this),this.listTools=this.listTools.bind(this),this.callTool=this.callTool.bind(this),this.executeTool=this.executeTool.bind(this),this.registerResource=this.registerResource.bind(this),this.listResources=this.listResources.bind(this),this.readResource=this.readResource.bind(this),this.registerPrompt=this.registerPrompt.bind(this),this.listPrompts=this.listPrompts.bind(this),this.getPrompt=this.getPrompt.bind(this),this.createMessage=this.createMessage.bind(this),this.elicitInput=this.elicitInput.bind(this),!0)}get _parentTools(){return this._registeredTools}get _parentResources(){return this._registeredResources}get _parentPrompts(){return this._registeredPrompts}toTransportSchema(e,t=!0){if(!e||typeof e!=`object`)return t?(console.warn(`[BrowserMcpServer] toTransportSchema received non-object schema (${typeof e}), using default`),em):{};let n=Nu(e),r=n?xp(n,{strictUnions:!0,pipeStrategy:`input`}):e;return Object.keys(r).length===0?t?em:r:t&&r.type===void 0?{type:`object`,...r}:r}isZodSchema(e){if(!e||typeof e!=`object`)return!1;let t=e;return`_zod`in t||`_def`in t}getNativeToolsApi(){if(!this.native)return;let e=this.native;if(!(typeof e.listTools!=`function`||typeof e.callTool!=`function`))return e}registerToolInServer(e){let t=this.toTransportSchema(e.inputSchema);return super.registerTool(e.name,{description:e.description,inputSchema:t,...e.outputSchema?{outputSchema:e.outputSchema}:{},...e.annotations?{annotations:e.annotations}:{}},async t=>cm(await e.execute(t,{requestUserInteraction:async e=>e()}))),{unregister:()=>this.unregisterTool(e.name)}}backfillTools(e,t){let n=0;for(let r of e){if(!r?.name||this._parentTools[r.name])continue;let e={name:r.name,description:r.description??``,inputSchema:r.inputSchema??em,execute:async e=>t(r.name,e)};r.outputSchema&&(e.outputSchema=r.outputSchema),r.annotations&&(e.annotations=r.annotations),this.registerToolInServer(e),n++}return n}registerTool(e){this.native&&this.native.registerTool(e);try{return this.registerToolInServer(e)}catch(t){if(this.native)try{this.native.unregisterTool(e.name)}catch(e){console.error(`[BrowserMcpServer] Rollback of native tool registration failed:`,e)}throw t}}syncNativeTools(){let e=this.getNativeToolsApi();if(!e)return 0;let t=e.callTool.bind(e);return this.backfillTools(e.listTools(),async(e,n)=>t({name:e,arguments:n}))}unregisterTool(e){let t=this.resolveToolNameForUnregister(e);this._parentTools[t]?.remove(),this.native&&this.native.unregisterTool(t)}clearRegisteredTools(){for(let e of Object.keys(this._parentTools))this.unregisterTool(e)}registerResource(e){let t=super.registerResource(e.name,e.uri,{...e.description!==void 0&&{description:e.description},...e.mimeType!==void 0&&{mimeType:e.mimeType}},async t=>({contents:(await e.read(t)).contents}));return{unregister:()=>t.remove()}}registerPrompt(e){e.argsSchema&&this._promptSchemas.set(e.name,e.argsSchema);let t=super.registerPrompt(e.name,{...e.description!==void 0&&{description:e.description}},async t=>({messages:(await e.get(t)).messages}));return{unregister:()=>{this._promptSchemas.delete(e.name),t.remove()}}}provideContext(e){this.warnProvideContextDeprecationOnce(),this.clearRegisteredTools();for(let t of e?.tools??[])this.registerTool(t)}clearContext(){this.warnClearContextDeprecationOnce(),this.clearRegisteredTools()}resolveToolNameForUnregister(e){if(typeof e==`string`)return e;if(nm(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.`)}warnProvideContextDeprecationOnce(){this._provideContextDeprecationWarned||(this._provideContextDeprecationWarned=!0,console.warn(`[BrowserMcpServer] 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(`[BrowserMcpServer] navigator.modelContext.clearContext() is deprecated and will be removed in the next major version. Unregister individual tools instead.`))}listResources(){return Object.entries(this._parentResources).filter(([,e])=>e.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata}))}async readResource(e){let t=this._parentResources[e];if(!t)throw Error(`Resource not found: ${e}`);return t.readCallback(new URL(e),{})}listPrompts(){return Object.entries(this._parentPrompts).filter(([,e])=>e.enabled).map(([e,t])=>{let n=this._promptSchemas.get(e);return{name:e,...t.description!==void 0&&{description:t.description},...n?.properties?{arguments:Object.entries(n.properties).map(([e,t])=>({name:e,...typeof t==`object`&&t&&`description`in t?{description:t.description}:{},...n.required?.includes(e)?{required:!0}:{}}))}:{}}})}async getPrompt(e,t={}){let n=this._parentPrompts[e];if(!n)throw Error(`Prompt not found: ${e}`);let r=this._promptSchemas.get(e);if(r){let n=this._jsonValidator.getValidator(r)(t);if(!n.valid)throw Error(`Invalid arguments for prompt ${e}: ${n.errorMessage}`)}return n.callback(t,{})}listTools(){return Object.entries(this._parentTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,description:t.description??``,inputSchema:this.toTransportSchema(t.inputSchema??em)};return t.outputSchema&&(n.outputSchema=this.toTransportSchema(t.outputSchema,!1)),t.annotations&&(n.annotations=t.annotations),n})}async validateToolInput(e,t,n){if(!e.inputSchema)return;if(this.isZodSchema(e.inputSchema)){let r=await ju(e.inputSchema,t??{});if(!r.success)throw Error(`Invalid arguments for tool ${n}: ${Pu(r.error)}`);return r.data}let r=this._jsonValidator.getValidator(e.inputSchema)(t??{});if(!r.valid)throw Error(`Invalid arguments for tool ${n}: ${r.errorMessage}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema)return;let r=t;if(!(`content`in r)||r.isError||!r.structuredContent)return;if(this.isZodSchema(e.outputSchema)){let t=await ju(e.outputSchema,r.structuredContent);if(!t.success)throw Error(`Output validation error: Invalid structured content for tool ${n}: ${Pu(t.error)}`);return}let i=this._jsonValidator.getValidator(e.outputSchema)(r.structuredContent);if(!i.valid)throw Error(`Output validation error: Invalid structured content for tool ${n}: ${i.errorMessage}`)}async callTool(e){let t=this._parentTools[e.name];if(!t)throw Error(`Tool not found: ${e.name}`);return t.handler(e.arguments??{},{})}async executeTool(e,t={}){return this.callTool({name:e,arguments:t})}async connect(e){return this.setToolRequestHandlers(),this.setResourceRequestHandlers(),this.setPromptRequestHandlers(),this.server.setRequestHandler(kf,()=>({tools:this.listTools()})),this.server.setRequestHandler(pf,()=>({prompts:this.listPrompts()})),this.server.setRequestHandler(gf,async e=>{let t=this._parentPrompts[e.params.name];if(!t)throw Error(`Prompt ${e.params.name} not found`);if(!t.enabled)throw Error(`Prompt ${e.params.name} disabled`);let n=this._promptSchemas.get(e.params.name);if(n){let r=this._jsonValidator.getValidator(n)(e.params.arguments??{});if(!r.valid)throw Error(`Invalid arguments for prompt ${e.params.name}: ${r.errorMessage}`);return t.callback(e.params.arguments,{})}return t.callback({},{})}),super.connect(e)}async createMessage(e,t){return this.server.createMessage(e,lm(t))}async elicitInput(e,t){return this.server.elicitInput(e,lm(t))}};(function(e){return e.START=`start`,e.STARTED=`started`,e.STOP=`stop`,e.STOPPED=`stopped`,e.PING=`ping`,e.PONG=`pong`,e.ERROR=`error`,e.LIST_TOOLS=`list_tools`,e.CALL_TOOL=`call_tool`,e.TOOL_LIST_UPDATED=`tool_list_updated`,e.TOOL_LIST_UPDATED_ACK=`tool_list_updated_ack`,e.PROCESS_DATA=`process_data`,e.SERVER_STARTED=`server_started`,e.SERVER_STOPPED=`server_stopped`,e.ERROR_FROM_NATIVE_HOST=`error_from_native_host`,e.CONNECT_NATIVE=`connectNative`,e.PING_NATIVE=`ping_native`,e.DISCONNECT_NATIVE=`disconnect_native`,e})({}),{NAME:`com.chromemcp.nativehost`,DEFAULT_PORT:12306}.NAME;var dm=class{_started=!1;_allowedOrigins;_channelId;_messageHandler;_clientOrigin;_serverReadyTimeout;_serverReadyRetryMs;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins||e.allowedOrigins.length===0)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=e.allowedOrigins,this._channelId=e.channelId||`mcp-iframe`,this._serverReadyRetryMs=e.serverReadyRetryMs??250}async start(){if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(!this._allowedOrigins.includes(e.origin)&&!this._allowedOrigins.includes(`*`)||e.data?.channel!==this._channelId||e.data?.type!==`mcp`||e.data?.direction!==`client-to-server`)return;this._clientOrigin=e.origin;let t=e.data.payload;if(typeof t==`string`&&t===`mcp-check-ready`){this.broadcastServerReady();return}try{let e=od.parse(t);this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this.broadcastServerReady()}broadcastServerReady(){window.parent&&window.parent!==window?(window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},`*`),this.clearServerReadyRetry()):this.scheduleServerReadyRetry()}scheduleServerReadyRetry(){this._serverReadyTimeout||=setTimeout(()=>{this._serverReadyTimeout=void 0,this._started&&this.broadcastServerReady()},this._serverReadyRetryMs)}clearServerReadyRetry(){this._serverReadyTimeout&&=(clearTimeout(this._serverReadyTimeout),void 0)}async send(e){if(!this._started)throw Error(`Transport not started`);if(!this._clientOrigin){console.debug(`[IframeChildTransport] No client connected, message not sent`);return}window.parent&&window.parent!==window?window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this._clientOrigin):console.debug(`[IframeChildTransport] Not running in an iframe, message not sent`)}async close(){this._messageHandler&&window.removeEventListener(`message`,this._messageHandler),this._started=!1,this._clientOrigin&&window.parent&&window.parent!==window&&window.parent.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-stopped`},`*`),this.clearServerReadyRetry(),this.onclose?.()}},fm=class{_started=!1;_allowedOrigins;_channelId;_messageHandler;_beforeUnloadHandler;_cleanupInterval;_pendingRequests=new Map;SELF_TARGET_ORIGIN=`*`;REQUEST_TIMEOUT_MS=3e5;onclose;onerror;onmessage;constructor(e){if(!e.allowedOrigins||e.allowedOrigins.length===0)throw Error(`At least one allowed origin must be specified`);this._allowedOrigins=e.allowedOrigins,this._channelId=e.channelId||`mcp-default`}async start(){if(this._started)throw Error(`Transport already started`);this._messageHandler=e=>{if(!this._allowedOrigins.includes(e.origin)&&!this._allowedOrigins.includes(`*`)||e.data?.channel!==this._channelId||e.data?.type!==`mcp`||e.data?.direction!==`client-to-server`)return;let t=e.data.payload;if(typeof t==`string`&&t===`mcp-check-ready`){window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},this.SELF_TARGET_ORIGIN);return}try{let e=od.parse(t);`method`in e&&`id`in e&&e.id!==void 0&&this._pendingRequests.set(e.id,{request:e,receivedAt:Date.now(),interruptedSent:!1}),this.onmessage?.(e)}catch(e){this.onerror?.(Error(`Invalid message: ${e instanceof Error?e.message:String(e)}`))}},window.addEventListener(`message`,this._messageHandler),this._started=!0,this._beforeUnloadHandler=()=>{this._handleBeforeUnload()},window.addEventListener(`beforeunload`,this._beforeUnloadHandler),this._cleanupInterval=setInterval(()=>{this._cleanupStaleRequests()},6e4),window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-ready`},this.SELF_TARGET_ORIGIN)}async send(e){if(!this._started)throw Error(`Transport not started`);if((`result`in e||`error`in e)&&e.id!==void 0){if(this._pendingRequests.get(e.id)?.interruptedSent){console.debug(`[TabServerTransport] Suppressing response for ${e.id} - interrupted response already sent`),this._pendingRequests.delete(e.id);return}this._pendingRequests.delete(e.id)}window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this.SELF_TARGET_ORIGIN)}_handleBeforeUnload(){let e=Array.from(this._pendingRequests.entries()).reverse();for(let[t,n]of e){n.interruptedSent=!0;let e={jsonrpc:`2.0`,id:t,result:{content:[{type:`text`,text:`Tool execution interrupted by page navigation`}],metadata:{navigationInterrupted:!0,originalMethod:`method`in n.request?n.request.method:`unknown`,timestamp:Date.now()}}};try{window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:e},this.SELF_TARGET_ORIGIN)}catch(e){console.error(`[TabServerTransport] Failed to send beforeunload response:`,e)}}this._pendingRequests.clear()}_cleanupStaleRequests(){let e=Date.now(),t=[];for(let[n,r]of this._pendingRequests)e-r.receivedAt>this.REQUEST_TIMEOUT_MS&&t.push(n);if(t.length>0){console.warn(`[TabServerTransport] Cleaning up ${t.length} stale requests`);for(let e of t)this._pendingRequests.delete(e)}}async close(){this._messageHandler&&window.removeEventListener(`message`,this._messageHandler),this._beforeUnloadHandler&&window.removeEventListener(`beforeunload`,this._beforeUnloadHandler),this._cleanupInterval!==void 0&&clearInterval(this._cleanupInterval),this._pendingRequests.clear(),this._started=!1,window.postMessage({channel:this._channelId,type:`mcp`,direction:`server-to-client`,payload:`mcp-server-stopped`},this.SELF_TARGET_ORIGIN),this.onclose?.()}};let pm=null;function mm(){return typeof window<`u`&&window.navigator!==void 0}function hm(e){try{Object.defineProperty(navigator,`modelContext`,{configurable:!0,enumerable:!0,writable:!1,value:e})}catch{Object.defineProperty(Object.getPrototypeOf(navigator),`modelContext`,{configurable:!0,enumerable:!0,get(){return e}})}navigator.modelContext!==e&&console.error(`[WebModelContext] Failed to replace navigator.modelContext.`,`Descriptor:`,Object.getOwnPropertyDescriptor(navigator,`modelContext`))}function gm(e){if(window.parent!==window&&e?.iframeServer!==!1){let{allowedOrigins:t,...n}=typeof e?.iframeServer==`object`?e.iframeServer:{};return new dm({allowedOrigins:t??[`*`],...n})}if(e?.tabServer===!1)throw Error(`tabServer transport is disabled and iframe transport was not selected`);let{allowedOrigins:t,...n}=typeof e?.tabServer==`object`?e.tabServer:{};return new fm({allowedOrigins:t??[`*`],...n})}function _m(e){if(e)try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:t}catch(e){console.warn(`[WebMCP] Failed to parse testing inputSchema JSON:`,e);return}}function vm(){let e=navigator.modelContextTesting;if(e){if(typeof e.getRegisteredTools==`function`)return{testingShim:e,tools:e.getRegisteredTools()};if(typeof e.listTools==`function`)return{testingShim:e,tools:e.listTools().map(e=>({name:e.name,description:e.description??``,inputSchema:_m(e.inputSchema)??{type:`object`,properties:{}}}))}}}function ym(e){let t=vm();if(!t)return 0;let{testingShim:n,tools:r}=t;return e.backfillTools(r,async(e,t)=>{let r=await n.executeTool(e,JSON.stringify(t??{}));if(r===null)return{content:[{type:`text`,text:`Tool execution interrupted by navigation`}],isError:!0};let i;try{i=JSON.parse(r)}catch(t){throw Error(`Failed to parse serialized tool response for ${e}: ${t instanceof Error?t.message:String(t)}`)}if(!i||typeof i!=`object`||Array.isArray(i))throw Error(`Invalid serialized tool response for ${e}`);return i})}function bm(e){if(!mm()||pm||navigator.modelContext?.[tm])return;Eu({installTestingShim:e?.installTestingShim??`if-missing`});let t=navigator.modelContext;if(!t)throw Error(`navigator.modelContext is not available`);let n=new um({name:`${window.location.hostname||`localhost`}-webmcp`,version:`1.0.0`},{native:t});n.syncNativeTools(),ym(n),hm(n);let r=gm(e?.transport);pm={native:t,server:n,transport:r},n.connect(r).catch(e=>{console.error(`[WebModelContext] Failed to connect MCP transport:`,e)})}function xm(){if(!pm)return;let{native:e,server:t,transport:n}=pm;pm=null,t.close(),n.close(),hm(e)}if(typeof window<`u`&&typeof document<`u`){let e=window.__webModelContextOptions;if(e?.autoInitialize!==!1)try{bm(e)}catch(e){console.error(`[WebModelContext] Auto-initialization failed:`,e)}}return e.cleanupWebModelContext=xm,e.initializeWebModelContext=bm,e})({});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcp-b/global",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "W3C Web Model Context API polyfill - Let AI agents like Claude, ChatGPT, and Gemini interact with your website via navigator.modelContext",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|
|
@@ -62,10 +62,10 @@
|
|
|
62
62
|
"dist"
|
|
63
63
|
],
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@mcp-b/transports": "2.
|
|
66
|
-
"@mcp-b/webmcp-
|
|
67
|
-
"@mcp-b/webmcp-
|
|
68
|
-
"@mcp-b/webmcp-types": "2.
|
|
65
|
+
"@mcp-b/transports": "2.2.0",
|
|
66
|
+
"@mcp-b/webmcp-ts-sdk": "2.2.0",
|
|
67
|
+
"@mcp-b/webmcp-polyfill": "2.2.0",
|
|
68
|
+
"@mcp-b/webmcp-types": "2.2.0"
|
|
69
69
|
},
|
|
70
70
|
"devDependencies": {
|
|
71
71
|
"@types/node": "22.17.2",
|