@mearl/mcp-server 3.0.0-beta.5 → 3.0.0-beta.8
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 +5 -5
- package/dist/THIRD_PARTY_NOTICES.txt +1 -1
- package/dist/index.js +3 -3
- package/package.json +9 -9
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
让 AI 能够与浏览器实时交互的 MCP 服务器。
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
MCP 工具与 CLI、SDK 共用浏览器动作、插件入口和控制会话。3.0 使用 npm 的 `beta` 通道。
|
|
6
6
|
|
|
7
7
|
## 功能
|
|
8
8
|
|
|
@@ -72,14 +72,14 @@ DOM 代码通过 `mearl.pageEval` 执行。文件和已注册 Skill 均从该宿
|
|
|
72
72
|
|
|
73
73
|
```bash
|
|
74
74
|
# 直接运行配置向导,会自动生成 npx 配置
|
|
75
|
-
npx @mearl/mcp-server --configure
|
|
75
|
+
npx @mearl/mcp-server@beta --configure
|
|
76
76
|
```
|
|
77
77
|
|
|
78
78
|
**方式二:全局安装(启动更快)**
|
|
79
79
|
|
|
80
80
|
```bash
|
|
81
81
|
# 全局安装
|
|
82
|
-
npm install -g @mearl/mcp-server
|
|
82
|
+
npm install -g @mearl/mcp-server@beta
|
|
83
83
|
|
|
84
84
|
# 运行配置向导
|
|
85
85
|
mearl-mcp-configure
|
|
@@ -126,7 +126,7 @@ node packages/mcp-server/dist/configure-bin.js --extension-id <你的开发版
|
|
|
126
126
|
|
|
127
127
|
> 💡 在 `chrome://extensions/` 查看你的 Extension ID
|
|
128
128
|
|
|
129
|
-
发行版本与根仓库及其他 Mearl 包统一维护,`server.json`
|
|
129
|
+
发行版本与根仓库及其他 Mearl 包统一维护,`server.json` 的版本也必须一致。发行流程见[发布文档](../../docs/releases.md)。
|
|
130
130
|
|
|
131
131
|
## 卸载
|
|
132
132
|
|
|
@@ -135,7 +135,7 @@ node packages/mcp-server/dist/configure-bin.js --extension-id <你的开发版
|
|
|
135
135
|
mearl-mcp-uninstall
|
|
136
136
|
|
|
137
137
|
# 或使用 npx
|
|
138
|
-
npx @mearl/mcp-server --uninstall
|
|
138
|
+
npx @mearl/mcp-server@beta --uninstall
|
|
139
139
|
```
|
|
140
140
|
|
|
141
141
|
## 故障排查
|
package/dist/index.js
CHANGED
|
@@ -62,9 +62,9 @@ ${content.join(`
|
|
|
62
62
|
|
|
63
63
|
`)}return doc.write("payload.value = newResult;"),doc.write("return payload;"),doc.compile()},fastpass,isObject2=isObject,jit=!globalConfig.jitless,fastEnabled=jit&&allowsEval.value,catchall=def.catchall,value;inst._zod.parse=(payload,ctx)=>{value??(value=_normalized.value);let input=payload.value;return isObject2(input)?jit&&fastEnabled&&ctx?.async===!1&&ctx.jitless!==!0?(fastpass||(fastpass=generateFastpass(def.shape)),payload=fastpass(payload,ctx),catchall?handleCatchall([],input,payload,ctx,value,inst,ctx?.abortEarly===!0):payload):superParse(payload,ctx):(payload.issues.push({expected:"object",code:"invalid_type",input,inst}),payload)}});function handleUnionResults(results,final,inst,ctx){for(let result of results)if(result.issues.length===0)return final.value=result.value,final;let nonaborted=results.filter(r=>!aborted(r));return nonaborted.length===1?(final.value=nonaborted[0].value,nonaborted[0]):(final.issues.push({code:"invalid_union",input:final.value,inst,errors:results.map(result=>result.issues.map(iss=>finalizeIssue(iss,ctx,config())))}),final)}var $ZodUnion=$constructor("$ZodUnion",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",zod=>zod.def.options.some(o=>o._zod.optin==="defaulted")?"defaulted":zod.def.options.some(o=>o._zod.optin!==void 0)?"optional":void 0),defineLazyInternal(inst,"optout",zod=>zod.def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),defineLazyInternal(inst,"values",zod=>{if(zod.def.options.every(o=>o._zod.values))return new Set(zod.def.options.flatMap(option=>Array.from(option._zod.values)))}),defineLazyInternal(inst,"pattern",zod=>{if(zod.def.options.every(o=>o._zod.pattern)){let patterns=zod.def.options.map(o=>o._zod.pattern);return new RegExp(`^(${patterns.map(p=>cleanRegex(p.source)).join("|")})$`)}});let first=def.options.length===1?def.options[0]._zod.run:null;inst._zod.parse=(payload,ctx)=>{if(first)return first(payload,ctx);let async=!1,results=[];for(let option of def.options){let result=option._zod.run({value:payload.value,issues:[]},ctx);if(result instanceof Promise)results.push(result),async=!0;else{if(result.issues.length===0)return result;results.push(result)}}return async?Promise.all(results).then(results2=>handleUnionResults(results2,payload,inst,ctx)):handleUnionResults(results,payload,inst,ctx)}});function discriminatorMap(def){let map=new Map;for(let option of def.options){let values=option._zod.propValues?.[def.discriminator];if(!values||values.size===0)throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);for(let value of values)if(map.has(value)){if(value!==void 0)throw new Error(`Duplicate discriminator value "${String(value)}"`);map.set(value,null)}else map.set(value,option)}return map}var $ZodDiscriminatedUnion=$constructor("$ZodDiscriminatedUnion",(inst,def)=>{def.inclusive=!1,$ZodUnion.init(inst,def);let _super=inst._zod.parse;defineLazyInternal(inst,"propValues",zod=>{let propValues={},undefinedCount=0;for(let option of zod.def.options){let pv=option._zod.propValues;if(!pv||Object.keys(pv).length===0)throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`);pv[zod.def.discriminator]?.has(void 0)&&undefinedCount++;for(let[k,v]of Object.entries(pv)){Object.prototype.hasOwnProperty.call(propValues,k)||assignProp(propValues,k,new Set);for(let val of v)propValues[k].add(val)}}return!zod.def.unionFallback&&undefinedCount>1&&propValues[zod.def.discriminator]?.delete(void 0),propValues}),def.options.forEach((option,i)=>{let propShape=rawShape(option._zod.def);if(propShape&&!Object.prototype.hasOwnProperty.call(propShape,def.discriminator))throw new Error(`Invalid discriminated union option at index "${i}"`)});let disc=cached(()=>discriminatorMap(def));inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isObject(input))return payload.issues.push({code:"invalid_type",expected:"object",input,inst}),payload;let value=input?.[def.discriminator],opt=disc.value.get(value);return opt&&(value!==void 0||ctx.direction!=="backward")?opt._zod.run(payload,ctx):def.unionFallback||ctx.direction==="backward"?_super(payload,ctx):(payload.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:def.discriminator,options:Array.from(disc.value.keys()).filter(value2=>disc.value.get(value2)!==null),input,path:[def.discriminator],inst}),payload)}}),$ZodIntersection=$constructor("$ZodIntersection",(inst,def)=>{$ZodType.init(inst,def),inst._zod.parse=(payload,ctx)=>{let input=payload.value,left=def.left._zod.run({value:input,issues:[]},ctx),right=def.right._zod.run({value:input,issues:[]},ctx);return left instanceof Promise||right instanceof Promise?Promise.all([left,right]).then(([left2,right2])=>handleIntersectionResults(payload,left2,right2)):handleIntersectionResults(payload,left,right)}});function mergeValues(a,b){if(a===b)return{valid:!0,data:a};if(a instanceof Date&&b instanceof Date&&+a==+b)return{valid:!0,data:a};if(isPlainObject(a)&&isPlainObject(b)){let bKeys=Object.keys(b),sharedKeys=Object.keys(a).filter(key=>bKeys.indexOf(key)!==-1),newObj={...a,...b};Object.prototype.hasOwnProperty.call(newObj,"__proto__")&&delete newObj.__proto__;for(let key of sharedKeys){if(key==="__proto__")continue;let sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[key,...sharedValue.mergeErrorPath]};newObj[key]=sharedValue.data}return{valid:!0,data:newObj}}if(Array.isArray(a)&&Array.isArray(b)){if(a.length!==b.length)return{valid:!1,mergeErrorPath:[]};let newArray=[];for(let index=0;index<a.length;index++){let itemA=a[index],itemB=b[index],sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid)return{valid:!1,mergeErrorPath:[index,...sharedValue.mergeErrorPath]};newArray.push(sharedValue.data)}return{valid:!0,data:newArray}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(result,left,right){let unrecKeys=new Map,unrecIssue,keyIssues=new Map,collect=(iss,side)=>{let keys;if(iss.code==="unrecognized_keys"&&!iss.path?.length)unrecIssue??(unrecIssue=iss),keys=iss.keys;else if(iss.code==="invalid_key"&&iss.origin==="record"&&iss.path?.length===1){let k=String(iss.path[0]);keyIssues.has(k)||keyIssues.set(k,iss),keys=[k]}else return!1;for(let k of keys)unrecKeys.has(k)||unrecKeys.set(k,{}),unrecKeys.get(k)[side]=!0;return!0};for(let iss of left.issues)collect(iss,"l")||result.issues.push(iss);for(let iss of right.issues)collect(iss,"r")||result.issues.push(iss);let bothKeys=[...unrecKeys].filter(([,f])=>f.l&&f.r).map(([k])=>k);if(bothKeys.length){let aggregated=unrecIssue?bothKeys.filter(k=>unrecIssue.keys.includes(k)):[];aggregated.length&&result.issues.push({...unrecIssue,keys:aggregated});for(let k of bothKeys)!aggregated.includes(k)&&keyIssues.has(k)&&result.issues.push(keyIssues.get(k))}let merged=mergeValues(left.value,right.value);if(!merged.valid){if(aborted(result))return result;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`)}return result.value=merged.data,result}var $ZodRecord=$constructor("$ZodRecord",(inst,def)=>{$ZodType.init(inst,def);let memo2=globalConfig.memoizer;memo2?.attach(inst),inst._zod.parse=(payload,ctx)=>{let input=payload.value;if(!isPlainObject(input))return payload.issues.push({expected:"record",code:"invalid_type",input,inst}),payload;let proms=[],values=def.keyType._zod.values;if(values&&!def.partial){payload.value=memo2?memo2.alloc(inst,payload,{},ctx):{};let recordKeys=new Set;for(let key of values)if(typeof key=="string"||typeof key=="number"||typeof key=="symbol"){if(recordKeys.add(typeof key=="number"?key.toString():key),key==="__proto__")continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(keyResult.issues.length){payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value;if(outKey==="__proto__")continue;let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[outKey]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[outKey]=result.value)}let unrecognized;for(let key in input)if(!recordKeys.has(key))if(def.mode==="loose"){if(key==="__proto__")continue;payload.value[key]=input[key]}else unrecognized=unrecognized??[],unrecognized.push(key);unrecognized&&unrecognized.length>0&&payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized,continue:!0})}else{payload.value=memo2?memo2.alloc(inst,payload,{},ctx):{};let unrecognized;for(let key of Reflect.ownKeys(input)){if(key==="__proto__"||!Object.prototype.propertyIsEnumerable.call(input,key))continue;let keyResult=def.keyType._zod.run({value:key,issues:[]},ctx);if(keyResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof key=="string"&&number.test(key)&&keyResult.issues.length){let retryResult=def.keyType._zod.run({value:Number(key),issues:[]},ctx);if(retryResult instanceof Promise)throw new Error("Async schemas not supported in object keys currently");retryResult.issues.length===0&&(keyResult=retryResult)}if(keyResult.issues.length){def.mode==="loose"?payload.value[key]=input[key]:values?(unrecognized=unrecognized??[],unrecognized.push(key)):payload.issues.push({code:"invalid_key",origin:"record",issues:keyResult.issues.map(iss=>finalizeIssue(iss,ctx,config())),input:key,path:[key],inst});continue}let outKey=keyResult.value;if(outKey==="__proto__")continue;let result=def.valueType._zod.run({value:input[key],issues:[]},ctx);result instanceof Promise?proms.push(result.then(result2=>{result2.issues.length&&payload.issues.push(...prefixIssues(key,result2.issues)),payload.value[outKey]=result2.value})):(result.issues.length&&payload.issues.push(...prefixIssues(key,result.issues)),payload.value[outKey]=result.value)}unrecognized&&unrecognized.length>0&&payload.issues.push({code:"unrecognized_keys",input,inst,keys:unrecognized,continue:!0})}return proms.length?Promise.all(proms).then(()=>payload):payload}});var $ZodEnum=$constructor("$ZodEnum",(inst,def)=>{$ZodType.init(inst,def);let values=getEnumValues(def.entries),valuesSet=new Set(values);inst._zod.values=valuesSet,defineLazyInternal(inst,"pattern",zod=>{let patternValues=getEnumValues(zod.def.entries).filter(k=>propertyKeyTypes.has(typeof k));return new RegExp(patternValues.length?`^(${patternValues.map(o=>escapeRegex(o.toString())).join("|")})$`:"^[^\\s\\S]$")}),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return valuesSet.has(input)||payload.issues.push({code:"invalid_value",values,input,inst}),payload}}),$ZodLiteral=$constructor("$ZodLiteral",(inst,def)=>{$ZodType.init(inst,def);let values=new Set(def.values);inst._zod.values=values,defineLazyInternal(inst,"pattern",zod=>{let vals=zod.def.values;return new RegExp(vals.length?`^(${vals.map(o=>typeof o=="string"?escapeRegex(o):o?escapeRegex(o.toString()):String(o)).join("|")})$`:"^[^\\s\\S]$")}),inst._zod.parse=(payload,_ctx)=>{let input=payload.value;return values.has(input)||payload.issues.push({code:"invalid_value",values:def.values,input,inst}),payload}});var $ZodTransform=$constructor("$ZodTransform",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="optional",globalConfig.memoizer?.guard(inst),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);let _out=def.transform(payload.value,payload);if(ctx.async)return(_out instanceof Promise?_out:Promise.resolve(_out)).then(output2=>(payload.value=output2,payload));if(_out instanceof Promise)throw new $ZodAsyncError;return payload.value=_out,payload}});function handleOptionalResult(payload,result){return payload.value=result.issues.length?void 0:result.value,payload}var $ZodOptional=$constructor("$ZodOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",zod=>zod.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),inst._zod.optout="optional",defineLazyInternal(inst,"values",zod=>{let values=zod.def.innerType._zod.values;return values?new Set([...values,void 0]):void 0}),defineLazyInternal(inst,"pattern",zod=>{let pattern=zod.def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)})?$`):void 0}),inst._zod.parse=(payload,ctx)=>{if(payload.value===void 0){if(def.innerType._zod.optin!=="defaulted")return payload;let result=def.innerType._zod.run({value:payload.value,issues:[]},ctx);return result instanceof Promise?result.then(result2=>handleOptionalResult(payload,result2)):handleOptionalResult(payload,result)}return def.innerType._zod.run(payload,ctx)}}),$ZodExactOptional=$constructor("$ZodExactOptional",(inst,def)=>{$ZodOptional.init(inst,def),defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),defineLazyInternal(inst,"pattern",zod=>zod.def.innerType._zod.pattern),inst._zod.parse=(payload,ctx)=>def.innerType._zod.run(payload,ctx)}),$ZodNullable=$constructor("$ZodNullable",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",zod=>zod.def.innerType._zod.optin),defineLazyInternal(inst,"optout",zod=>zod.def.innerType._zod.optout),defineLazyInternal(inst,"pattern",zod=>{let pattern=zod.def.innerType._zod.pattern;return pattern?new RegExp(`^(${cleanRegex(pattern.source)}|null)$`):void 0}),defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values?new Set([...zod.def.innerType._zod.values,null]):void 0),inst._zod.parse=(payload,ctx)=>payload.value===null?payload:def.innerType._zod.run(payload,ctx)}),$ZodDefault=$constructor("$ZodDefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="defaulted",defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);if(payload.value===void 0)return payload.value=def.defaultValue,payload;let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleDefaultResult(result2,def)):handleDefaultResult(result,def)}});function handleDefaultResult(payload,def){return payload.value===void 0&&(payload.value=def.defaultValue),payload}var $ZodPrefault=$constructor("$ZodPrefault",(inst,def)=>{$ZodType.init(inst,def),inst._zod.optin="defaulted",defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>(ctx.direction==="backward"||payload.value===void 0&&(payload.value=def.defaultValue),def.innerType._zod.run(payload,ctx))}),$ZodNonOptional=$constructor("$ZodNonOptional",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"values",zod=>{let v=zod.def.innerType._zod.values;return v?new Set([...v].filter(x=>x!==void 0)):void 0}),inst._zod.parse=(payload,ctx)=>{let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(result2=>handleNonOptionalResult(result2,inst)):handleNonOptionalResult(result,inst)}});function handleNonOptionalResult(payload,inst){return!payload.issues.length&&payload.value===void 0&&payload.issues.push({code:"invalid_type",expected:"nonoptional",input:payload.value,inst}),payload}function handleCatchResult(payload,result,def,ctx){return result.issues.length?(payload.value=def.catchValue({...result,value:payload.value,error:{issues:result.issues.map(iss=>finalizeIssue(iss,ctx,config()))},input:payload.value}),payload):(payload.value=result.value,result.memo&&(payload.memo=!0),payload)}var $ZodCatch=$constructor("$ZodCatch",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"optin",zod=>zod.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),defineLazyInternal(inst,"optout",zod=>zod.def.innerType._zod.optout),defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run({value:payload.value,issues:[]},ctx);return result instanceof Promise?result.then(result2=>handleCatchResult(payload,result2,def,ctx)):handleCatchResult(payload,result,def,ctx)}});var $ZodPipe=$constructor("$ZodPipe",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"values",zod=>zod.def.in._zod.values),defineLazyInternal(inst,"optin",zod=>zod.def.in._zod.optin),defineLazyInternal(inst,"optout",zod=>zod.def.out._zod.optout),defineLazyInternal(inst,"propValues",zod=>zod.def.in._zod.propValues),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward"){let right=def.out._zod.run(payload,ctx);return right instanceof Promise?right.then(right2=>handlePipeResult(right2,def.in,ctx)):handlePipeResult(right,def.in,ctx)}let left=def.in._zod.run(payload,ctx);return left instanceof Promise?left.then(left2=>handlePipeResult(left2,def.out,ctx)):handlePipeResult(left,def.out,ctx)}});function handlePipeResult(left,next,ctx){return left.issues.some(iss=>iss.code!=="unrecognized_keys")?(left.aborted=!0,left):next._zod.run({value:left.value,issues:left.issues},ctx)}var $ZodPreprocess=$constructor("$ZodPreprocess",(inst,def)=>{$ZodPipe.init(inst,def)}),$ZodReadonly=$constructor("$ZodReadonly",(inst,def)=>{$ZodType.init(inst,def),defineLazyInternal(inst,"propValues",zod=>zod.def.innerType._zod.propValues),defineLazyInternal(inst,"values",zod=>zod.def.innerType._zod.values),defineLazyInternal(inst,"optin",zod=>zod.def.innerType?._zod?.optin),defineLazyInternal(inst,"optout",zod=>zod.def.innerType?._zod?.optout),inst._zod.parse=(payload,ctx)=>{if(ctx.direction==="backward")return def.innerType._zod.run(payload,ctx);let result=def.innerType._zod.run(payload,ctx);return result instanceof Promise?result.then(handleReadonlyResult):handleReadonlyResult(result)}});function handleReadonlyResult(payload){return payload.memo||(payload.value=Object.freeze(payload.value)),payload}var $ZodCustom=$constructor("$ZodCustom",(inst,def)=>{$ZodCheck.init(inst,def),$ZodType.init(inst,def),inst._zod.parse=(payload,_)=>payload,inst._zod.check=payload=>{let input=payload.value,r=def.fn(input);if(r instanceof Promise)return r.then(r2=>handleRefineResult(r2,payload,input,inst));handleRefineResult(r,payload,input,inst)}});function handleRefineResult(result,payload,input,inst){if(!result){let _iss={code:"custom",input,inst,path:[...inst._zod.def.path??[]],continue:!inst._zod.def.abort};inst._zod.def.params&&(_iss.params=inst._zod.def.params),payload.issues.push(issue(_iss))}}var $ZodCyclicError=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},STATE="~memo",NO_ISSUES=[];function isRef(value){return value!==null&&typeof value=="object"}function cloneIssues(issues){return issues.map(iss=>iss.path?{...iss,path:iss.path.slice()}:{...iss})}var recursive=new WeakMap,NONE=0,ASSUMED=1,PROVEN=2;function isRecursive(inst,stack,resolve){let cached2=recursive.get(inst);if(cached2!==void 0)return cached2?PROVEN:NONE;if(stack.has(inst))return PROVEN;stack.add(inst);let result=NONE,check=child=>{if(result!==PROVEN&&child?._zod){let answer=isRecursive(child,stack,resolve);answer>result&&(result=answer)}},shape=(sh,spread)=>{let answer=NONE;for(let key of Reflect.ownKeys(sh)){let desc=Object.getOwnPropertyDescriptor(sh,key);if(spread&&!desc.enumerable)continue;let child=desc.get?ASSUMED:desc.value?._zod?isRecursive(desc.value,stack,resolve):NONE;child>answer&&(answer=child)}return answer},merge2=answer=>{answer>result&&(result=answer)},def=inst._zod.def,kind=def.type;switch(kind){case"object":{let raw=rawShape(def);merge2(raw?shape(raw,!0):ASSUMED),check(def.catchall);break}case"array":check(def.element);break;case"tuple":for(let el of def.items)check(el);check(def.rest);break;case"record":case"map":check(def.keyType),check(def.valueType);break;case"set":check(def.valueType);break;case"union":for(let el of def.options)check(el);break;case"intersection":check(def.left),check(def.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":check(def.innerType);break;case"pipe":check(def.in),check(def.out);break;case"function":check(def.input),check(def.output);break;case"lazy":{let inner=def._cachedInner??(resolve?inst._zod.innerType:void 0);merge2(inner?isRecursive(inner,stack,!1):ASSUMED);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let key in def){let desc=Object.getOwnPropertyDescriptor(def,key);if(!desc||desc.get)continue;let value=desc.value;if(!(!value||typeof value!="object")){if(value._zod)check(value);else if(Array.isArray(value))for(let el of value)check(el)}}}return stack.delete(inst),settle(inst,result)}function settle(inst,answer){return answer!==ASSUMED&&recursive.set(inst,answer===PROVEN),answer}function bucketFor(state,inst){let bucket=state.buckets.get(inst);return bucket||(bucket=new WeakMap,state.buckets.set(inst,bucket)),bucket}var handoff,open=[],memo={alloc(_inst,payload,empty){let bucket=handoff;if(!bucket)return empty;handoff=void 0;let entry={value:empty,issues:null};return bucket.set(payload.value,entry),open.push(entry),empty},guard(inst){var _a3;(_a3=inst._zod).deferred??(_a3.deferred=[]),inst._zod.deferred.push(()=>{let base=inst._zod.parse,wrapped=(payload,ctx)=>{if(ctx.direction!=="backward"&&isBackEdge(ctx,payload.value))throw new $ZodCyclicError;return base(payload,ctx)};inst._zod.parse=wrapped,inst._zod.run===base&&(inst._zod.run=wrapped)})},attach(inst){var _a3;let isRecursiveInst,rechecked=!1,lastCtx,lastBucket;(_a3=inst._zod).deferred??(_a3.deferred=[]),inst._zod.deferred.push(()=>{let base=inst._zod.parse,wrapped=(payload,ctx)=>{if(isRecursiveInst===void 0){let walked=isRecursive(inst,new Set,!1);if(walked===NONE)return inst._zod.parse=base,inst._zod.run===wrapped&&(inst._zod.run=base),base(payload,ctx);walked===PROVEN||rechecked?isRecursiveInst=!0:rechecked=!0}let input=payload.value;if(!isRef(input))return base(payload,ctx);let state=ctx[STATE];state||(state={buckets:new WeakMap,backEdges:void 0},ctx[STATE]=state);let bucket;lastCtx===ctx?bucket=lastBucket:(bucket=bucketFor(state,inst),lastCtx=ctx,lastBucket=bucket);let hit=bucket.get(input);if(hit)return payload.value=hit.value,hit.issues?hit.issues.length&&payload.issues.push(...cloneIssues(hit.issues)):(payload.memo=!0,state.backEdges??(state.backEdges=new WeakSet),state.backEdges.add(hit.value)),payload;handoff=bucket;let depth=open.length,result=base(payload,ctx);handoff=void 0;let entry=open.length>depth?open.pop():void 0;return result instanceof Promise?result.then(r=>(entry&&(entry.issues=r.issues.length?cloneIssues(r.issues):NO_ISSUES),r)):(entry&&(entry.issues=result.issues.length?cloneIssues(result.issues):NO_ISSUES),result)};inst._zod.parse=wrapped,inst._zod.run===base&&(inst._zod.run=wrapped)})}};function memoizer(){return memo}function isBackEdge(ctx,value){let backEdges=ctx[STATE]?.backEdges;return backEdges!==void 0&&isRef(value)&&backEdges.has(value)}var error=()=>{let Sizable={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function getSizing(origin){return Sizable[origin]??null}let FormatDictionary={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},TypeDictionary={nan:"NaN"};function getTypeName(type,input){return type==="number"&&typeof input=="number"&&!Number.isFinite(input)?String(input):TypeDictionary[type]??type}return issue2=>{switch(issue2.code){case"invalid_type":{let expected=getTypeName(issue2.expected),receivedType=parsedType(issue2.input),received=getTypeName(receivedType,issue2.input);return`Invalid input: expected ${expected}, received ${received}`}case"invalid_value":return issue2.values.length===1?`Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`:`Invalid option: expected one of ${joinValues(issue2.values,"|")}`;case"too_big":{let adj=issue2.exact?"exactly ":issue2.inclusive?"<=":"<",sizing=getSizing(issue2.origin);return sizing?`Too big: expected ${issue2.origin??"value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit??"elements"}`:`Too big: expected ${issue2.origin??"value"} to be ${adj}${issue2.maximum.toString()}`}case"too_small":{let adj=issue2.exact?"exactly ":issue2.inclusive?">=":">",sizing=getSizing(issue2.origin);return sizing?`Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`:`Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`}case"invalid_format":{let _issue=issue2;return _issue.format==="starts_with"?`Invalid string: must start with "${_issue.prefix}"`:_issue.format==="ends_with"?`Invalid string: must end with "${_issue.suffix}"`:_issue.format==="includes"?`Invalid string: must include "${_issue.includes}"`:_issue.format==="regex"?`Invalid string: must match pattern ${_issue.pattern}`:`Invalid ${FormatDictionary[_issue.format]??issue2.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${issue2.divisor}`;case"unrecognized_keys":return`Unrecognized key${issue2.keys.length>1?"s":""}: ${joinValues(issue2.keys,", ")}`;case"invalid_key":return`Invalid key in ${issue2.origin}`;case"invalid_union":return issue2.options&&Array.isArray(issue2.options)&&issue2.options.length>0?`Invalid discriminator value. Expected ${issue2.options.map(o=>`'${o}'`).join(" | ")}`:issue2.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${issue2.origin}`;default:return"Invalid input"}}};function en_default(){return{localeError:error()}}var _a2;var $ZodRegistry=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(schema,..._meta){let meta2=_meta[0];return this._map.set(schema,meta2),meta2&&typeof meta2=="object"&&"id"in meta2&&this._idmap.set(meta2.id,schema),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(schema){let meta2=this._map.get(schema);return meta2&&typeof meta2=="object"&&"id"in meta2&&this._idmap.delete(meta2.id),this._map.delete(schema),this}get(schema){let p=schema._zod.parent;if(p){let pm={...this.get(p)??{}};delete pm.id;let f={...pm,...this._map.get(schema)};return Object.keys(f).length?f:void 0}return this._map.get(schema)}has(schema){return this._map.has(schema)}};function registry(){return new $ZodRegistry}(_a2=globalThis).__zod_globalRegistry??(_a2.__zod_globalRegistry=registry());var globalRegistry=globalThis.__zod_globalRegistry;function snapshotChecks(def){return def.checks&&(def.checks=[...def.checks]),def}function _string(Class2,params){return new Class2(snapshotChecks({type:"string",...normalizeParams(params)}))}function _email(Class2,params){return new Class2({type:"string",format:"email",check:"string_format",abort:!1,...normalizeParams(params)})}function _guid(Class2,params){return new Class2({type:"string",format:"guid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuid(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _uuidv4(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...normalizeParams(params)})}function _uuidv6(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...normalizeParams(params)})}function _uuidv7(Class2,params){return new Class2({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...normalizeParams(params)})}function _url(Class2,params){return new Class2({type:"string",format:"url",check:"string_format",abort:!1,...normalizeParams(params)})}function _emoji2(Class2,params){return new Class2({type:"string",format:"emoji",check:"string_format",abort:!1,...normalizeParams(params)})}function _nanoid(Class2,params){return new Class2({type:"string",format:"nanoid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid(Class2,params){return new Class2({type:"string",format:"cuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _cuid2(Class2,params){return new Class2({type:"string",format:"cuid2",check:"string_format",abort:!1,...normalizeParams(params)})}function _ulid(Class2,params){return new Class2({type:"string",format:"ulid",check:"string_format",abort:!1,...normalizeParams(params)})}function _xid(Class2,params){return new Class2({type:"string",format:"xid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ksuid(Class2,params){return new Class2({type:"string",format:"ksuid",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv4(Class2,params){return new Class2({type:"string",format:"ipv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _ipv6(Class2,params){return new Class2({type:"string",format:"ipv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv4(Class2,params){return new Class2({type:"string",format:"cidrv4",check:"string_format",abort:!1,...normalizeParams(params)})}function _cidrv6(Class2,params){return new Class2({type:"string",format:"cidrv6",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64(Class2,params){return new Class2({type:"string",format:"base64",check:"string_format",abort:!1,...normalizeParams(params)})}function _base64url(Class2,params){return new Class2({type:"string",format:"base64url",check:"string_format",abort:!1,...normalizeParams(params)})}function _e164(Class2,params){return new Class2({type:"string",format:"e164",check:"string_format",abort:!1,...normalizeParams(params)})}function _jwt(Class2,params){return new Class2({type:"string",format:"jwt",check:"string_format",abort:!1,...normalizeParams(params)})}function _isoDateTime(Class2,params){return new Class2({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...normalizeParams(params)})}function _isoDate(Class2,params){return new Class2({type:"string",format:"date",check:"string_format",...normalizeParams(params)})}function _isoTime(Class2,params){return new Class2({type:"string",format:"time",check:"string_format",precision:null,...normalizeParams(params)})}function _isoDuration(Class2,params){return new Class2({type:"string",format:"duration",check:"string_format",...normalizeParams(params)})}function _number(Class2,params){return new Class2(snapshotChecks({type:"number",checks:[],...normalizeParams(params)}))}function _int(Class2,params){return new Class2({type:"number",check:"number_format",abort:!1,format:"safeint",...normalizeParams(params)})}function _boolean(Class2,params){return new Class2({type:"boolean",...normalizeParams(params)})}function _null2(Class2,params){return new Class2({type:"null",...normalizeParams(params)})}function _unknown(Class2){return new Class2({type:"unknown"})}function _never(Class2,params){return new Class2({type:"never",...normalizeParams(params)})}function _lt(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!1})}function _lte(value,params){return new $ZodCheckLessThan({check:"less_than",...normalizeParams(params),value,inclusive:!0})}function _gt(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!1})}function _gte(value,params){return new $ZodCheckGreaterThan({check:"greater_than",...normalizeParams(params),value,inclusive:!0})}function _multipleOf(value,params){return new $ZodCheckMultipleOf({check:"multiple_of",...normalizeParams(params),value})}function _maxLength(maximum,params){return new $ZodCheckMaxLength({check:"max_length",...normalizeParams(params),maximum})}function _minLength(minimum,params){return new $ZodCheckMinLength({check:"min_length",...normalizeParams(params),minimum})}function _length(length,params){return new $ZodCheckLengthEquals({check:"length_equals",...normalizeParams(params),length})}function _regex(pattern,params){return new $ZodCheckRegex({check:"string_format",format:"regex",...normalizeParams(params),pattern})}function _lowercase(params){return new $ZodCheckLowerCase({check:"string_format",format:"lowercase",...normalizeParams(params)})}function _uppercase(params){return new $ZodCheckUpperCase({check:"string_format",format:"uppercase",...normalizeParams(params)})}function _includes(includes,params){return new $ZodCheckIncludes({check:"string_format",format:"includes",...normalizeParams(params),includes})}function _startsWith(prefix,params){return new $ZodCheckStartsWith({check:"string_format",format:"starts_with",...normalizeParams(params),prefix})}function _endsWith(suffix,params){return new $ZodCheckEndsWith({check:"string_format",format:"ends_with",...normalizeParams(params),suffix})}function _overwrite(tx){return new $ZodCheckOverwrite({check:"overwrite",tx})}function _normalize(form){return _overwrite(input=>input.normalize(form))}function _trim(){return _overwrite(input=>input.trim())}function _toLowerCase(){return _overwrite(input=>input.toLowerCase())}function _toUpperCase(){return _overwrite(input=>input.toUpperCase())}function _slugify(){return _overwrite(input=>slugify(input))}function _array(Class2,element,params){return new Class2({type:"array",element,...normalizeParams(params)})}function _custom(Class2,fn,_params){let norm=normalizeParams(_params);return norm.abort??(norm.abort=!0),new Class2({type:"custom",check:"custom",fn,...norm})}function _refine(Class2,fn,_params){return new Class2({type:"custom",check:"custom",fn,...normalizeParams(_params)})}function _superRefine(fn,params){let ch=_check(payload=>(payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(issue(issue2,payload.value,ch._zod.def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=ch),_issue.continue??(_issue.continue=!ch._zod.def.abort),payload.issues.push(issue(_issue))}},fn(payload.value,payload)),params);return ch}function _check(fn,params){let ch=new $ZodCheck({check:"custom",...normalizeParams(params)});return ch._zod.check=fn,ch}function assignProps(target,...sources){for(let source of sources)for(let key of Reflect.ownKeys(source))Object.prototype.propertyIsEnumerable.call(source,key)&&assignProp(target,key,source[key]);return target}function initializeContext(params){let target=params?.target??"draft-2020-12";return target==="draft-4"&&(target="draft-04"),target==="draft-7"&&(target="draft-07"),{processors:params.processors??{},metadataRegistry:params?.metadata??globalRegistry,target,unrepresentable:params?.unrepresentable??"throw",override:params?.override??(()=>{}),io:params?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:params?.cycles??"ref",reused:params?.reused??"inline",intersections:[],deferred:[],external:params?.external??void 0}}function handleUnrepresentable(schema,ctx,json,params,message){let result=typeof ctx.unrepresentable=="function"?ctx.unrepresentable({zodSchema:schema,path:params.path,message}):ctx.unrepresentable;if(result==="any")return!1;if(result===void 0||result==="throw")throw new Error(message);return Object.assign(json,result),!0}function processSchema(schema,ctx,_params={path:[],schemaPath:[]}){var _a3;let def=schema._zod.def,seen=ctx.seen.get(schema);if(seen)return seen.count++,_params.schemaPath.includes(schema)&&(seen.cycle=_params.path),seen.schema;let result={schema:{},count:1,cycle:void 0,path:_params.path};ctx.seen.set(schema,result),ctx.sharedDefsExtractedFor=void 0,ctx.sharedEmitDoneFor=void 0;let overrideSchema=schema._zod.toJSONSchema?.();if(overrideSchema)result.schema=overrideSchema;else{let params={..._params,schemaPath:[..._params.schemaPath,schema],path:_params.path};if(schema._zod.processJSONSchema)schema._zod.processJSONSchema(ctx,result.schema,params);else{let _json=result.schema,processor=ctx.processors[def.type];if(!processor)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);processor(schema,ctx,_json,params)}let parent=schema._zod.parent;parent&&(result.ref||(result.ref=parent),processSchema(parent,ctx,params),ctx.seen.get(parent).isParent=!0)}let meta2=ctx.metadataRegistry.get(schema);return meta2&&assignProps(result.schema,meta2),ctx.io==="input"&&isTransforming(schema)&&(delete result.schema.examples,delete result.schema.default),ctx.io==="input"&&"_prefault"in result.schema&&((_a3=result.schema).default??(_a3.default=result.schema._prefault)),delete result.schema._prefault,ctx.seen.get(schema).schema}function encodeJSONPointerSegment(segment){return segment.replace(/~/g,"~0").replace(/\//g,"~1")}function extractDefs(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");if(ctx.external&&ctx.sharedDefsExtractedFor===ctx.external)return;let idToSchema=new Map;for(let entry of ctx.seen.entries()){let id=ctx.metadataRegistry.get(entry[0])?.id;if(id){let existing=idToSchema.get(id);if(existing&&existing!==entry[0])throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);idToSchema.set(id,entry[0])}}let makeURI=entry=>{let defsSegment=ctx.target==="draft-2020-12"?"$defs":"definitions";if(ctx.external){let externalId=ctx.external.registry.get(entry[0])?.id,uriGenerator=ctx.external.uri??(id2=>id2);if(externalId)return{ref:uriGenerator(externalId)};let id=entry[1].defId??entry[1].schema.id??`schema${ctx.counter++}`;return entry[1].defId=id,{defId:id,ref:`${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`}}let uriPrefix="#",defUriPrefix=`${uriPrefix}/${defsSegment}/`;if(entry[1]===root&&!entry[1].schema.id)return{ref:uriPrefix};let defId=entry[1].schema.id??`__schema${ctx.counter++}`;return{defId,ref:defUriPrefix+encodeJSONPointerSegment(defId)}},extractToDef=entry=>{if(entry[1].schema.$ref)return;let seen=entry[1],{ref,defId}=makeURI(entry);seen.def={...seen.schema},defId&&(seen.defId=defId);let schema2=seen.schema;for(let key in schema2)delete schema2[key];schema2.$ref=ref};if(ctx.cycles==="throw")for(let entry of ctx.seen.entries()){let seen=entry[1];if(seen.cycle)throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
|
|
64
64
|
|
|
65
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!="string")return;types.includes(member)||types.push(member)}}delete schema.anyOf,schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required2=new Set;for(let object3 of objects){for(let key in object3.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part=other.properties?.[key]??undeclaredConstraint(other);part!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part))||parts.push(part))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object3.required??[])required2.add(key)}let folded={type:"object",properties};if(required2.size&&(folded.required=[...required2]),objects.every(object3=>object3.additionalProperties===!1))folded.additionalProperties=!1;else{let constraints=[];for(let object3 of objects){let constraint=undeclaredConstraint(object3);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded.additionalProperties=constraints[0]:constraints.length>1&&(folded.additionalProperties={allOf:constraints})}return folded}function foldIntersection(json){let allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded=null;if(!unions.length)folded=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded={[keyword]:branches}}folded&&(delete json.allOf,assignProps(json,folded))}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):assignProps(schema2,refSchema),assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2)key==="$ref"||key==="allOf"||key in _cached||delete schema2[key];if(refSchema.$ref&&refSeen.def)for(let key in schema2)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])&&delete schema2[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema2)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])&&delete schema2[key]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json of[seen.schema,seen.def]){let allOf=json?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json):carriers.set(allOf,[json])}for(let allOf of ctx.intersections)for(let json of carriers.get(allOf)??[])foldIntersection(json)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{(agg[key]===void 0||value>agg[key])&&(agg[key]=value)},narrowMax=(agg,key,value)=>{(agg[key]===void 0||value<agg[key])&&(agg[key]=value)},narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value),narrowMax(agg,"maximum",value)},addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value)||agg.multipleOf.push(value)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{agg.format=format,format.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);let bag=schema._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum=="number"&&(json.minLength=minimum),typeof maximum=="number"&&(json.maxLength=maximum),format&&(json.format=formatMap[format]??format,json.format===""&&delete json.format,(format==="time"||laxFormat)&&delete json.format),contentEncoding&&(json.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json.pattern=patternList[0].source:patternList.length>1&&(json.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,params)=>{let json=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0):json.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json.minimum=minimum),exMax?legacy?(json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0):json.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json.multipleOf=first),rest.length&&(json.allOf=[...json.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var nullProcessor=(_schema,ctx,json,_params)=>{ctx.target==="openapi-3.0"?(json.type="string",json.nullable=!0,json.enum=[null]):json.type="null"};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.length===0){json.not={};return}values.every(v=>typeof v=="number")&&(json.type="number"),values.every(v=>typeof v=="string")&&(json.type="string"),json.enum=values},literalProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;if(def.values.length===0){json.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json.enum=[val]:json.const=val}else vals.every(v=>typeof v=="number")&&(json.type="number"),vals.every(v=>typeof v=="string")&&(json.type="string"),vals.every(v=>typeof v=="boolean")&&(json.type="boolean"),vals.every(v=>v===null)&&(json.type="null"),json.enum=vals};var customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")};var transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")};var arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum),json.type="array",json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){let def=schema._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema"))return;json.type="object",json.properties={};for(let key in shape)assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key)}requiredKeys.length>0&&(json.required=requiredKeys),def.catchall?._zod.def.type==="never"?json.additionalProperties=!1:def.catchall?def.catchall&&(json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json.additionalProperties=!1)},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json.oneOf=options:json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf,ctx.intersections.push(allOf)};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);let def=bySchema.get(json)?.def;if(!def)return json;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i)=>branch!==branches[i])&&(json={...json,[keyword]:mapped})}let types=Array.isArray(json.type)?json.type:[json.type],numericType=!types.includes("string")&&types.some(t=>t==="number"||t==="integer"),values=json.enum??(json.const!==void 0?[json.const]:void 0);if(!numericType&&!values?.some(v=>typeof v=="number"))return json;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values||(rest.pattern=(types.includes("number")?number:integer).source)),rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record2 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record2),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);rewritten!==names&&rewrites.set(names,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}var recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);pending||(pending=[],pendingRecords.set(ctx,pending),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending.push(schema)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json.required=validKeyValues.map(String))}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json.nullable=!0):json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=!1,serialized=JSON.stringify(value,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}var defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);value!==UNREPRESENTABLE_DEFAULT&&(json.default=value)},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);value!==UNREPRESENTABLE_DEFAULT&&(json._prefault=value)},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0};var optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType};function isZ4Schema(s){return!!s._zod}function safeParse2(schema,data){return isZ4Schema(schema)?safeParse(schema,data):schema.safeParse(data)}function getObjectShape(schema){if(!schema)return;let rawShape2;if(isZ4Schema(schema)?rawShape2=schema._zod?.def?.shape:rawShape2=schema.shape,!!rawShape2){if(typeof rawShape2=="function")try{return rawShape2()}catch{return}return rawShape2}}function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value=make(this);return Object.defineProperty(this,key,{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,key,{value,configurable:!0,writable:!0})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self=>mapper=>formatError(self,mapper)),_lazyMethod(proto,"flatten",self=>mapper=>flattenError(self,mapper)),_lazyMethod(proto,"addIssue",self=>issue2=>{self.issues.push(issue2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self=>issues2=>{self.issues.push(...issues2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))};var ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse3=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta2){return reg.add(this,meta2),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value){util_exports.own(this,"~standard",value)},parse:function _parse2(data,params){return parse2(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse3(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){util_exports.own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode2(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode2(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});function _null3(params){return _null2(ZodNull,params)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});function never(params){return _never(ZodNever,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),util_exports.installLazyProp(inst,"shape",self=>self._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});function object2(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output2=>(payload.value=output2,payload)):(payload.value=output,payload)}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date2,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=union([string2(),number2().int()]),CursorSchema=string2(),TaskCreationParamsSchema=looseObject({ttl:union([number2(),_null3()]).optional(),pollInterval:number2().optional()}),TaskMetadataSchema=object2({ttl:number2().optional()}),RelatedTaskMetadataSchema=object2({taskId:string2()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object2({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,RequestSchema=object2({method:string2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object2({_meta:RequestMetaSchema.optional()}),NotificationSchema=object2({method:string2(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string2(),number2().int()]),JSONRPCRequestSchema=object2({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=value=>JSONRPCRequestSchema.safeParse(value).success,JSONRPCNotificationSchema=object2({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=value=>JSONRPCNotificationSchema.safeParse(value).success,JSONRPCResultResponseSchema=object2({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=value=>JSONRPCResultResponseSchema.safeParse(value).success;var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=object2({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object2({code:number2().int(),message:string2(),data:unknown().optional()})}).strict();var isJSONRPCErrorResponse=value=>JSONRPCErrorResponseSchema.safeParse(value).success;var JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object2({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object2({icons:array(IconSchema).optional()}),BaseMetadataSchema=object2({name:string2(),title:string2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema=intersection(object2({applyDefaults:boolean2().optional()}),record(string2(),unknown())),ElicitationCapabilitySchema=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object2({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string2(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object2({experimental:record(string2(),AssertObjectSchema).optional(),sampling:object2({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object2({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=object2({experimental:record(string2(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object2({listChanged:boolean2().optional()}).optional(),resources:object2({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object2({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string2().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object2({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema=object2({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object2({taskId:string2(),status:TaskStatusSchema,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object2({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string2()}),Base64Schema=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object2({audience:array(RoleSchema).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema=object2({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object2({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string2()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object2({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema=object2({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object2({type:literal("text"),text:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema=object2({type:literal("image"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema=object2({type:literal("audio"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema=object2({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema=object2({type:literal("resource"),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object2({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object2({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema=object2({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object2({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string2().optional(),inputSchema:object2({type:literal("object"),properties:record(string2(),AssertObjectSchema).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:object2({type:literal("object"),properties:record(string2(),AssertObjectSchema).optional(),required:array(string2()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string2(),unknown()).optional(),isError:boolean2().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object2({autoRefresh:boolean2().default(!0),debounceMs:number2().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object2({name:string2().optional()}),ModelPreferencesSchema=object2({hints:array(ModelHintSchema).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema=object2({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object2({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema).default([]),structuredContent:object2({}).loose().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object2({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object2({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema=object2({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema=object2({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema=object2({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema=object2({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object2({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema=object2({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object2({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object2({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema=object2({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object2({anyOf:array(object2({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object2({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema),required:array(string2()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema=object2({type:literal("ref/resource"),uri:string2()});var PromptReferenceSchema=object2({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object2({name:string2(),value:string2()}),context:object2({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema});var CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema=object2({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{constructor(code,message,data){super(`MCP error ${code}: ${message}`),this.code=code,this.data=data,this.name="McpError"}static fromError(code,message,data){if(code===ErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code,message,data)}},UrlElicitationRequiredError=class extends McpError{constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function getMethodLiteral(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value!="string")throw new Error("Schema method literal must be a string");return value}function parseWithCompat(schema,data){let result=safeParse2(schema,data);if(!result.success)throw result.error;return result.data}var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,Protocol=class{constructor(_options){this._options=_options,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(CancelledNotificationSchema,notification=>{this._oncancel(notification)}),this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)}),this.setRequestHandler(PingRequestSchema,_request=>({})),this._taskStore=_options?.taskStore,this._taskMessageQueue=_options?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...task}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{let handleTaskResult=async()=>{let taskId=request.params.taskId;if(this._taskMessageQueue){let queuedMessage;for(;queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId);){if(queuedMessage.type==="response"||queuedMessage.type==="error"){let message=queuedMessage.message,requestId=message.id,resolver=this._requestResolvers.get(requestId);if(resolver)if(this._requestResolvers.delete(requestId),queuedMessage.type==="response")resolver(message);else{let errorMessage=message,error2=new McpError(errorMessage.error.code,errorMessage.error.message,errorMessage.error.data);resolver(error2)}else{let messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}let task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(!isTerminal(task.status))return await this._waitForTaskUpdate(taskId,extra.signal),await handleTaskResult();if(isTerminal(task.status)){let result=await this._taskStore.getTaskResult(taskId,extra.sessionId);return this._clearTaskQueue(taskId),{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()};return await handleTaskResult()}),this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{let{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error2){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error2 instanceof Error?error2.message:String(error2)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`);await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId),this._clearTaskQueue(request.params.taskId);let cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`);return{_meta:{},...cancelledTask}}catch(error2){throw error2 instanceof McpError?error2:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error2 instanceof Error?error2.message:String(error2)}`)}}))}async _oncancel(notification){if(!notification.params.requestId)return;this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.(),this._onclose()};let _onerror=this.transport?.onerror;this._transport.onerror=error2=>{_onerror?.(error2),this._onerror(error2)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let controller of this._requestHandlerAbortControllers.values())controller.abort();this._requestHandlerAbortControllers.clear();let error2=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let handler of responseHandlers.values())handler(error2)}_onerror(error2){this.onerror?.(error2)}_onnotification(notification){let handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;handler!==void 0&&Promise.resolve().then(()=>handler(notification)).catch(error2=>this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)))}_onrequest(request,extra){let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler,capturedTransport=this._transport,relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;if(handler===void 0){let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};relatedTaskId&&this._taskMessageQueue?this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error2=>this._onerror(new Error(`Failed to enqueue error response: ${error2}`))):capturedTransport?.send(errorResponse).catch(error2=>this._onerror(new Error(`Failed to send an error response: ${error2}`)));return}let abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0,taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0,fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:async notification=>{if(abortController.signal.aborted)return;let notificationOptions={relatedRequestId:request.id};relatedTaskId&&(notificationOptions.relatedTask={taskId:relatedTaskId}),await this.notification(notification,notificationOptions)},sendRequest:async(r,resultSchema,options)=>{if(abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");let requestOptions={...options,relatedRequestId:request.id};relatedTaskId&&!requestOptions.relatedTask&&(requestOptions.relatedTask={taskId:relatedTaskId});let effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;return effectiveTaskId&&taskStore&&await taskStore.updateTaskStatus(effectiveTaskId,"input_required"),await this.request(r,resultSchema,requestOptions)},authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};Promise.resolve().then(()=>{taskCreationParams&&this.assertTaskHandlerCapability(request.method)}).then(()=>handler(request,fullExtra)).then(async result=>{if(abortController.signal.aborted)return;let response={result,jsonrpc:"2.0",id:request.id};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(response)},async error2=>{if(abortController.signal.aborted)return;let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error2.code)?error2.code:ErrorCode.InternalError,message:error2.message??"Internal error",...error2.data!==void 0&&{data:error2.data}}};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(errorResponse)}).catch(error2=>this._onerror(new Error(`Failed to send response: ${error2}`))).finally(()=>{this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error2){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error2);return}handler(params)}_onresponse(response){let messageId=Number(response.id),resolver=this._requestResolvers.get(messageId);if(resolver){if(this._requestResolvers.delete(messageId),isJSONRPCResultResponse(response))resolver(response);else{let error2=new McpError(response.error.code,response.error.message,response.error.data);resolver(error2)}return}let handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId);let isTaskResponse=!1;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result=="object"){let result=response.result;if(result.task&&typeof result.task=="object"){let task=result.task;typeof task.taskId=="string"&&(isTaskResponse=!0,this._taskProgressTokens.set(task.taskId,messageId))}}if(isTaskResponse||this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response))handler(response);else{let error2=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error2)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){let{task}=options??{};if(!task){try{yield{type:"result",result:await this.request(request,resultSchema,options)}}catch(error2){yield{type:"error",error:error2 instanceof McpError?error2:new McpError(ErrorCode.InternalError,String(error2))}}return}let taskId;try{let createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task)taskId=createResult.task.taskId,yield{type:"taskCreated",task:createResult.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");for(;;){let task2=await this.getTask({taskId},options);if(yield{type:"taskStatus",task:task2},isTerminal(task2.status)){task2.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)}:task2.status==="failed"?yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}:task2.status==="cancelled"&&(yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)});return}if(task2.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};return}let pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve=>setTimeout(resolve,pollInterval)),options?.signal?.throwIfAborted()}}catch(error2){yield{type:"error",error:error2 instanceof McpError?error2:new McpError(ErrorCode.InternalError,String(error2))}}}request(request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve,reject)=>{let earlyReject=error2=>{reject(error2)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method),task&&this.assertTaskCapability(request.method)}catch(e){earlyReject(e);return}options?.signal?.throwIfAborted();let messageId=this._requestMessageId++,jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}}),task&&(jsonrpcRequest.params={...jsonrpcRequest.params,task}),relatedTask&&(jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}});let cancel=reason=>{this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error3=>this._onerror(new Error(`Failed to send cancellation: ${error3}`)));let error2=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error2)};this._responseHandlers.set(messageId,response=>{if(!options?.signal?.aborted){if(response instanceof Error)return reject(response);try{let parseResult=safeParse2(resultSchema,response.result);parseResult.success?resolve(parseResult.data):reject(parseResult.error)}catch(error2){reject(error2)}}}),options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1);let relatedTaskId=relatedTask?.taskId;if(relatedTaskId){let responseResolver=response=>{let handler=this._responseHandlers.get(messageId);handler?handler(response):this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))};this._requestResolvers.set(messageId,responseResolver),this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error2=>{this._cleanupTimeout(messageId),reject(error2)})}else this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error2=>{this._cleanupTimeout(messageId),reject(error2)})})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(notification.method);let relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){let jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;let jsonrpcNotification2={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),this._transport?.send(jsonrpcNotification2,options).catch(error2=>this._onerror(error2))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){let method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method),this._requestHandlers.set(method,(request,extra)=>{let parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(notificationSchema,handler){let method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{let parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){let progressToken=this._taskProgressTokens.get(taskId);progressToken!==void 0&&(this._progressHandlers.delete(progressToken),this._taskProgressTokens.delete(taskId))}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){let messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(let message of messages)if(message.type==="request"&&isJSONRPCRequest(message.message)){let requestId=message.message.id,resolver=this._requestResolvers.get(requestId);resolver?(resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(requestId)):this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}async _waitForTaskUpdate(taskId,signal){let interval=this._options?.defaultTaskPollInterval??1e3;try{let task=await this._taskStore?.getTask(taskId);task?.pollInterval&&(interval=task.pollInterval)}catch{}return new Promise((resolve,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}let timeoutId=setTimeout(resolve,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId),reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(request,sessionId){let taskStore=this._taskStore;if(!taskStore)throw new Error("No task store configured");return{createTask:async taskParams=>{if(!request)throw new Error("No request provided");return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},getTask:async taskId=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return task},storeTaskResult:async(taskId,status,result)=>{await taskStore.storeTaskResult(taskId,status,result,sessionId);let task=await taskStore.getTask(taskId,sessionId);if(task){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification),isTerminal(task.status)&&this._cleanupTaskProgressHandler(taskId)}},getTaskResult:taskId=>taskStore.getTaskResult(taskId,sessionId),updateTaskStatus:async(taskId,status,statusMessage)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await taskStore.updateTaskStatus(taskId,status,statusMessage,sessionId);let updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification),isTerminal(updatedTask.status)&&this._cleanupTaskProgressHandler(taskId)}},listTasks:cursor=>taskStore.listTasks(cursor,sessionId)}}};function isPlainObject2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];isPlainObject2(baseValue)&&isPlainObject2(addValue)?result[k]={...baseValue,...addValue}:result[k]=addValue}return result}var import_ajv=__toESM(require_ajv(),1),import_ajv_formats=__toESM(require_dist(),1);function createDefaultAjvInstance(){let ajv=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_ajv_formats.default)(ajv),ajv}var AjvJsonSchemaValidator=class{constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){let ajvValidator="$id"in schema&&typeof schema.$id=="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}};var ExperimentalServerTasks=class{constructor(_server){this._server=_server}requestStream(request,resultSchema,options){return this._server.requestStream(request,resultSchema,options)}createMessageStream(params,options){let clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id)),toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){let clientCapabilities=this._server.getClientCapabilities(),mode=params.mode??"form";switch(mode){case"url":{if(!clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let normalizedParams=mode==="form"&¶ms.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"tools/call":if(!requests.tools?.call)throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);break;default:break}}function assertClientRequestTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage)throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);break;case"elicitation/create":if(!requests.elicitation?.create)throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);break;default:break}}var Server=class extends Protocol{constructor(_serverInfo,options){super(options),this._serverInfo=_serverInfo,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index)=>[level,index])),this.isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1},this._capabilities=options?.capabilities??{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,request=>this._oninitialize(request)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(request,extra)=>{let transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0,{level}=request.params,parseResult=LoggingLevelSchema.safeParse(level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalServerTasks(this)}),this._experimental}registerCapabilities(capabilities){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let methodValue;if(isZ4Schema(methodSchema)){let v4Schema=methodSchema;methodValue=v4Schema._zod?.def?.value??v4Schema.value}else{let v3Schema=methodSchema;methodValue=v3Schema._def?.value??v3Schema.value}if(typeof methodValue!="string")throw new Error("Schema method literal must be a string");if(methodValue==="tools/call"){let wrappedHandler=async(request,extra)=>{let validatedRequest=safeParse2(CallToolRequestSchema,request);if(!validatedRequest.success){let errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse2(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}let validationResult=safeParse2(CallToolResultSchema,result);if(!validationResult.success){let errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage}`)}return validationResult.data};return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(this._capabilities)switch(method){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${method})`);break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;return this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION,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"},EmptyResultSchema)}async createMessage(params,options){if((params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id)),toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return params.tools?this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options):this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){switch(params.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error2){throw error2 instanceof McpError?error2:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error2 instanceof Error?error2.message:String(error2)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}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"})}};import process2 from"node:process";var ReadBuffer=class{append(chunk){this._buffer=this._buffer?Buffer.concat([this._buffer,chunk]):chunk}readMessage(){if(!this._buffer)return null;let index=this._buffer.indexOf(`
|
|
65
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let entry of ctx.seen.entries()){let seen=entry[1];if(schema===entry[0]){extractToDef(entry);continue}if(ctx.external){let ext=ctx.external.registry.get(entry[0])?.id;if(schema!==entry[0]&&ext){extractToDef(entry);continue}}if(ctx.metadataRegistry.get(entry[0])?.id){extractToDef(entry);continue}if(seen.cycle){extractToDef(entry);continue}seen.count>1&&ctx.reused==="ref"&&extractToDef(entry)}ctx.external&&(ctx.sharedDefsExtractedFor=ctx.external)}function compactTypeUnion(schema){let options=schema.anyOf;if(!Array.isArray(options)||options.length===0||schema.type!==void 0)return;let types=[];for(let option of options){if(!option||typeof option!="object")return;compactTypeUnion(option);let keys=Object.keys(option);if(keys.length!==1||keys[0]!=="type")return;let type=option.type;for(let member of Array.isArray(type)?type:[type]){if(typeof member!="string")return;types.includes(member)||types.push(member)}}delete schema.anyOf,schema.type=types.length===1?types[0]:types}var FOLDABLE_KEYS=new Set(["type","properties","required","additionalProperties"]),UNION_KEYS=["oneOf","anyOf"];function undeclaredConstraint(member){let extra=member.additionalProperties;return extra===void 0||extra===!1||typeof extra!="object"||extra===null?null:Object.keys(extra).length?extra:null}function foldObjects(members2){let objects=[];for(let member of members2){if(typeof member!="object"||member.type!=="object")return null;for(let key in member)if(!FOLDABLE_KEYS.has(key))return null;objects.push(member)}let properties={},required2=new Set;for(let object3 of objects){for(let key in object3.properties){if(Object.prototype.hasOwnProperty.call(properties,key))continue;let parts=[];for(let other of objects){let part=other.properties?.[key]??undeclaredConstraint(other);part!=null&&(parts.some(seen=>JSON.stringify(seen)===JSON.stringify(part))||parts.push(part))}let merged=parts.length===1?parts[0]:foldObjects(parts)??{allOf:parts};assignProp(properties,key,merged)}for(let key of object3.required??[])required2.add(key)}let folded={type:"object",properties};if(required2.size&&(folded.required=[...required2]),objects.every(object3=>object3.additionalProperties===!1))folded.additionalProperties=!1;else{let constraints=[];for(let object3 of objects){let constraint=undeclaredConstraint(object3);constraint&&!constraints.some(seen=>JSON.stringify(seen)===JSON.stringify(constraint))&&constraints.push(constraint)}constraints.length===1?folded.additionalProperties=constraints[0]:constraints.length>1&&(folded.additionalProperties={allOf:constraints})}return folded}function foldIntersection(json){let allOf=json.allOf;if(!Array.isArray(allOf)||allOf.length<2)return;for(let key of FOLDABLE_KEYS)if(key in json)return;let unions=allOf.filter(m=>UNION_KEYS.some(k=>Array.isArray(m[k]))),folded=null;if(!unions.length)folded=foldObjects(allOf);else{let union2=unions[0],keyword=UNION_KEYS.find(k=>Array.isArray(union2[k]));if(Object.keys(union2).length!==1)return;let rest=allOf.filter(m=>m!==union2),branches=union2[keyword].map(branch=>foldObjects([...rest,branch]));if(branches.some(b=>!b))return;folded={[keyword]:branches}}folded&&(delete json.allOf,assignProps(json,folded))}function finalize(ctx,schema){let root=ctx.seen.get(schema);if(!root)throw new Error("Unprocessed schema. This is a bug in Zod.");let flattenRef=zodSchema=>{let seen=ctx.seen.get(zodSchema);if(seen.ref===null)return;let schema2=seen.def??seen.schema,_cached={...schema2},ref=seen.ref;if(seen.ref=null,ref){flattenRef(ref);let refSeen=ctx.seen.get(ref),refSchema=refSeen.schema;if(refSchema.$ref&&(ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0")?(schema2.allOf=schema2.allOf??[],schema2.allOf.push(refSchema)):assignProps(schema2,refSchema),assignProps(schema2,_cached),zodSchema._zod.parent===ref)for(let key in schema2)key==="$ref"||key==="allOf"||key in _cached||delete schema2[key];if(refSchema.$ref&&refSeen.def)for(let key in schema2)key==="$ref"||key==="allOf"||key in refSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(refSeen.def[key])&&delete schema2[key]}let parent=zodSchema._zod.parent;if(parent&&parent!==ref){flattenRef(parent);let parentSeen=ctx.seen.get(parent);if(parentSeen?.schema.$ref&&(schema2.$ref=parentSeen.schema.$ref,parentSeen.def))for(let key in schema2)key==="$ref"||key==="allOf"||key in parentSeen.def&&JSON.stringify(schema2[key])===JSON.stringify(parentSeen.def[key])&&delete schema2[key]}ctx.override({zodSchema,jsonSchema:schema2,path:seen.path??[]})};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external){for(let entry of[...ctx.seen.entries()].reverse())flattenRef(entry[0]);if(ctx.target!=="openapi-3.0")for(let entry of ctx.seen.entries())compactTypeUnion(entry[1].def??entry[1].schema);for(let rewrite of ctx.deferred)rewrite();if(ctx.intersections.length){let carriers=new Map;for(let seen of ctx.seen.values())for(let json of[seen.schema,seen.def]){let allOf=json?.allOf;if(!Array.isArray(allOf))continue;let existing=carriers.get(allOf);existing?existing.push(json):carriers.set(allOf,[json])}for(let allOf of ctx.intersections)for(let json of carriers.get(allOf)??[])foldIntersection(json)}}let result={};if(ctx.target==="draft-2020-12"?result.$schema="https://json-schema.org/draft/2020-12/schema":ctx.target==="draft-07"?result.$schema="http://json-schema.org/draft-07/schema#":ctx.target==="draft-04"?result.$schema="http://json-schema.org/draft-04/schema#":ctx.target,ctx.external?.uri){let id=ctx.external.registry.get(schema)?.id;if(!id)throw new Error("Schema is missing an `id` property");result.$id=ctx.external.uri(id)}assignProps(result,root.defId?root.schema:root.def??root.schema);let rootMetaId=ctx.metadataRegistry.get(schema)?.id;rootMetaId!==void 0&&result.id===rootMetaId&&delete result.id;let defs=ctx.external?.defs??{};if(!ctx.external||ctx.sharedEmitDoneFor!==ctx.external)for(let entry of ctx.seen.entries()){let seen=entry[1];seen.def&&seen.defId&&(seen.def.id===seen.defId&&delete seen.def.id,assignProp(defs,seen.defId,seen.def))}ctx.external&&(ctx.sharedEmitDoneFor=ctx.external),ctx.external||Object.keys(defs).length>0&&(ctx.target==="draft-2020-12"?result.$defs=defs:result.definitions=defs);try{let finalized=JSON.parse(JSON.stringify(result));return Object.defineProperty(finalized,"~standard",{value:{...schema["~standard"],jsonSchema:{input:createStandardJSONSchemaMethod(schema,"input",ctx.processors),output:createStandardJSONSchemaMethod(schema,"output",ctx.processors)}},enumerable:!1,writable:!1}),finalized}catch{throw new Error("Error converting schema to JSON.")}}function isTransforming(_schema,_ctx){let ctx=_ctx??{seen:new Set};if(ctx.seen.has(_schema))return!1;ctx.seen.add(_schema);let def=_schema._zod.def;if(def.type==="transform")return!0;if(def.type==="array")return isTransforming(def.element,ctx);if(def.type==="set")return isTransforming(def.valueType,ctx);if(def.type==="lazy")return isTransforming(def.getter(),ctx);if(def.type==="promise"||def.type==="optional"||def.type==="nonoptional"||def.type==="nullable"||def.type==="readonly"||def.type==="default"||def.type==="prefault"||def.type==="catch")return isTransforming(def.innerType,ctx);if(def.type==="intersection")return isTransforming(def.left,ctx)||isTransforming(def.right,ctx);if(def.type==="record"||def.type==="map")return isTransforming(def.keyType,ctx)||isTransforming(def.valueType,ctx);if(def.type==="pipe")return _schema._zod.traits.has("$ZodCodec")?!0:isTransforming(def.in,ctx)||isTransforming(def.out,ctx);if(def.type==="object"){for(let key in def.shape)if(isTransforming(def.shape[key],ctx))return!0;return!1}if(def.type==="union"){for(let option of def.options)if(isTransforming(option,ctx))return!0;return!1}if(def.type==="tuple"){for(let item of def.items)if(isTransforming(item,ctx))return!0;return!!(def.rest&&isTransforming(def.rest,ctx))}return!1}var createToJSONSchemaMethod=(schema,processors={})=>params=>{let ctx=initializeContext({...params,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)},createStandardJSONSchemaMethod=(schema,io,processors={})=>params=>{let{libraryOptions,target}=params??{},ctx=initializeContext({...libraryOptions??{},target,io,processors});return processSchema(schema,ctx),extractDefs(ctx,schema),finalize(ctx,schema)};var narrowMin=(agg,key,value)=>{(agg[key]===void 0||value>agg[key])&&(agg[key]=value)},narrowMax=(agg,key,value)=>{(agg[key]===void 0||value<agg[key])&&(agg[key]=value)},narrowBoth=(agg,value)=>{narrowMin(agg,"minimum",value),narrowMax(agg,"maximum",value)},addDivisor=(agg,value)=>{agg.multipleOf??(agg.multipleOf=[]),agg.multipleOf.includes(value)||agg.multipleOf.push(value)},addPattern=(agg,pattern)=>{agg.patterns??(agg.patterns=new Set),agg.patterns.add(pattern)},intersectMime=(agg,mime)=>{agg.mime=agg.mime?agg.mime.filter(m=>mime.includes(m)):[...mime]},setFormat=(agg,format)=>{agg.format=format,format.includes("int")&&(agg.isInt=!0)},minContributor=(agg,def)=>narrowMin(agg,"minimum",def.minimum),maxContributor=(agg,def)=>narrowMax(agg,"maximum",def.maximum),formatContributor=ranges=>(agg,def)=>{setFormat(agg,def.format);let[minimum,maximum]=ranges[def.format];narrowMin(agg,"minimum",minimum),narrowMax(agg,"maximum",maximum)},contributors={greater_than:(agg,def)=>narrowMin(agg,def.inclusive?"minimum":"exclusiveMinimum",def.value),less_than:(agg,def)=>narrowMax(agg,def.inclusive?"maximum":"exclusiveMaximum",def.value),multiple_of:(agg,def)=>addDivisor(agg,def.value),number_format:formatContributor(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),min_length:minContributor,max_length:maxContributor,length_equals:(agg,def)=>narrowBoth(agg,def.length),min_size:minContributor,max_size:maxContributor,size_equals:(agg,def)=>narrowBoth(agg,def.size),string_format:(agg,def)=>{setFormat(agg,def.format),def.pattern&&addPattern(agg,def.pattern),(def.format==="base64"||def.format==="base64url")&&(agg.contentEncoding=def.format),(def.local||def.precision===-1)&&(agg.laxFormat=!0)},mime_type:(agg,def)=>intersectMime(agg,def.mime)};function aggregateChecks(schema){let agg={},def=schema._zod.def,list=schema._zod.traits.has("$ZodCheck")?[schema,...def.checks??[]]:def.checks??[];for(let ch of list)contributors[ch._zod.def.check]?.(agg,ch._zod.def);let bag=schema._zod.bag;bag.minimum!==void 0&&narrowMin(agg,"minimum",bag.minimum),bag.exclusiveMinimum!==void 0&&narrowMin(agg,"exclusiveMinimum",bag.exclusiveMinimum),bag.maximum!==void 0&&narrowMax(agg,"maximum",bag.maximum),bag.exclusiveMaximum!==void 0&&narrowMax(agg,"exclusiveMaximum",bag.exclusiveMaximum),bag.multipleOf!==void 0&&addDivisor(agg,bag.multipleOf),bag.format!==void 0&&(agg.format??(agg.format=bag.format),bag.format.includes("int")&&(agg.isInt=!0)),bag.mime&&intersectMime(agg,bag.mime);for(let pattern of bag.patterns??[])addPattern(agg,pattern);return agg}var formatMap={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},exactPatterns=new Map([[base64Charset,base64],[base64urlCharset,base64url]]),exactPattern=p=>exactPatterns.get(p)??p,stringProcessor=(schema,ctx,_json,_params)=>{let json=_json;json.type="string";let{minimum,maximum,format,patterns,contentEncoding,laxFormat}=aggregateChecks(schema);if(typeof minimum=="number"&&(json.minLength=minimum),typeof maximum=="number"&&(json.maxLength=maximum),format&&(json.format=formatMap[format]??format,json.format===""&&delete json.format,(format==="time"||laxFormat)&&delete json.format),contentEncoding&&(json.contentEncoding=contentEncoding),patterns&&patterns.size>0){let patternList=[...patterns].map(exactPattern);patternList.length===1?json.pattern=patternList[0].source:patternList.length>1&&(json.allOf=[...patternList.map(regex=>({...ctx.target==="draft-07"||ctx.target==="draft-04"||ctx.target==="openapi-3.0"?{type:"string"}:{},pattern:regex.source}))])}},numberProcessor=(schema,ctx,_json,params)=>{let json=_json,{minimum,maximum,multipleOf,exclusiveMaximum,exclusiveMinimum,isInt}=aggregateChecks(schema);json.type=isInt?"integer":"number";let exMin=typeof exclusiveMinimum=="number"&&exclusiveMinimum>=(minimum??Number.NEGATIVE_INFINITY),exMax=typeof exclusiveMaximum=="number"&&exclusiveMaximum<=(maximum??Number.POSITIVE_INFINITY),legacy=ctx.target==="draft-04"||ctx.target==="openapi-3.0";if(exMin?legacy?(json.minimum=exclusiveMinimum,json.exclusiveMinimum=!0):json.exclusiveMinimum=exclusiveMinimum:typeof minimum=="number"&&(json.minimum=minimum),exMax?legacy?(json.maximum=exclusiveMaximum,json.exclusiveMaximum=!0):json.exclusiveMaximum=exclusiveMaximum:typeof maximum=="number"&&(json.maximum=maximum),multipleOf){let divisors=new Set;for(let divisor of multipleOf)Number.isFinite(divisor)&&divisor!==0?divisors.add(Math.abs(divisor)):handleUnrepresentable(schema,ctx,json,params,`A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);let[first,...rest]=divisors;first!==void 0&&(json.multipleOf=first),rest.length&&(json.allOf=[...json.allOf??[],...rest.map(m=>({multipleOf:m}))])}},booleanProcessor=(_schema,_ctx,json,_params)=>{json.type="boolean"};var nullProcessor=(_schema,ctx,json,_params)=>{ctx.target==="openapi-3.0"?(json.type="string",json.nullable=!0,json.enum=[null]):json.type="null"};var neverProcessor=(_schema,_ctx,json,_params)=>{json.not={}};var unknownProcessor=(_schema,_ctx,_json,_params)=>{};var enumProcessor=(schema,_ctx,json,_params)=>{let def=schema._zod.def,values=getEnumValues(def.entries);if(values.length===0){json.not={};return}values.every(v=>typeof v=="number")&&(json.type="number"),values.every(v=>typeof v=="string")&&(json.type="string"),json.enum=values},literalProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;if(def.values.length===0){json.not={};return}let vals=[];for(let val of def.values)if(val===void 0){if(handleUnrepresentable(schema,ctx,json,params,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof val=="bigint"){if(handleUnrepresentable(schema,ctx,json,params,"BigInt literals cannot be represented in JSON Schema"))return;vals.push(Number(val))}else vals.push(val);if(vals.length!==0)if(vals.length===1){let val=vals[0];json.type=val===null?"null":typeof val,ctx.target==="draft-04"||ctx.target==="openapi-3.0"?json.enum=[val]:json.const=val}else vals.every(v=>typeof v=="number")&&(json.type="number"),vals.every(v=>typeof v=="string")&&(json.type="string"),vals.every(v=>typeof v=="boolean")&&(json.type="boolean"),vals.every(v=>v===null)&&(json.type="null"),json.enum=vals};var customProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Custom types cannot be represented in JSON Schema")};var transformProcessor=(schema,ctx,json,params)=>{handleUnrepresentable(schema,ctx,json,params,"Transforms cannot be represented in JSON Schema")};var arrayProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,{minimum,maximum}=aggregateChecks(schema);typeof minimum=="number"&&(json.minItems=minimum),typeof maximum=="number"&&(json.maxItems=maximum),json.type="array",json.items=processSchema(def.element,ctx,{...params,path:[...params.path,"items"]})};function inputOptin(schema){let def=schema._zod.def;return def.type==="pipe"&&def.in._zod.traits.has("$ZodTransform")?inputOptin(def.out):def.type==="catch"?inputOptin(def.innerType):schema._zod.optin}var objectProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def,shape=def.shape;if(Object.getOwnPropertySymbols(shape).length&&handleUnrepresentable(schema,ctx,json,params,"Symbol keys cannot be represented in JSON Schema"))return;json.type="object",json.properties={};for(let key in shape)assignProp(json.properties,key,processSchema(shape[key],ctx,{...params,path:[...params.path,"properties",key]}));let requiredKeys=[];for(let key of Object.keys(shape)){let field=def.shape[key];(ctx.io==="input"?inputOptin(field)===void 0:field._zod.optout===void 0)&&requiredKeys.push(key)}requiredKeys.length>0&&(json.required=requiredKeys),def.catchall?._zod.def.type==="never"?json.additionalProperties=!1:def.catchall?def.catchall&&(json.additionalProperties=processSchema(def.catchall,ctx,{...params,path:[...params.path,"additionalProperties"]})):ctx.io==="output"&&(json.additionalProperties=!1)},unionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,isExclusive=def.inclusive===!1,options=def.options.map((x,i)=>processSchema(x,ctx,{...params,path:[...params.path,isExclusive?"oneOf":"anyOf",i]}));isExclusive?json.oneOf=options:json.anyOf=options},intersectionProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,a=processSchema(def.left,ctx,{...params,path:[...params.path,"allOf",0]}),b=processSchema(def.right,ctx,{...params,path:[...params.path,"allOf",1]}),isSimpleIntersection=val=>"allOf"in val&&Object.keys(val).length===1,allOf=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(b)?b.allOf:[b]];json.allOf=allOf,ctx.intersections.push(allOf)};function stringifyKeyNames(bySchema,json,visited){if(json.$ref){if(visited.has(json))return json;visited.add(json);let def=bySchema.get(json)?.def;if(!def)return json;let inlined=stringifyKeyNames(bySchema,def,visited);return inlined===def?json:inlined}for(let keyword of["anyOf","oneOf"]){let branches=json[keyword];if(!Array.isArray(branches))continue;let mapped=branches.map(branch=>stringifyKeyNames(bySchema,branch,visited));mapped.some((branch,i)=>branch!==branches[i])&&(json={...json,[keyword]:mapped})}let types=Array.isArray(json.type)?json.type:[json.type],numericType=!types.includes("string")&&types.some(t=>t==="number"||t==="integer"),values=json.enum??(json.const!==void 0?[json.const]:void 0);if(!numericType&&!values?.some(v=>typeof v=="number"))return json;let{minimum,maximum,exclusiveMinimum,exclusiveMaximum,multipleOf,format,id,...rest}=json;return rest.enum?rest.enum=rest.enum.map(v=>typeof v=="number"?String(v):v):typeof rest.const=="number"&&(rest.const=String(rest.const)),numericType&&(rest.type="string",values||(rest.pattern=(types.includes("number")?number:integer).source)),rest}var pendingRecords=new WeakMap;function rewriteKeyNames(ctx){let bySchema=new Map;for(let entry of ctx.seen.values())entry.def&&!bySchema.has(entry.schema)&&bySchema.set(entry.schema,entry);let rewrites=new Map;for(let record2 of pendingRecords.get(ctx)??[]){let seen=ctx.seen.get(record2),names=(seen?.def??seen?.schema)?.propertyNames;if(!names||names===!0||rewrites.has(names))continue;let rewritten=stringifyKeyNames(bySchema,names,new Set);rewritten!==names&&rewrites.set(names,rewritten)}if(rewrites.size)for(let entry of ctx.seen.values())for(let carrier of[entry.schema,entry.def]){let rewritten=carrier&&rewrites.get(carrier.propertyNames);rewritten&&(carrier.propertyNames=rewritten)}}var recordProcessor=(schema,ctx,_json,params)=>{let json=_json,def=schema._zod.def;json.type="object";let keyType=def.keyType,patterns=aggregateChecks(keyType).patterns;if(def.mode==="loose"&&patterns&&patterns.size>0){let valueSchema=processSchema(def.valueType,ctx,{...params,path:[...params.path,"patternProperties","*"]});json.patternProperties={};for(let pattern of patterns)assignProp(json.patternProperties,exactPattern(pattern).source,valueSchema)}else{if(ctx.target==="draft-07"||ctx.target==="draft-2020-12"){json.propertyNames=processSchema(def.keyType,ctx,{...params,path:[...params.path,"propertyNames"]});let pending=pendingRecords.get(ctx);pending||(pending=[],pendingRecords.set(ctx,pending),ctx.deferred.push(()=>rewriteKeyNames(ctx))),pending.push(schema)}json.additionalProperties=processSchema(def.valueType,ctx,{...params,path:[...params.path,"additionalProperties"]})}let keyValues=keyType._zod.values,omittableOnInput=ctx.io==="input"&&inputOptin(def.valueType)!==void 0;if(keyValues&&!def.partial&&!omittableOnInput){let validKeyValues=[...keyValues].filter(v=>typeof v=="string"||typeof v=="number");validKeyValues.length>0&&(json.required=validKeyValues.map(String))}},nullableProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def,inner=processSchema(def.innerType,ctx,params),seen=ctx.seen.get(schema);ctx.target==="openapi-3.0"?(seen.ref=def.innerType,json.nullable=!0):json.anyOf=[inner,{type:"null"}]},nonoptionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType},UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(value,schema,ctx,json,params){let unrepresentable=!1,serialized=JSON.stringify(value,(_,val)=>typeof val!="bigint"?val:(unrepresentable=!0,null));return unrepresentable?(handleUnrepresentable(schema,ctx,json,params,"BigInt defaults cannot be represented in JSON Schema"),UNREPRESENTABLE_DEFAULT):JSON.parse(serialized)}var defaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);value!==UNREPRESENTABLE_DEFAULT&&(json.default=value)},prefaultProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);if(seen.ref=def.innerType,ctx.io!=="input")return;let value=serializeDefaultValue(def.defaultValue,schema,ctx,json,params);value!==UNREPRESENTABLE_DEFAULT&&(json._prefault=value)},catchProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType;let catchValue;try{catchValue=def.catchValue(void 0)}catch{handleUnrepresentable(schema,ctx,json,params,"Dynamic catch values are not supported in JSON Schema");return}json.default=catchValue},pipeProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def,inIsTransform=def.in._zod.traits.has("$ZodTransform"),innerType=ctx.io==="input"?inIsTransform?def.out:def.in:def.out;processSchema(innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=innerType},readonlyProcessor=(schema,ctx,json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType,json.readOnly=!0};var optionalProcessor=(schema,ctx,_json,params)=>{let def=schema._zod.def;processSchema(def.innerType,ctx,params);let seen=ctx.seen.get(schema);seen.ref=def.innerType};function isZ4Schema(s){return!!s._zod}function safeParse2(schema,data){return isZ4Schema(schema)?safeParse(schema,data):schema.safeParse(data)}function getObjectShape(schema){if(!schema)return;let rawShape2;if(isZ4Schema(schema)?rawShape2=schema._zod?.def?.shape:rawShape2=schema.shape,!!rawShape2){if(typeof rawShape2=="function")try{return rawShape2()}catch{return}return rawShape2}}function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}var _installedErrorProtos=new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(proto,key,make){Object.defineProperty(proto,key,{configurable:!0,enumerable:!1,get(){let value=make(this);return Object.defineProperty(this,key,{value,configurable:!0,writable:!0}),value},set(value){Object.defineProperty(this,key,{value,configurable:!0,writable:!0})}})}var initializer2=(inst,issues)=>{$ZodError.init(inst,issues),inst.name="ZodError";let proto=Object.getPrototypeOf(inst);_installedErrorProtos.has(proto)||(_installedErrorProtos.add(proto),_lazyMethod(proto,"format",self=>mapper=>formatError(self,mapper)),_lazyMethod(proto,"flatten",self=>mapper=>flattenError(self,mapper)),_lazyMethod(proto,"addIssue",self=>issue2=>{self.issues.push(issue2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),_lazyMethod(proto,"addIssues",self=>issues2=>{self.issues.push(...issues2),self.message=JSON.stringify(self.issues,jsonStringifyReplacer,2)}),Object.defineProperty(proto,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))};var ZodRealError=$constructor("ZodError",initializer2,void 0,{Parent:Error});var parse2=_parse(ZodRealError),parseAsync2=_parseAsync(ZodRealError),safeParse3=_safeParse(ZodRealError),safeParseAsync2=_safeParseAsync(ZodRealError),encode2=_encode(ZodRealError),decode2=_decode(ZodRealError),encodeAsync2=_encodeAsync(ZodRealError),decodeAsync2=_decodeAsync(ZodRealError),safeEncode2=_safeEncode(ZodRealError),safeDecode2=_safeDecode(ZodRealError),safeEncodeAsync2=_safeEncodeAsync(ZodRealError),safeDecodeAsync2=_safeDecodeAsync(ZodRealError);function _ensureDefaultLocale(){globalConfig.localeError||config(en_default())}function _ensureDefaultMemoizer(){globalConfig.memoizer||config({memoizer:memoizer()})}var ZodType=$constructor("ZodType",(inst,def)=>(_ensureDefaultLocale(),$ZodType.init(inst,def),inst.def=def,inst.type=def.type,inst),{check(...chks){let def=this.def;return this.clone(util_exports.mergeDefs(def,{checks:[...def.checks??[],...chks.map(ch=>typeof ch=="function"?{_zod:{check:ch,def:{check:"custom"},onattach:[]}}:ch)]}),{parent:!0})},with(...chks){return this.check(...chks)},clone(def,params){return clone(this,def,params)},brand(){return this},register(reg,meta2){return reg.add(this,meta2),this},refine(check,params){return this.check(refine(check,params))},superRefine(refinement,params){return this.check(superRefine(refinement,params))},overwrite(fn){return this.check(_overwrite(fn))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(params){return nonoptional(this,params)},array(){return array(this)},or(arg){return union([this,arg])},and(arg){return intersection(this,arg)},transform(tx){return pipe(this,transform(tx))},default(d){return _default(this,d)},prefault(d){return prefault(this,d)},catch(params){return _catch(this,params)},pipe(target){return pipe(this,target)},readonly(){return readonly(this)},describe(description){let cl=this.clone();return globalRegistry.add(cl,{description}),cl},meta(...args){if(args.length===0)return globalRegistry.get(this);let cl=this.clone();return globalRegistry.add(cl,args[0]),cl},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(fn,...args){return args.length===0?fn(this):fn(this,...args)},get"~standard"(){return util_exports.hide(this,"~standard",{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,"input"),output:createStandardJSONSchemaMethod(this,"output")}})},set"~standard"(value){util_exports.own(this,"~standard",value)},parse:function _parse2(data,params){return parse2(this,data,params,{callee:_parse2})},parseAsync:async function _parseAsync2(data,params){return await parseAsync2(this,data,params,{callee:_parseAsync2})},safeParse(data,params){return safeParse3(this,data,params)},async safeParseAsync(data,params){return safeParseAsync2(this,data,params)},get spa(){return this?.safeParseAsync},set spa(value){util_exports.own(this,"spa",value)},validate(data,params){return validate(this,data,params)},validateAsync(data,params){return validateAsync(this,data,params)},encode:function _encode2(data,params){return encode2(this,data,params,{callee:_encode2})},decode:function _decode2(data,params){return decode2(this,data,params,{callee:_decode2})},encodeAsync:async function _encodeAsync2(data,params){return await encodeAsync2(this,data,params,{callee:_encodeAsync2})},decodeAsync:async function _decodeAsync2(data,params){return await decodeAsync2(this,data,params,{callee:_decodeAsync2})},safeEncode(data,params){return safeEncode2(this,data,params)},safeDecode(data,params){return safeDecode2(this,data,params)},async safeEncodeAsync(data,params){return safeEncodeAsync2(this,data,params)},async safeDecodeAsync(data,params){return safeDecodeAsync2(this,data,params)},toJSONSchema(params){return createToJSONSchemaMethod(this,{})(params)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}}),_ZodString=$constructor("_ZodString",(inst,def)=>{$ZodString.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>stringProcessor(inst,ctx,json,params)},util_exports.derived({format:inst=>aggregateChecks(inst).format??null,minLength:inst=>aggregateChecks(inst).minimum??null,maxLength:inst=>aggregateChecks(inst).maximum??null},{regex(...args){return this.check(_regex(...args))},includes(...args){return this.check(_includes(...args))},startsWith(...args){return this.check(_startsWith(...args))},endsWith(...args){return this.check(_endsWith(...args))},min(...args){return this.check(_minLength(...args))},max(...args){return this.check(_maxLength(...args))},length(...args){return this.check(_length(...args))},nonempty(...args){return this.check(_minLength(1,...args))},lowercase(params){return this.check(_lowercase(params))},uppercase(params){return this.check(_uppercase(params))},trim(){return this.check(_trim())},normalize(...args){return this.check(_normalize(...args))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}})),ZodString=$constructor("ZodString",(inst,def)=>{$ZodString.init(inst,def),_ZodString.init(inst,def)},{email(params){return this.check(_email(ZodEmail,params))},url(params){return this.check(_url(ZodURL,params))},jwt(params){return this.check(_jwt(ZodJWT,params))},emoji(params){return this.check(_emoji2(ZodEmoji,params))},guid(params){return this.check(_guid(ZodGUID,params))},uuid(params){return this.check(_uuid(ZodUUID,params))},uuidv4(params){return this.check(_uuidv4(ZodUUID,params))},uuidv6(params){return this.check(_uuidv6(ZodUUID,params))},uuidv7(params){return this.check(_uuidv7(ZodUUID,params))},nanoid(params){return this.check(_nanoid(ZodNanoID,params))},cuid(params){return this.check(_cuid(ZodCUID,params))},cuid2(params){return this.check(_cuid2(ZodCUID2,params))},ulid(params){return this.check(_ulid(ZodULID,params))},base64(params){return this.check(_base64(ZodBase64,params))},base64url(params){return this.check(_base64url(ZodBase64URL,params))},xid(params){return this.check(_xid(ZodXID,params))},ksuid(params){return this.check(_ksuid(ZodKSUID,params))},ipv4(params){return this.check(_ipv4(ZodIPv4,params))},ipv6(params){return this.check(_ipv6(ZodIPv6,params))},cidrv4(params){return this.check(_cidrv4(ZodCIDRv4,params))},cidrv6(params){return this.check(_cidrv6(ZodCIDRv6,params))},e164(params){return this.check(_e164(ZodE164,params))},datetime(params){return this.check(_isoDateTime(ZodISODateTime,params))},date(params){return this.check(_isoDate(ZodISODate,params))},time(params){return this.check(_isoTime(ZodISOTime,params))},duration(params){return this.check(_isoDuration(ZodISODuration,params))}});function string2(params){return _string(ZodString,params)}var ZodStringFormat=$constructor("ZodStringFormat",(inst,def)=>{$ZodStringFormat.init(inst,def),_ZodString.init(inst,def)}),ZodISODateTime=$constructor("ZodISODateTime",(inst,def)=>{$ZodISODateTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODate=$constructor("ZodISODate",(inst,def)=>{$ZodISODate.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISOTime=$constructor("ZodISOTime",(inst,def)=>{$ZodISOTime.init(inst,def),ZodStringFormat.init(inst,def)}),ZodISODuration=$constructor("ZodISODuration",(inst,def)=>{$ZodISODuration.init(inst,def),ZodStringFormat.init(inst,def)}),ZodEmail=$constructor("ZodEmail",(inst,def)=>{$ZodEmail.init(inst,def),ZodStringFormat.init(inst,def)});var ZodGUID=$constructor("ZodGUID",(inst,def)=>{$ZodGUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodUUID=$constructor("ZodUUID",(inst,def)=>{$ZodUUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodURL=$constructor("ZodURL",(inst,def)=>{$ZodURL.init(inst,def),ZodStringFormat.init(inst,def)});var ZodEmoji=$constructor("ZodEmoji",(inst,def)=>{$ZodEmoji.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNanoID=$constructor("ZodNanoID",(inst,def)=>{$ZodNanoID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID=$constructor("ZodCUID",(inst,def)=>{$ZodCUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCUID2=$constructor("ZodCUID2",(inst,def)=>{$ZodCUID2.init(inst,def),ZodStringFormat.init(inst,def)});var ZodULID=$constructor("ZodULID",(inst,def)=>{$ZodULID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodXID=$constructor("ZodXID",(inst,def)=>{$ZodXID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodKSUID=$constructor("ZodKSUID",(inst,def)=>{$ZodKSUID.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv4=$constructor("ZodIPv4",(inst,def)=>{$ZodIPv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodIPv6=$constructor("ZodIPv6",(inst,def)=>{$ZodIPv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv4=$constructor("ZodCIDRv4",(inst,def)=>{$ZodCIDRv4.init(inst,def),ZodStringFormat.init(inst,def)});var ZodCIDRv6=$constructor("ZodCIDRv6",(inst,def)=>{$ZodCIDRv6.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64=$constructor("ZodBase64",(inst,def)=>{$ZodBase64.init(inst,def),ZodStringFormat.init(inst,def)});var ZodBase64URL=$constructor("ZodBase64URL",(inst,def)=>{$ZodBase64URL.init(inst,def),ZodStringFormat.init(inst,def)});var ZodE164=$constructor("ZodE164",(inst,def)=>{$ZodE164.init(inst,def),ZodStringFormat.init(inst,def)});var ZodJWT=$constructor("ZodJWT",(inst,def)=>{$ZodJWT.init(inst,def),ZodStringFormat.init(inst,def)});var ZodNumber=$constructor("ZodNumber",(inst,def)=>{$ZodNumber.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>numberProcessor(inst,ctx,json,params),inst.isFinite=!0},util_exports.derived({minValue:inst=>{let{minimum,exclusiveMinimum}=aggregateChecks(inst);return Math.max(minimum??Number.NEGATIVE_INFINITY,exclusiveMinimum??Number.NEGATIVE_INFINITY)},maxValue:inst=>{let{maximum,exclusiveMaximum}=aggregateChecks(inst);return Math.min(maximum??Number.POSITIVE_INFINITY,exclusiveMaximum??Number.POSITIVE_INFINITY)},isInt:inst=>{let{isInt,multipleOf}=aggregateChecks(inst);return!!isInt||!!multipleOf?.some(Number.isSafeInteger)},format:inst=>aggregateChecks(inst).format??null},{gt(value,params){return this.check(_gt(value,params))},gte(value,params){return this.check(_gte(value,params))},min(value,params){return this.check(_gte(value,params))},lt(value,params){return this.check(_lt(value,params))},lte(value,params){return this.check(_lte(value,params))},max(value,params){return this.check(_lte(value,params))},int(params){return this.check(int(params))},safe(params){return this.check(int(params))},positive(params){return this.check(_gt(0,params))},nonnegative(params){return this.check(_gte(0,params))},negative(params){return this.check(_lt(0,params))},nonpositive(params){return this.check(_lte(0,params))},multipleOf(value,params){return this.check(_multipleOf(value,params))},step(value,params){return this.check(_multipleOf(value,params))},finite(){return this}}));function number2(params){return _number(ZodNumber,params)}var ZodNumberFormat=$constructor("ZodNumberFormat",(inst,def)=>{$ZodNumberFormat.init(inst,def),ZodNumber.init(inst,def)});function int(params){return _int(ZodNumberFormat,params)}var ZodBoolean=$constructor("ZodBoolean",(inst,def)=>{$ZodBoolean.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>booleanProcessor(inst,ctx,json,params)});function boolean2(params){return _boolean(ZodBoolean,params)}var ZodNull=$constructor("ZodNull",(inst,def)=>{$ZodNull.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullProcessor(inst,ctx,json,params)});function _null3(params){return _null2(ZodNull,params)}var ZodUnknown=$constructor("ZodUnknown",(inst,def)=>{$ZodUnknown.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unknownProcessor(inst,ctx,json,params)});function unknown(){return _unknown(ZodUnknown)}var ZodNever=$constructor("ZodNever",(inst,def)=>{$ZodNever.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>neverProcessor(inst,ctx,json,params)});function never(params){return _never(ZodNever,params)}var ZodArray=$constructor("ZodArray",(inst,def)=>{_ensureDefaultMemoizer(),$ZodArray.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>arrayProcessor(inst,ctx,json,params),inst.element=def.element},{min(n,params){return this.check(_minLength(n,params))},nonempty(params){return this.check(_minLength(1,params))},max(n,params){return this.check(_maxLength(n,params))},length(n,params){return this.check(_length(n,params))},unwrap(){return this.element}});function array(element,params){return _array(ZodArray,element,params)}var ZodObject=$constructor("ZodObject",(inst,def)=>{_ensureDefaultMemoizer(),$ZodObjectJIT.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>objectProcessor(inst,ctx,json,params),util_exports.installLazyProp(inst,"shape",self=>self._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(catchall){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall}))},passthrough(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(util_exports.mergeDefs(this._zod.def,{catchall:void 0}))},extend(incoming){return util_exports.extend(this,incoming)},safeExtend(incoming){return util_exports.safeExtend(this,incoming)},merge(other){return util_exports.merge(this,other)},pick(mask){return util_exports.pick(this,mask)},omit(mask){return util_exports.omit(this,mask)},partial(...args){return util_exports.partial(ZodOptional,this,args[0])},exactPartial(...args){return util_exports.partial(ZodExactOptional,this,args[0],"exactPartial")},required(...args){return util_exports.required(ZodNonOptional,this,args[0])}});function object2(shape,params){let def={type:"object",shape:shape??{},...util_exports.normalizeParams(params)};return new ZodObject(def)}function looseObject(shape,params){return new ZodObject({type:"object",shape,catchall:unknown(),...util_exports.normalizeParams(params)})}var ZodUnion=$constructor("ZodUnion",(inst,def)=>{$ZodUnion.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>unionProcessor(inst,ctx,json,params),inst.options=def.options});function union(options,params){return new ZodUnion({type:"union",options,...util_exports.normalizeParams(params)})}var ZodDiscriminatedUnion=$constructor("ZodDiscriminatedUnion",(inst,def)=>{ZodUnion.init(inst,def),$ZodDiscriminatedUnion.init(inst,def)});function discriminatedUnion(discriminator,options,params){return new ZodDiscriminatedUnion({type:"union",options,discriminator,...util_exports.normalizeParams(params)})}var ZodIntersection=$constructor("ZodIntersection",(inst,def)=>{$ZodIntersection.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>intersectionProcessor(inst,ctx,json,params)});function intersection(left,right){return new ZodIntersection({type:"intersection",left,right})}var ZodRecord=$constructor("ZodRecord",(inst,def)=>{_ensureDefaultMemoizer(),$ZodRecord.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>recordProcessor(inst,ctx,json,params),inst.keyType=def.keyType,inst.valueType=def.valueType});function record(keyType,valueType,params){return!valueType||!valueType._zod?new ZodRecord({type:"record",keyType:string2(),valueType:keyType,...util_exports.normalizeParams(valueType)}):new ZodRecord({type:"record",keyType,valueType,...util_exports.normalizeParams(params)})}var ZodEnum=$constructor("ZodEnum",(inst,def)=>{$ZodEnum.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>enumProcessor(inst,ctx,json,params),inst.enum=def.entries,inst.options=[...inst._zod.values];let keys=new Set(Object.keys(def.entries));inst.extract=(values,params)=>{let newEntries={};for(let value of values)if(keys.has(value))newEntries[value]=def.entries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})},inst.exclude=(values,params)=>{let newEntries={...def.entries};for(let value of values)if(keys.has(value))delete newEntries[value];else throw new Error(`Key ${value} not found in enum`);return new ZodEnum({...def,checks:[],...util_exports.normalizeParams(params),entries:newEntries})}});function _enum(values,params){let entries=Array.isArray(values)?Object.fromEntries(values.map(v=>[v,v])):values;return new ZodEnum({type:"enum",entries,...util_exports.normalizeParams(params)})}var ZodLiteral=$constructor("ZodLiteral",(inst,def)=>{$ZodLiteral.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>literalProcessor(inst,ctx,json,params),inst.values=new Set(def.values),Object.defineProperty(inst,"value",{get(){if(def.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return def.values[0]}})});function literal(value,params){return new ZodLiteral({type:"literal",values:Array.isArray(value)?value:[value],...util_exports.normalizeParams(params)})}var ZodTransform=$constructor("ZodTransform",(inst,def)=>{_ensureDefaultMemoizer(),$ZodTransform.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>transformProcessor(inst,ctx,json,params),inst._zod.parse=(payload,_ctx)=>{if(_ctx.direction==="backward")throw new $ZodEncodeError(inst.constructor.name);payload.addIssue=issue2=>{if(typeof issue2=="string")payload.issues.push(util_exports.issue(issue2,payload.value,def));else{let _issue=issue2;_issue.fatal&&(_issue.continue=!1),_issue.code??(_issue.code="custom"),"input"in _issue||(_issue.input=payload.value),_issue.inst??(_issue.inst=inst),payload.issues.push(util_exports.issue(_issue))}};let output=def.transform(payload.value,payload);return output instanceof Promise?output.then(output2=>(payload.value=output2,payload)):(payload.value=output,payload)}});function transform(fn){return new ZodTransform({type:"transform",transform:fn})}var ZodOptional=$constructor("ZodOptional",(inst,def)=>{$ZodOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function optional(innerType){return new ZodOptional({type:"optional",innerType})}var ZodExactOptional=$constructor("ZodExactOptional",(inst,def)=>{$ZodExactOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>optionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function exactOptional(innerType){return new ZodExactOptional({type:"optional",innerType})}var ZodNullable=$constructor("ZodNullable",(inst,def)=>{$ZodNullable.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nullableProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nullable(innerType){return new ZodNullable({type:"nullable",innerType})}var ZodDefault=$constructor("ZodDefault",(inst,def)=>{$ZodDefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>defaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeDefault=inst.unwrap});function _default(innerType,defaultValue){return new ZodDefault({type:"default",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodPrefault=$constructor("ZodPrefault",(inst,def)=>{$ZodPrefault.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>prefaultProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function prefault(innerType,defaultValue){return new ZodPrefault({type:"prefault",innerType,get defaultValue(){return typeof defaultValue=="function"?defaultValue():util_exports.shallowClone(defaultValue)}})}var ZodNonOptional=$constructor("ZodNonOptional",(inst,def)=>{$ZodNonOptional.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>nonoptionalProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function nonoptional(innerType,params){return new ZodNonOptional({type:"nonoptional",innerType,...util_exports.normalizeParams(params)})}var ZodCatch=$constructor("ZodCatch",(inst,def)=>{$ZodCatch.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>catchProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType,inst.removeCatch=inst.unwrap});function _catch(innerType,catchValue){return new ZodCatch({type:"catch",innerType,catchValue:typeof catchValue=="function"?catchValue:util_exports.constantCatch(catchValue)})}var ZodPipe=$constructor("ZodPipe",(inst,def)=>{$ZodPipe.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>pipeProcessor(inst,ctx,json,params),inst.in=def.in,inst.out=def.out});function pipe(in_,out){return new ZodPipe({type:"pipe",in:in_,out})}var ZodPreprocess=$constructor("ZodPreprocess",(inst,def)=>{ZodPipe.init(inst,def),$ZodPreprocess.init(inst,def)}),ZodReadonly=$constructor("ZodReadonly",(inst,def)=>{$ZodReadonly.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>readonlyProcessor(inst,ctx,json,params),inst.unwrap=()=>inst._zod.def.innerType});function readonly(innerType){return new ZodReadonly({type:"readonly",innerType})}var ZodCustom=$constructor("ZodCustom",(inst,def)=>{$ZodCustom.init(inst,def),ZodType.init(inst,def),inst._zod.processJSONSchema=(ctx,json,params)=>customProcessor(inst,ctx,json,params)});function custom(fn,_params){return _custom(ZodCustom,fn??(()=>!0),_params)}function refine(fn,_params={}){return _refine(ZodCustom,fn,_params)}function superRefine(fn,params){return _superRefine(fn,params)}function preprocess(fn,schema){return new ZodPreprocess({type:"pipe",in:transform(fn),out:schema})}var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date2,datetime:()=>datetime2,duration:()=>duration2,time:()=>time2});function datetime2(params){return _isoDateTime(ZodISODateTime,params)}function date2(params){return _isoDate(ZodISODate,params)}function time2(params){return _isoTime(ZodISOTime,params)}function duration2(params){return _isoDuration(ZodISODuration,params)}var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=union([string2(),number2().int()]),CursorSchema=string2(),TaskCreationParamsSchema=looseObject({ttl:number2().optional(),pollInterval:number2().optional()}),TaskMetadataSchema=object2({ttl:number2().optional()}),RelatedTaskMetadataSchema=object2({taskId:string2()}),RequestMetaSchema=looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=object2({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,RequestSchema=object2({method:string2(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=object2({_meta:RequestMetaSchema.optional()}),NotificationSchema=object2({method:string2(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=union([string2(),number2().int()]),JSONRPCRequestSchema=object2({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=value=>JSONRPCRequestSchema.safeParse(value).success,JSONRPCNotificationSchema=object2({jsonrpc:literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=value=>JSONRPCNotificationSchema.safeParse(value).success,JSONRPCResultResponseSchema=object2({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=value=>JSONRPCResultResponseSchema.safeParse(value).success;var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=object2({jsonrpc:literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:object2({code:number2().int(),message:string2(),data:unknown().optional()})}).strict();var isJSONRPCErrorResponse=value=>JSONRPCErrorResponseSchema.safeParse(value).success;var JSONRPCMessageSchema=union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:string2().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=object2({src:string2(),mimeType:string2().optional(),sizes:array(string2()).optional(),theme:_enum(["light","dark"]).optional()}),IconsSchema=object2({icons:array(IconSchema).optional()}),BaseMetadataSchema=object2({name:string2(),title:string2().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:string2(),websiteUrl:string2().optional(),description:string2().optional()}),FormElicitationCapabilitySchema=intersection(object2({applyDefaults:boolean2().optional()}),record(string2(),unknown())),ElicitationCapabilitySchema=preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,intersection(object2({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),record(string2(),unknown()).optional())),ClientTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({sampling:looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:looseObject({tools:looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=object2({experimental:record(string2(),AssertObjectSchema).optional(),sampling:object2({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:object2({listChanged:boolean2().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional(),extensions:record(string2(),AssertObjectSchema).optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:string2(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=object2({experimental:record(string2(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:object2({listChanged:boolean2().optional()}).optional(),resources:object2({subscribe:boolean2().optional(),listChanged:boolean2().optional()}).optional(),tools:object2({listChanged:boolean2().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional(),extensions:record(string2(),AssertObjectSchema).optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:string2(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:string2().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=object2({progress:number2(),total:optional(number2()),message:optional(string2())}),ProgressNotificationParamsSchema=object2({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=_enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=object2({taskId:string2(),status:TaskStatusSchema,ttl:union([number2(),_null3()]),createdAt:string2(),lastUpdatedAt:string2(),pollInterval:optional(number2()),statusMessage:optional(string2())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:string2()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=object2({uri:string2(),mimeType:optional(string2()),_meta:record(string2(),unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:string2()}),Base64Schema=string2().refine(val=>{try{return atob(val),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=_enum(["user","assistant"]),AnnotationsSchema=object2({audience:array(RoleSchema).optional(),priority:number2().min(0).max(1).optional(),lastModified:iso_exports.datetime({offset:!0}).optional()}),ResourceSchema=object2({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:string2(),description:optional(string2()),mimeType:optional(string2()),size:optional(number2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ResourceTemplateSchema=object2({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:string2(),description:optional(string2()),mimeType:optional(string2()),annotations:AnnotationsSchema.optional(),_meta:optional(looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:string2()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:array(union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:string2()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=object2({name:string2(),description:optional(string2()),required:optional(boolean2())}),PromptSchema=object2({...BaseMetadataSchema.shape,...IconsSchema.shape,description:optional(string2()),arguments:optional(array(PromptArgumentSchema)),_meta:optional(looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:string2(),arguments:record(string2(),string2()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=object2({type:literal("text"),text:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ImageContentSchema=object2({type:literal("image"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),AudioContentSchema=object2({type:literal("audio"),data:Base64Schema,mimeType:string2(),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ToolUseContentSchema=object2({type:literal("tool_use"),name:string2(),id:string2(),input:record(string2(),unknown()),_meta:record(string2(),unknown()).optional()}),EmbeddedResourceSchema=object2({type:literal("resource"),resource:union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:record(string2(),unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:literal("resource_link")}),ContentBlockSchema=union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=object2({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:string2().optional(),messages:array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=object2({title:string2().optional(),readOnlyHint:boolean2().optional(),destructiveHint:boolean2().optional(),idempotentHint:boolean2().optional(),openWorldHint:boolean2().optional()}),ToolExecutionSchema=object2({taskSupport:_enum(["required","optional","forbidden"]).optional()}),ToolSchema=object2({...BaseMetadataSchema.shape,...IconsSchema.shape,description:string2().optional(),inputSchema:object2({type:literal("object"),properties:record(string2(),AssertObjectSchema).optional(),required:array(string2()).optional()}).catchall(unknown()),outputSchema:object2({type:literal("object"),properties:record(string2(),AssertObjectSchema).optional(),required:array(string2()).optional()}).catchall(unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:record(string2(),unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:array(ContentBlockSchema).default([]),structuredContent:record(string2(),unknown()).optional(),isError:boolean2().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:string2(),arguments:record(string2(),unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=object2({autoRefresh:boolean2().default(!0),debounceMs:number2().int().nonnegative().default(300)}),LoggingLevelSchema=_enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:string2().optional(),data:unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=object2({name:string2().optional()}),ModelPreferencesSchema=object2({hints:array(ModelHintSchema).optional(),costPriority:number2().min(0).max(1).optional(),speedPriority:number2().min(0).max(1).optional(),intelligencePriority:number2().min(0).max(1).optional()}),ToolChoiceSchema=object2({mode:_enum(["auto","required","none"]).optional()}),ToolResultContentSchema=object2({type:literal("tool_result"),toolUseId:string2().describe("The unique identifier for the corresponding tool call."),content:array(ContentBlockSchema).default([]),structuredContent:object2({}).loose().optional(),isError:boolean2().optional(),_meta:record(string2(),unknown()).optional()}),SamplingContentSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=object2({role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)]),_meta:record(string2(),unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:string2().optional(),includeContext:_enum(["none","thisServer","allServers"]).optional(),temperature:number2().optional(),maxTokens:number2().int(),stopSequences:array(string2()).optional(),metadata:AssertObjectSchema.optional(),tools:array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens"]).or(string2())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:string2(),stopReason:optional(_enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(string2())),role:RoleSchema,content:union([SamplingMessageContentBlockSchema,array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=object2({type:literal("boolean"),title:string2().optional(),description:string2().optional(),default:boolean2().optional()}),StringSchemaSchema=object2({type:literal("string"),title:string2().optional(),description:string2().optional(),minLength:number2().optional(),maxLength:number2().optional(),format:_enum(["email","uri","date","date-time"]).optional(),default:string2().optional()}),NumberSchemaSchema=object2({type:_enum(["number","integer"]),title:string2().optional(),description:string2().optional(),minimum:number2().optional(),maximum:number2().optional(),default:number2().optional()}),UntitledSingleSelectEnumSchemaSchema=object2({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),default:string2().optional()}),TitledSingleSelectEnumSchemaSchema=object2({type:literal("string"),title:string2().optional(),description:string2().optional(),oneOf:array(object2({const:string2(),title:string2()})),default:string2().optional()}),LegacyTitledEnumSchemaSchema=object2({type:literal("string"),title:string2().optional(),description:string2().optional(),enum:array(string2()),enumNames:array(string2()).optional(),default:string2().optional()}),SingleSelectEnumSchemaSchema=union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=object2({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object2({type:literal("string"),enum:array(string2())}),default:array(string2()).optional()}),TitledMultiSelectEnumSchemaSchema=object2({type:literal("array"),title:string2().optional(),description:string2().optional(),minItems:number2().optional(),maxItems:number2().optional(),items:object2({anyOf:array(object2({const:string2(),title:string2()}))}),default:array(string2()).optional()}),MultiSelectEnumSchemaSchema=union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("form").optional(),message:string2(),requestedSchema:object2({type:literal("object"),properties:record(string2(),PrimitiveSchemaDefinitionSchema),required:array(string2()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:literal("url"),message:string2(),elicitationId:string2(),url:string2().url()}),ElicitRequestParamsSchema=union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:string2()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:_enum(["accept","decline","cancel"]),content:preprocess(val=>val===null?void 0:val,record(string2(),union([string2(),number2(),boolean2(),array(string2())])).optional())}),ResourceTemplateReferenceSchema=object2({type:literal("ref/resource"),uri:string2()});var PromptReferenceSchema=object2({type:literal("ref/prompt"),name:string2()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:object2({name:string2(),value:string2()}),context:object2({arguments:record(string2(),string2()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:literal("completion/complete"),params:CompleteRequestParamsSchema});var CompleteResultSchema=ResultSchema.extend({completion:looseObject({values:array(string2()).max(100),total:optional(number2().int()),hasMore:optional(boolean2())})}),RootSchema=object2({uri:string2().startsWith("file://"),name:string2().optional(),_meta:record(string2(),unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{constructor(code,message,data){super(`MCP error ${code}: ${message}`),this.code=code,this.data=data,this.name="McpError"}static fromError(code,message,data){if(code===ErrorCode.UrlElicitationRequired&&data){let errorData=data;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code,message,data)}},UrlElicitationRequiredError=class extends McpError{constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function getMethodLiteral(schema){let methodSchema=getObjectShape(schema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let value=getLiteralValue(methodSchema);if(typeof value!="string")throw new Error("Schema method literal must be a string");return value}function parseWithCompat(schema,data){let result=safeParse2(schema,data);if(!result.success)throw result.error;return result.data}var DEFAULT_REQUEST_TIMEOUT_MSEC=6e4,Protocol=class{constructor(_options){this._options=_options,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(CancelledNotificationSchema,notification=>{this._oncancel(notification)}),this.setNotificationHandler(ProgressNotificationSchema,notification=>{this._onprogress(notification)}),this.setRequestHandler(PingRequestSchema,_request=>({})),this._taskStore=_options?.taskStore,this._taskMessageQueue=_options?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(GetTaskRequestSchema,async(request,extra)=>{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return{...task}}),this.setRequestHandler(GetTaskPayloadRequestSchema,async(request,extra)=>{let handleTaskResult=async()=>{let taskId=request.params.taskId;if(!await this._taskStore.getTask(taskId,extra.sessionId))throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(this._taskMessageQueue){let queuedMessage;for(;queuedMessage=await this._taskMessageQueue.dequeue(taskId,extra.sessionId);){if(queuedMessage.type==="response"||queuedMessage.type==="error"){let message=queuedMessage.message,requestId=message.id,resolver=this._requestResolvers.get(requestId);if(resolver)if(this._requestResolvers.delete(requestId),queuedMessage.type==="response")resolver(message);else{let errorMessage=message,error2=new McpError(errorMessage.error.code,errorMessage.error.message,errorMessage.error.data);resolver(error2)}else{let messageType=queuedMessage.type==="response"?"Response":"Error";this._onerror(new Error(`${messageType} handler missing for request ${requestId}`))}continue}await this._transport?.send(queuedMessage.message,{relatedRequestId:extra.requestId})}}let task=await this._taskStore.getTask(taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${taskId}`);if(!isTerminal(task.status))return await this._waitForTaskUpdate(taskId,extra.signal,extra.sessionId),await handleTaskResult();if(isTerminal(task.status)){let result=await this._taskStore.getTaskResult(taskId,extra.sessionId);return this._clearTaskQueue(taskId,extra.sessionId),{...result,_meta:{...result._meta,[RELATED_TASK_META_KEY]:{taskId}}}}return await handleTaskResult()};return await handleTaskResult()}),this.setRequestHandler(ListTasksRequestSchema,async(request,extra)=>{try{let{tasks,nextCursor}=await this._taskStore.listTasks(request.params?.cursor,extra.sessionId);return{tasks,nextCursor,_meta:{}}}catch(error2){throw new McpError(ErrorCode.InvalidParams,`Failed to list tasks: ${error2 instanceof Error?error2.message:String(error2)}`)}}),this.setRequestHandler(CancelTaskRequestSchema,async(request,extra)=>{try{let task=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task not found: ${request.params.taskId}`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot cancel task in terminal status: ${task.status}`);await this._taskStore.updateTaskStatus(request.params.taskId,"cancelled","Client cancelled task execution.",extra.sessionId),this._clearTaskQueue(request.params.taskId,extra.sessionId);let cancelledTask=await this._taskStore.getTask(request.params.taskId,extra.sessionId);if(!cancelledTask)throw new McpError(ErrorCode.InvalidParams,`Task not found after cancellation: ${request.params.taskId}`);return{_meta:{},...cancelledTask}}catch(error2){throw error2 instanceof McpError?error2:new McpError(ErrorCode.InvalidRequest,`Failed to cancel task: ${error2 instanceof Error?error2.message:String(error2)}`)}}))}async _oncancel(notification){if(!notification.params.requestId)return;this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason)}_setupTimeout(messageId,timeout,maxTotalTimeout,onTimeout,resetTimeoutOnProgress=!1){this._timeoutInfo.set(messageId,{timeoutId:setTimeout(onTimeout,timeout),startTime:Date.now(),timeout,maxTotalTimeout,resetTimeoutOnProgress,onTimeout})}_resetTimeout(messageId){let info=this._timeoutInfo.get(messageId);if(!info)return!1;let totalElapsed=Date.now()-info.startTime;if(info.maxTotalTimeout&&totalElapsed>=info.maxTotalTimeout)throw this._timeoutInfo.delete(messageId),McpError.fromError(ErrorCode.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:info.maxTotalTimeout,totalElapsed});return clearTimeout(info.timeoutId),info.timeoutId=setTimeout(info.onTimeout,info.timeout),!0}_cleanupTimeout(messageId){let info=this._timeoutInfo.get(messageId);info&&(clearTimeout(info.timeoutId),this._timeoutInfo.delete(messageId))}async connect(transport){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=transport;let _onclose=this.transport?.onclose;this._transport.onclose=()=>{_onclose?.(),this._onclose()};let _onerror=this.transport?.onerror;this._transport.onerror=error2=>{_onerror?.(error2),this._onerror(error2)};let _onmessage=this._transport?.onmessage;this._transport.onmessage=(message,extra)=>{_onmessage?.(message,extra),isJSONRPCResultResponse(message)||isJSONRPCErrorResponse(message)?this._onresponse(message):isJSONRPCRequest(message)?this._onrequest(message,extra):isJSONRPCNotification(message)?this._onnotification(message):this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`))},await this._transport.start()}_onclose(){let responseHandlers=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let info of this._timeoutInfo.values())clearTimeout(info.timeoutId);this._timeoutInfo.clear();for(let controller of this._requestHandlerAbortControllers.values())controller.abort();this._requestHandlerAbortControllers.clear();let error2=McpError.fromError(ErrorCode.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let handler of responseHandlers.values())handler(error2)}_onerror(error2){this.onerror?.(error2)}_onnotification(notification){let handler=this._notificationHandlers.get(notification.method)??this.fallbackNotificationHandler;handler!==void 0&&Promise.resolve().then(()=>handler(notification)).catch(error2=>this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)))}_onrequest(request,extra){let handler=this._requestHandlers.get(request.method)??this.fallbackRequestHandler,capturedTransport=this._transport,relatedTaskId=request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId,sessionId=capturedTransport?.sessionId,store=this._taskStore,relatedTaskFound=!0,relatedTaskLookup;if(relatedTaskId&&store&&this._taskMessageQueue&&sessionId!==void 0&&(relatedTaskFound=!1,relatedTaskLookup=(async()=>{if(!await store.getTask(relatedTaskId,sessionId))throw new McpError(ErrorCode.InvalidParams,`Task not found: ${relatedTaskId}`);relatedTaskFound=!0})()),handler===void 0){let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:ErrorCode.MethodNotFound,message:"Method not found"}};if(relatedTaskId&&relatedTaskLookup){let queuedError={type:"error",message:errorResponse,timestamp:Date.now()};relatedTaskLookup.then(()=>this._enqueueTaskMessage(relatedTaskId,queuedError,sessionId),()=>capturedTransport?.send(errorResponse)).catch(error2=>this._onerror(new Error(`Failed to send an error response: ${error2}`)))}else relatedTaskId&&this._taskMessageQueue?this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId).catch(error2=>this._onerror(new Error(`Failed to enqueue error response: ${error2}`))):capturedTransport?.send(errorResponse).catch(error2=>this._onerror(new Error(`Failed to send an error response: ${error2}`)));return}let abortController=new AbortController;this._requestHandlerAbortControllers.set(request.id,abortController);let taskCreationParams=isTaskAugmentedRequestParams(request.params)?request.params.task:void 0,taskStore=this._taskStore?this.requestTaskStore(request,capturedTransport?.sessionId):void 0,fullExtra={signal:abortController.signal,sessionId:capturedTransport?.sessionId,_meta:request.params?._meta,sendNotification:async notification=>{if(abortController.signal.aborted)return;let notificationOptions={relatedRequestId:request.id};relatedTaskId&&(notificationOptions.relatedTask={taskId:relatedTaskId}),await this.notification(notification,notificationOptions)},sendRequest:async(r,resultSchema,options)=>{if(abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");let requestOptions={...options,relatedRequestId:request.id};relatedTaskId&&!requestOptions.relatedTask&&(requestOptions.relatedTask={taskId:relatedTaskId});let effectiveTaskId=requestOptions.relatedTask?.taskId??relatedTaskId;return effectiveTaskId&&taskStore&&await taskStore.updateTaskStatus(effectiveTaskId,"input_required"),await this.request(r,resultSchema,requestOptions)},authInfo:extra?.authInfo,requestId:request.id,requestInfo:extra?.requestInfo,taskId:relatedTaskId,taskStore,taskRequestedTtl:taskCreationParams?.ttl,closeSSEStream:extra?.closeSSEStream,closeStandaloneSSEStream:extra?.closeStandaloneSSEStream};(relatedTaskLookup??Promise.resolve()).then(()=>{if(relatedTaskLookup&&abortController.signal.aborted)throw new McpError(ErrorCode.ConnectionClosed,"Request was cancelled");taskCreationParams&&this.assertTaskHandlerCapability(request.method)}).then(()=>handler(request,fullExtra)).then(async result=>{if(abortController.signal.aborted)return;let response={result,jsonrpc:"2.0",id:request.id};relatedTaskId&&this._taskMessageQueue?await this._enqueueTaskMessage(relatedTaskId,{type:"response",message:response,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(response)},async error2=>{if(abortController.signal.aborted)return;let errorResponse={jsonrpc:"2.0",id:request.id,error:{code:Number.isSafeInteger(error2.code)?error2.code:ErrorCode.InternalError,message:error2.message??"Internal error",...error2.data!==void 0&&{data:error2.data}}};relatedTaskId&&this._taskMessageQueue&&relatedTaskFound?await this._enqueueTaskMessage(relatedTaskId,{type:"error",message:errorResponse,timestamp:Date.now()},capturedTransport?.sessionId):await capturedTransport?.send(errorResponse)}).catch(error2=>this._onerror(new Error(`Failed to send response: ${error2}`))).finally(()=>{this._requestHandlerAbortControllers.get(request.id)===abortController&&this._requestHandlerAbortControllers.delete(request.id)})}_onprogress(notification){let{progressToken,...params}=notification.params,messageId=Number(progressToken),handler=this._progressHandlers.get(messageId);if(!handler){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));return}let responseHandler=this._responseHandlers.get(messageId),timeoutInfo=this._timeoutInfo.get(messageId);if(timeoutInfo&&responseHandler&&timeoutInfo.resetTimeoutOnProgress)try{this._resetTimeout(messageId)}catch(error2){this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),responseHandler(error2);return}handler(params)}_onresponse(response){let messageId=Number(response.id),resolver=this._requestResolvers.get(messageId);if(resolver){if(this._requestResolvers.delete(messageId),isJSONRPCResultResponse(response))resolver(response);else{let error2=new McpError(response.error.code,response.error.message,response.error.data);resolver(error2)}return}let handler=this._responseHandlers.get(messageId);if(handler===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));return}this._responseHandlers.delete(messageId),this._cleanupTimeout(messageId);let isTaskResponse=!1;if(isJSONRPCResultResponse(response)&&response.result&&typeof response.result=="object"){let result=response.result;if(result.task&&typeof result.task=="object"){let task=result.task;typeof task.taskId=="string"&&(isTaskResponse=!0,this._taskProgressTokens.set(task.taskId,messageId))}}if(isTaskResponse||this._progressHandlers.delete(messageId),isJSONRPCResultResponse(response))handler(response);else{let error2=McpError.fromError(response.error.code,response.error.message,response.error.data);handler(error2)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(request,resultSchema,options){let{task}=options??{};if(!task){try{yield{type:"result",result:await this.request(request,resultSchema,options)}}catch(error2){yield{type:"error",error:error2 instanceof McpError?error2:new McpError(ErrorCode.InternalError,String(error2))}}return}let taskId;try{let createResult=await this.request(request,CreateTaskResultSchema,options);if(createResult.task)taskId=createResult.task.taskId,yield{type:"taskCreated",task:createResult.task};else throw new McpError(ErrorCode.InternalError,"Task creation did not return a task");for(;;){let task2=await this.getTask({taskId},options);if(yield{type:"taskStatus",task:task2},isTerminal(task2.status)){task2.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)}:task2.status==="failed"?yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} failed`)}:task2.status==="cancelled"&&(yield{type:"error",error:new McpError(ErrorCode.InternalError,`Task ${taskId} was cancelled`)});return}if(task2.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId},resultSchema,options)};return}let pollInterval=task2.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(resolve=>setTimeout(resolve,pollInterval)),options?.signal?.throwIfAborted()}}catch(error2){yield{type:"error",error:error2 instanceof McpError?error2:new McpError(ErrorCode.InternalError,String(error2))}}}request(request,resultSchema,options){let{relatedRequestId,resumptionToken,onresumptiontoken,task,relatedTask}=options??{};return new Promise((resolve,reject)=>{let earlyReject=error2=>{reject(error2)};if(!this._transport){earlyReject(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(request.method),task&&this.assertTaskCapability(request.method)}catch(e){earlyReject(e);return}options?.signal?.throwIfAborted();let messageId=this._requestMessageId++,jsonrpcRequest={...request,jsonrpc:"2.0",id:messageId};options?.onprogress&&(this._progressHandlers.set(messageId,options.onprogress),jsonrpcRequest.params={...request.params,_meta:{...request.params?._meta||{},progressToken:messageId}}),task&&(jsonrpcRequest.params={...jsonrpcRequest.params,task}),relatedTask&&(jsonrpcRequest.params={...jsonrpcRequest.params,_meta:{...jsonrpcRequest.params?._meta||{},[RELATED_TASK_META_KEY]:relatedTask}});let cancel=reason=>{this._responseHandlers.delete(messageId),this._progressHandlers.delete(messageId),this._cleanupTimeout(messageId),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:messageId,reason:String(reason)}},{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error3=>this._onerror(new Error(`Failed to send cancellation: ${error3}`)));let error2=reason instanceof McpError?reason:new McpError(ErrorCode.RequestTimeout,String(reason));reject(error2)};this._responseHandlers.set(messageId,response=>{if(!options?.signal?.aborted){if(response instanceof Error)return reject(response);try{let parseResult=safeParse2(resultSchema,response.result);parseResult.success?resolve(parseResult.data):reject(parseResult.error)}catch(error2){reject(error2)}}}),options?.signal?.addEventListener("abort",()=>{cancel(options?.signal?.reason)});let timeout=options?.timeout??DEFAULT_REQUEST_TIMEOUT_MSEC,timeoutHandler=()=>cancel(McpError.fromError(ErrorCode.RequestTimeout,"Request timed out",{timeout}));this._setupTimeout(messageId,timeout,options?.maxTotalTimeout,timeoutHandler,options?.resetTimeoutOnProgress??!1);let relatedTaskId=relatedTask?.taskId;if(relatedTaskId){let responseResolver=response=>{let handler=this._responseHandlers.get(messageId);handler?handler(response):this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`))};this._requestResolvers.set(messageId,responseResolver),this._enqueueTaskMessage(relatedTaskId,{type:"request",message:jsonrpcRequest,timestamp:Date.now()}).catch(error2=>{this._cleanupTimeout(messageId),reject(error2)})}else this._transport.send(jsonrpcRequest,{relatedRequestId,resumptionToken,onresumptiontoken}).catch(error2=>{this._cleanupTimeout(messageId),reject(error2)})})}async getTask(params,options){return this.request({method:"tasks/get",params},GetTaskResultSchema,options)}async getTaskResult(params,resultSchema,options){return this.request({method:"tasks/result",params},resultSchema,options)}async listTasks(params,options){return this.request({method:"tasks/list",params},ListTasksResultSchema,options)}async cancelTask(params,options){return this.request({method:"tasks/cancel",params},CancelTaskResultSchema,options)}async notification(notification,options){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(notification.method);let relatedTaskId=options?.relatedTask?.taskId;if(relatedTaskId){let jsonrpcNotification2={...notification,jsonrpc:"2.0",params:{...notification.params,_meta:{...notification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}};await this._enqueueTaskMessage(relatedTaskId,{type:"notification",message:jsonrpcNotification2,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(notification.method)&&!notification.params&&!options?.relatedRequestId&&!options?.relatedTask){if(this._pendingDebouncedNotifications.has(notification.method))return;this._pendingDebouncedNotifications.add(notification.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(notification.method),!this._transport)return;let jsonrpcNotification2={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification2={...jsonrpcNotification2,params:{...jsonrpcNotification2.params,_meta:{...jsonrpcNotification2.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),this._transport?.send(jsonrpcNotification2,options).catch(error2=>this._onerror(error2))});return}let jsonrpcNotification={...notification,jsonrpc:"2.0"};options?.relatedTask&&(jsonrpcNotification={...jsonrpcNotification,params:{...jsonrpcNotification.params,_meta:{...jsonrpcNotification.params?._meta||{},[RELATED_TASK_META_KEY]:options.relatedTask}}}),await this._transport.send(jsonrpcNotification,options)}setRequestHandler(requestSchema,handler){let method=getMethodLiteral(requestSchema);this.assertRequestHandlerCapability(method),this._requestHandlers.set(method,(request,extra)=>{let parsed=parseWithCompat(requestSchema,request);return Promise.resolve(handler(parsed,extra))})}removeRequestHandler(method){this._requestHandlers.delete(method)}assertCanSetRequestHandler(method){if(this._requestHandlers.has(method))throw new Error(`A request handler for ${method} already exists, which would be overridden`)}setNotificationHandler(notificationSchema,handler){let method=getMethodLiteral(notificationSchema);this._notificationHandlers.set(method,notification=>{let parsed=parseWithCompat(notificationSchema,notification);return Promise.resolve(handler(parsed))})}removeNotificationHandler(method){this._notificationHandlers.delete(method)}_cleanupTaskProgressHandler(taskId){let progressToken=this._taskProgressTokens.get(taskId);progressToken!==void 0&&(this._progressHandlers.delete(progressToken),this._taskProgressTokens.delete(taskId))}async _enqueueTaskMessage(taskId,message,sessionId){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let maxQueueSize=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(taskId,message,sessionId??this._transport?.sessionId,maxQueueSize)}async _clearTaskQueue(taskId,sessionId){if(this._taskMessageQueue){let messages=await this._taskMessageQueue.dequeueAll(taskId,sessionId);for(let message of messages)if(message.type==="request"&&isJSONRPCRequest(message.message)){let requestId=message.message.id,resolver=this._requestResolvers.get(requestId);resolver?(resolver(new McpError(ErrorCode.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(requestId)):this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`))}}}async _waitForTaskUpdate(taskId,signal,sessionId){let interval=this._options?.defaultTaskPollInterval??1e3;try{let task=await this._taskStore?.getTask(taskId,sessionId);task?.pollInterval&&(interval=task.pollInterval)}catch{}return new Promise((resolve,reject)=>{if(signal.aborted){reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"));return}let timeoutId=setTimeout(resolve,interval);signal.addEventListener("abort",()=>{clearTimeout(timeoutId),reject(new McpError(ErrorCode.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(request,sessionId){let taskStore=this._taskStore;if(!taskStore)throw new Error("No task store configured");return{createTask:async taskParams=>{if(!request)throw new Error("No request provided");return await taskStore.createTask(taskParams,request.id,{method:request.method,params:request.params},sessionId)},getTask:async taskId=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,"Failed to retrieve task: Task not found");return task},storeTaskResult:async(taskId,status,result)=>{await taskStore.storeTaskResult(taskId,status,result,sessionId);let task=await taskStore.getTask(taskId,sessionId);if(task){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:task});await this.notification(notification),isTerminal(task.status)&&this._cleanupTaskProgressHandler(taskId)}},getTaskResult:taskId=>taskStore.getTaskResult(taskId,sessionId),updateTaskStatus:async(taskId,status,statusMessage)=>{let task=await taskStore.getTask(taskId,sessionId);if(!task)throw new McpError(ErrorCode.InvalidParams,`Task "${taskId}" not found - it may have been cleaned up`);if(isTerminal(task.status))throw new McpError(ErrorCode.InvalidParams,`Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await taskStore.updateTaskStatus(taskId,status,statusMessage,sessionId);let updatedTask=await taskStore.getTask(taskId,sessionId);if(updatedTask){let notification=TaskStatusNotificationSchema.parse({method:"notifications/tasks/status",params:updatedTask});await this.notification(notification),isTerminal(updatedTask.status)&&this._cleanupTaskProgressHandler(taskId)}},listTasks:cursor=>taskStore.listTasks(cursor,sessionId)}}};function isPlainObject2(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function mergeCapabilities(base,additional){let result={...base};for(let key in additional){let k=key,addValue=additional[k];if(addValue===void 0)continue;let baseValue=result[k];isPlainObject2(baseValue)&&isPlainObject2(addValue)?result[k]={...baseValue,...addValue}:result[k]=addValue}return result}var import_ajv=__toESM(require_ajv(),1),import_ajv_formats=__toESM(require_dist(),1);function createDefaultAjvInstance(){let ajv=new import_ajv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,import_ajv_formats.default)(ajv),ajv}var AjvJsonSchemaValidator=class{constructor(ajv){this._ajv=ajv??createDefaultAjvInstance()}getValidator(schema){let ajvValidator="$id"in schema&&typeof schema.$id=="string"?this._ajv.getSchema(schema.$id)??this._ajv.compile(schema):this._ajv.compile(schema);return input=>ajvValidator(input)?{valid:!0,data:input,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(ajvValidator.errors)}}};var ExperimentalServerTasks=class{constructor(_server){this._server=_server}requestStream(request,resultSchema,options){return this._server.requestStream(request,resultSchema,options)}createMessageStream(params,options){let clientCapabilities=this._server.getClientCapabilities();if((params.tools||params.toolChoice)&&!clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id)),toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}elicitInputStream(params,options){let clientCapabilities=this._server.getClientCapabilities(),mode=params.mode??"form";switch(mode){case"url":{if(!clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let normalizedParams=mode==="form"&¶ms.mode===void 0?{...params,mode:"form"}:params;return this.requestStream({method:"elicitation/create",params:normalizedParams},ElicitResultSchema,options)}async getTask(taskId,options){return this._server.getTask({taskId},options)}async getTaskResult(taskId,resultSchema,options){return this._server.getTaskResult({taskId},resultSchema,options)}async listTasks(cursor,options){return this._server.listTasks(cursor?{cursor}:void 0,options)}async cancelTask(taskId,options){return this._server.cancelTask({taskId},options)}};function assertToolsCallTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"tools/call":if(!requests.tools?.call)throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);break;default:break}}function assertClientRequestTaskCapability(requests,method,entityName){if(!requests)throw new Error(`${entityName} does not support task creation (required for ${method})`);switch(method){case"sampling/createMessage":if(!requests.sampling?.createMessage)throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);break;case"elicitation/create":if(!requests.elicitation?.create)throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);break;default:break}}var Server=class extends Protocol{constructor(_serverInfo,options){super(options),this._serverInfo=_serverInfo,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(LoggingLevelSchema.options.map((level,index)=>[level,index])),this.isMessageIgnored=(level,sessionId)=>{let currentLevel=this._loggingLevels.get(sessionId);return currentLevel?this.LOG_LEVEL_SEVERITY.get(level)<this.LOG_LEVEL_SEVERITY.get(currentLevel):!1},this._capabilities=options?.capabilities??{},this._instructions=options?.instructions,this._jsonSchemaValidator=options?.jsonSchemaValidator??new AjvJsonSchemaValidator,this.setRequestHandler(InitializeRequestSchema,request=>this._oninitialize(request)),this.setNotificationHandler(InitializedNotificationSchema,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(SetLevelRequestSchema,async(request,extra)=>{let transportSessionId=extra.sessionId||extra.requestInfo?.headers["mcp-session-id"]||void 0,{level}=request.params,parseResult=LoggingLevelSchema.safeParse(level);return parseResult.success&&this._loggingLevels.set(transportSessionId,parseResult.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ExperimentalServerTasks(this)}),this._experimental}registerCapabilities(capabilities){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=mergeCapabilities(this._capabilities,capabilities)}setRequestHandler(requestSchema,handler){let methodSchema=getObjectShape(requestSchema)?.method;if(!methodSchema)throw new Error("Schema is missing a method literal");let methodValue=getLiteralValue(methodSchema);if(typeof methodValue!="string")throw new Error("Schema method literal must be a string");if(methodValue==="tools/call"){let wrappedHandler=async(request,extra)=>{let validatedRequest=safeParse2(CallToolRequestSchema,request);if(!validatedRequest.success){let errorMessage=validatedRequest.error instanceof Error?validatedRequest.error.message:String(validatedRequest.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call request: ${errorMessage}`)}let{params}=validatedRequest.data,result=await Promise.resolve(handler(request,extra));if(params.task){let taskValidationResult=safeParse2(CreateTaskResultSchema,result);if(!taskValidationResult.success){let errorMessage=taskValidationResult.error instanceof Error?taskValidationResult.error.message:String(taskValidationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid task creation result: ${errorMessage}`)}return taskValidationResult.data}let validationResult=safeParse2(CallToolResultSchema,result);if(!validationResult.success){let errorMessage=validationResult.error instanceof Error?validationResult.error.message:String(validationResult.error);throw new McpError(ErrorCode.InvalidParams,`Invalid tools/call result: ${errorMessage}`)}return validationResult.data};return super.setRequestHandler(requestSchema,wrappedHandler)}return super.setRequestHandler(requestSchema,handler)}assertCapabilityForMethod(method){switch(method){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${method})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${method})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${method})`);break;case"ping":break}}assertNotificationCapability(method){switch(method){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${method})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${method})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(method){if(this._capabilities)switch(method){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${method})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${method})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${method})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${method})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${method})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${method})`);break;case"ping":case"initialize":break}}assertTaskCapability(method){assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests,method,"Client")}assertTaskHandlerCapability(method){this._capabilities&&assertToolsCallTaskCapability(this._capabilities.tasks?.requests,method,"Server")}async _oninitialize(request){let requestedVersion=request.params.protocolVersion;return this._clientCapabilities=request.params.capabilities,this._clientVersion=request.params.clientInfo,{protocolVersion:SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion)?requestedVersion:LATEST_PROTOCOL_VERSION,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"},EmptyResultSchema)}async createMessage(params,options){if((params.tools||params.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(params.messages.length>0){let lastMessage=params.messages[params.messages.length-1],lastContent=Array.isArray(lastMessage.content)?lastMessage.content:[lastMessage.content],hasToolResults=lastContent.some(c=>c.type==="tool_result"),previousMessage=params.messages.length>1?params.messages[params.messages.length-2]:void 0,previousContent=previousMessage?Array.isArray(previousMessage.content)?previousMessage.content:[previousMessage.content]:[],hasPreviousToolUse=previousContent.some(c=>c.type==="tool_use");if(hasToolResults){if(lastContent.some(c=>c.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!hasPreviousToolUse)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(hasPreviousToolUse){let toolUseIds=new Set(previousContent.filter(c=>c.type==="tool_use").map(c=>c.id)),toolResultIds=new Set(lastContent.filter(c=>c.type==="tool_result").map(c=>c.toolUseId));if(toolUseIds.size!==toolResultIds.size||![...toolUseIds].every(id=>toolResultIds.has(id)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return params.tools?this.request({method:"sampling/createMessage",params},CreateMessageResultWithToolsSchema,options):this.request({method:"sampling/createMessage",params},CreateMessageResultSchema,options)}async elicitInput(params,options){switch(params.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let urlParams=params;return this.request({method:"elicitation/create",params:urlParams},ElicitResultSchema,options)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let formParams=params.mode==="form"?params:{...params,mode:"form"},result=await this.request({method:"elicitation/create",params:formParams},ElicitResultSchema,options);if(result.action==="accept"&&result.content&&formParams.requestedSchema)try{let validationResult=this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content);if(!validationResult.valid)throw new McpError(ErrorCode.InvalidParams,`Elicitation response content does not match requested schema: ${validationResult.errorMessage}`)}catch(error2){throw error2 instanceof McpError?error2:new McpError(ErrorCode.InternalError,`Error validating elicitation response: ${error2 instanceof Error?error2.message:String(error2)}`)}return result}}}createElicitationCompletionNotifier(elicitationId,options){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId}},options)}async listRoots(params,options){return this.request({method:"roots/list",params},ListRootsResultSchema,options)}async sendLoggingMessage(params,sessionId){if(this._capabilities.logging&&!this.isMessageIgnored(params.level,sessionId))return this.notification({method:"notifications/message",params})}async sendResourceUpdated(params){return this.notification({method:"notifications/resources/updated",params})}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"})}};import process2 from"node:process";var STDIO_DEFAULT_MAX_BUFFER_SIZE=10*1024*1024,ReadBuffer=class{constructor(options){this._maxBufferSize=options?.maxBufferSize??STDIO_DEFAULT_MAX_BUFFER_SIZE}append(chunk){if((this._buffer?.length??0)+chunk.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,chunk]):chunk}readMessage(){if(!this._buffer)return null;let index=this._buffer.indexOf(`
|
|
66
66
|
`);if(index===-1)return null;let line=this._buffer.toString("utf8",0,index).replace(/\r$/,"");return this._buffer=this._buffer.subarray(index+1),deserializeMessage(line)}clear(){this._buffer=void 0}};function deserializeMessage(line){return JSONRPCMessageSchema.parse(JSON.parse(line))}function serializeMessage(message){return JSON.stringify(message)+`
|
|
67
|
-
`}var StdioServerTransport=class{constructor(_stdin=process2.stdin,_stdout=process2.stdout){this._stdin=_stdin,this._stdout=_stdout,this.
|
|
67
|
+
`}var StdioServerTransport=class{constructor(_stdin=process2.stdin,_stdout=process2.stdout,options){this._stdin=_stdin,this._stdout=_stdout,this._started=!1,this._ondata=chunk=>{try{this._readBuffer.append(chunk),this.processReadBuffer()}catch(error2){this.onerror?.(error2),this.close().catch(()=>{})}},this._onerror=error2=>{this.onerror?.(error2)},this._readBuffer=new ReadBuffer({maxBufferSize:options?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let message=this._readBuffer.readMessage();if(message===null)break;this.onmessage?.(message)}catch(error2){this.onerror?.(error2)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(message){return new Promise(resolve=>{let json=serializeMessage(message);this._stdout.write(json)?resolve():this._stdout.once("drain",resolve)})}};import*as client from"@mearl/client";import{executeScript}from"@mearl/client/script";function asRecord(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:null}function requiredString(value,name){let result=typeof value=="string"?value.trim():"";if(!result)throw new Error(`${name} must be a non-empty string`);return result}async function invokePluginTool(value,invoke2){let input=asRecord(value);if(!input)throw new Error("plugin arguments must be an object");let plugin=requiredString(input.plugin,"plugin"),command=requiredString(input.command,"command"),commandInput=input.input===void 0?{}:asRecord(input.input);if(!commandInput)throw new Error("input must be an object");let options={source:"mcp"};if(input.browser!==void 0&&(options.browser=requiredString(input.browser,"browser")),input.timeoutSec!==void 0){if(typeof input.timeoutSec!="number"||!Number.isFinite(input.timeoutSec)||input.timeoutSec<=0)throw new Error("timeoutSec must be a positive number");options.timeoutSec=input.timeoutSec}return invoke2(plugin,{command,input:commandInput},options)}import{writeFileSync,appendFileSync,readFileSync,existsSync}from"fs";import{tmpdir}from"os";import{join,dirname}from"path";import{spawn}from"child_process";import{fileURLToPath}from"url";import{createRequire}from"module";import{MEARL_NATIVE_HOST_NAMES}from"@mearl/client/native-host";var RESPONSE_SIZE_SMALL=50*1024,RESPONSE_SIZE_MEDIUM=200*1024,RESPONSE_SIZE_LARGE=500*1024,RESPONSE_SIZE_MAX=1024*1024,HOST_NAME=MEARL_NATIVE_HOST_NAMES.mcp;var require2=createRequire(import.meta.url),MCP_SERVER_VERSION=require2("../package.json").version,BROWSER_DEVICE_PRESET_NAMES2=client.BROWSER_DEVICE_PRESET_NAMES,MCP_TOOL_ACTIONS={browser_tab_checkpoint:"tab_checkpoint",browser_get_requests:"get_requests",browser_get_events:"get_events",browser_get_logs:"get_logs",browser_set_mock:"set_mock",browser_get_mocks:"get_mocks",browser_send_request:"send_request",browser_set_rule:"set_rule",browser_get_rules:"get_rules",browser_get_capabilities:"get_capabilities",browser_page_screenshot:"page_screenshot",browser_launch:"browser_launch",browser_close:"browser_close",browser_release:"browser_release",browser_control:"browser_control",browser_page_download:"page_download",browser_tab_open:"tab_open",browser_tab_close:"tab_close",browser_tab_list:"tab_list",browser_tab_group:"tab_group",browser_page_click:"page_click",browser_page_drag:"page_drag",browser_page_type:"page_type",browser_page_scroll:"page_scroll",browser_page_hover:"page_hover",browser_page_eval:"page_eval",browser_page_inspect:"page_inspect",browser_page_snapshot:"page_snapshot",browser_page_press:"page_press",browser_page_wait:"page_wait",browser_page_navigate:"page_navigate",browser_page_upload:"page_upload",browser_page_frames:"page_frames",browser_set_device_emulation:"set_device_emulation",browser_set_app_profile:"set_app_profile",browser_set_timezone:"set_timezone",browser_get_cookie:"get_cookie",browser_set_cookie:"set_cookie",browser_run_actions:"run_actions",browser_list:"browser_list",browser_select_browser:"browser_select_browser",browser_request_permission:"request_permission"},PLUGIN_INVOKE_TOOL_NAME="plugin_invoke",RUN_CODE_TOOL_NAME="browser_run_code";var LOG_FILE=join(tmpdir(),"mearl-mcp-server.log"),log=(...args)=>{let msg=`[${new Date().toISOString()}] [MCP Server] ${args.join(" ")}
|
|
68
68
|
`;try{appendFileSync(LOG_FILE,msg)}catch{}console.error("[MCP Server]",...args)};function printCliHelp(){console.error(`mearl-mcp-server v${MCP_SERVER_VERSION}
|
|
69
69
|
|
|
70
70
|
Usage:
|
|
@@ -115,4 +115,4 @@ Largest fields per item:`,stats.largestFields.forEach(f=>{header+=`
|
|
|
115
115
|
${"─".repeat(60)}
|
|
116
116
|
|
|
117
117
|
${compactStr}`}]}let suggestions=getOptimizationSuggestions(toolName,args,result,stats),diagnostic={error:{code:"RESPONSE_TOO_LARGE",message:"The result exceeded the MCP response limit. Narrow the request and retry.",originalSizeBytes:compactSize,limitBytes:RESPONSE_SIZE_MAX},...result?.session?{session:{sessionId:result.session.sessionId,browserId:result.session.browserId,transport:result.session.transport,status:result.session.status,generation:result.session.generation}}:{},...result?.failedStep!==void 0?{failedStep:result.failedStep,completedSteps:result.completedSteps,totalSteps:result.totalSteps,stage:result.stage}:{},...result?.action?{action:{name:result.action.name,success:result.action.success}}:{},...toolName===RUN_CODE_TOOL_NAME?{success:result.success,executionStopped:result.executionStopped,mayHaveLateEffects:result.mayHaveLateEffects,pendingActions:result.pendingActions}:{},meta:stats.meta,largestFields:stats.largestFields?.map(field=>({...field,percentageOfTotal:Math.round(field.size/compactSize*100)})),suggestions:suggestions.length>0?suggestions:["Significantly reduce the data requested",'Use "fields" to extract only essential data',"Add filters to narrow down results"]};return[{type:"text",text:JSON.stringify(diagnostic,null,2)}]}async function main(){let rawArgs=process.argv.slice(2),cliArgs={forwardedArgs:[],mode:"server"};if(rawArgs.length>0)try{let{parseMcpArgs:parseMcpArgs2}=await Promise.resolve().then(()=>(init_cliArgs(),cliArgs_exports));cliArgs=await parseMcpArgs2(rawArgs)}catch(error2){console.error(`Error: ${error2 instanceof Error?error2.message:String(error2)}`),printCliHelp(),process.exitCode=2;return}if(cliArgs.mode==="help"){printCliHelp();return}if(cliArgs.mode==="version"){console.log(MCP_SERVER_VERSION);return}if(cliArgs.mode==="configure"){let __filename=fileURLToPath(import.meta.url),__dirname=dirname(__filename),configureScript=join(__dirname,"configure-bin.js");spawn(process.execPath,[configureScript,...cliArgs.forwardedArgs],{stdio:"inherit"}).on("exit",code=>{process.exit(code||0)});return}if(cliArgs.mode==="uninstall"){let __filename=fileURLToPath(import.meta.url),__dirname=dirname(__filename),uninstallScript=join(__dirname,"uninstall-bin.js");spawn(process.execPath,[uninstallScript,...cliArgs.forwardedArgs],{stdio:"inherit"}).on("exit",code=>{process.exit(code||0)});return}writeFileSync(LOG_FILE,`=== Mearl MCP Server Started at ${new Date().toISOString()} ===
|
|
118
|
-
`),log("Starting Mearl MCP Server..."),log("MCP Server initialized, will connect to Chrome Extension when tools are called");let server=new Server({name:"mearl",version:MCP_SERVER_VERSION},{capabilities:{tools:{}},instructions:"取得 tabId 后持续显式复用,默认后台操作。首次进入或导航后取一次 browser_page_snapshot,按 viewport、局部根节点或 query 控制范围;AX 稀疏时才用 dom,每次快照只用本次新 ref。交互默认返回 { action, observation },先检查 action.success 再核验业务效果;precondition 表示未派发,没有 observation/diagnostics;dispatch-uncertain 表示可能已生效,先检查 action.attempt 与可用观察或最小快照,避免直接重试。delta 优先复用 effects 中的 ref/selector,changed=true 且 effects 为空不表示失败;navigation 的 ready 表示就绪,openedTabs 已提供可操作 tabId。增量缺少下一步目标、ref 失效、需要新滚动视口或 fullSnapshotRecommended 提示时补最小快照,不固定追加 wait/snapshot/screenshot。布局和遮挡用 inspect,视觉任务用 screenshot,结构化工具无法表达时才用最小 page_eval。observe:false 且未开启 diagnostics 时返回裸动作结果,没有 action/observation;仅开启诊断时返回 { action, diagnostics },诊断不等待 DOM/导航稳定。page_eval 默认返回 { result }。run_actions 只用于无需中间判断的紧密序列,步骤没有内置观察。按用户目标核验终态;browser_release 只在用户要求结束接管或清理会话时调用。"}),OBSERVE_INPUT_SCHEMA={type:["object","boolean"],default:{},description:"默认开启 DOM/相关请求/导航稳定观察,返回 { action, observation }。传 false 且未开启 diagnostics 时返回裸动作结果,没有 action/observation;开启 diagnostics 时返回 { action, diagnostics }。关闭观察不等待 DOM/导航稳定",properties:{quietMs:{type:"number",description:"最后一次 DOM 变化后等待的稳定窗口,默认 100ms"},firstChangeTimeoutMs:{type:"number",description:"没有发生 DOM 变化时最多等待多久,默认 500ms"},timeoutMs:{type:"number",description:"整个观察阶段的最大时间,默认 3000ms"},navigationGraceMs:{type:"number",description:"低信息量点击或按键后等待导航开始的基础宽限时间,默认 1000ms;若仍有网络活动会自动延长,有明确 effects 时不等待"},navigationTimeoutMs:{type:"number",description:"导航开始后等待页面就绪的最大时间,默认 15000ms"},networkIdleMs:{type:"number",description:"文档加载完成且相关 XHR/Fetch/MTop 请求归零后继续保持静默的时间,默认 500ms,用于跳过业务骨架屏"},contentReadyAfterMs:{type:"number",description:"动作开始后允许用结构稳定兜底的保护期,默认 min(5000, navigationTimeoutMs / 2),并限制在导航超时之前;保护期内优先等待网络静默"}}},DIAGNOSTICS_INPUT_SCHEMA={type:["object","boolean"],default:!1,description:"默认关闭;true 返回动作期间新增 error logs/业务 requests,对象可自定义通道并显式开启 events。与 observe 独立;关闭观察时返回 { action, diagnostics },precondition 失败省略 diagnostics",properties:{logs:{type:["object","boolean"],properties:{level:{type:"string",enum:["log","warn","error","info","all"]},limit:{type:"number",default:100},filter:{type:"string"}}},requests:{type:["object","boolean"],properties:{source:{type:"string",enum:["mtop","requests","all"]},count:{type:"number",default:100},filter:{type:"string"},includeBody:{type:"boolean",default:!1},includeHeaders:{type:"boolean",default:!1},maxBodySize:{type:"number",description:"单个请求/响应体的最大字符数"},fields:{type:"array",items:{type:"string"},maxItems:100,description:"从响应体提取指定字段路径,如 data.list[0].id"},keysOnly:{type:"boolean",description:"只返回数据结构,不返回叶子值"}}},events:{type:["object","boolean"],properties:{source:{type:"string",enum:["rum","aplus","arms","all"]},event_type:{type:"string"},filter:{type:"string"},limit:{type:"number",default:100},includeRaw:{type:"boolean",default:!1}}}}},tools=[{name:"browser_control",description:"交给用户操作当前会话;用户在 Mearl 中交还后重新观察页面",inputSchema:{type:"object",properties:{operation:{type:"string",enum:["handoff","resume"]},reason:{type:"string"},tabId:{type:"number"}},required:["operation","session"]}},{name:"browser_page_download",description:"先监听再点击并等待下载,outputPath 可将文件分块保存到 MCP 宿主",inputSchema:{type:"object",properties:{tabId:{type:"number"},trigger:{type:"object"},url:{type:"string"},timeout:{type:"number"},outputPath:{type:"string"}},required:["tabId","trigger"]}},{name:PLUGIN_INVOKE_TOOL_NAME,description:"调用当前 MCP Server 宿主上的 Mearl Skill 插件,对应 CLI 的 mearl <plugin>。已登记在能力目录中的缺失插件可按需安装。插件名、子命令、认证方式和 input 契约以对应 Skill 为准;Node 插件使用当前宿主环境,浏览器操作使用当前选择或显式指定的 Browser ID。",inputSchema:{type:"object",properties:{plugin:{type:"string",description:"已注册的插件名,或当前能力目录中可按需安装的插件名"},command:{type:"string",description:"插件注册的子命令名"},input:{type:"object",description:"传给插件 handler 的业务参数,省略时为空对象",additionalProperties:!0},browser:{type:"string",description:"可选目标浏览器 ID 或名称;省略时继承 browser_select_browser 选择的目标"},timeoutSec:{type:"number",description:"可选的浏览器底层调用超时秒数"}},required:["plugin","command"]}},{name:"browser_tab_checkpoint",description:"为目标标签页建立日志、请求和埋点的可靠增量边界,对应 mearl tab_checkpoint。返回的 cursor 可传给 browser_get_logs/browser_get_requests/browser_get_events 的 after。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"}},required:["tabId"]}},{name:"browser_get_requests",description:"获取指定标签页持续采集的 API 请求历史,包含请求、响应与 pending 状态。无需打开 DevTools panel;不传 after 时返回最新 N 条,传 after 时从最早未读项开始分页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},count:{type:"number",description:"获取的请求数量,默认 10 个。最多可获取最近 1000 个请求",default:10},filter:{type:"string",description:'过滤 API 名称的正则表达式(可选)。例如: ".*\\.cart\\..*" 只返回购物车相关接口'},since:{type:"number",description:"从多久之前开始获取(秒)。例如: 60 表示获取最近 1 分钟内的请求"},after:{type:"string",description:"tab checkpoint 或上一次查询返回的 cursor,仅返回其后的请求"},includeBody:{type:"boolean",description:"是否包含请求体和响应体。指定 fields 时默认 false,否则默认 true;可显式设为 true 同时读取全文。"},includeHeaders:{type:"boolean",description:"是否包含请求头和响应头。false 时将省略 headers 和 responseHeaders 字段以减少数据量。默认 false",default:!1},maxBodySize:{type:"number",description:"单个请求/响应体的最大字节数。超过此大小将被截断。默认 50000(约 50KB)",default:5e4},fields:{type:"array",items:{type:"string"},description:'从响应体中提取指定字段,支持点号路径。例如: ["data.result.list", "data.total"] 只返回这些字段,大幅减少数据量'},keysOnly:{type:"boolean",description:"只返回数据结构(字段路径和类型),不返回实际值。设为 true 可先预览数据结构,再决定提取哪些字段。默认 false",default:!1},source:{type:"string",enum:["mtop","requests","all"],description:"数据源。mtop: mtop 接口(默认); requests: 普通 XHR/Fetch 请求; all: 全部业务请求"}},required:["tabId"]}},{name:"browser_get_events",description:"获取目标标签页后台采集的 RUM/aplus/ARMS 埋点事件,无需打开 DevTools panel。不传 after 时返回最新事件,传 after 时按完整上报批次从最早未读项开始分页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},source:{type:"string",enum:["rum","aplus","arms","all"],description:"事件来源。rum: RUM 性能监控事件; aplus: aplus 埋点事件; arms: ARMS 前端监控事件; all: 全部(默认)",default:"all"},event_type:{type:"string",description:'事件类型正则过滤。例如: "view" 匹配页面 view 事件, "CLK" 匹配点击埋点'},filter:{type:"string",description:"正则过滤,匹配事件的 name 或 url 字段"},since:{type:"number",description:"从多久之前开始获取(秒)。例如: 60 表示获取最近 1 分钟内的事件"},after:{type:"string",description:"tab checkpoint 或上一次查询返回的 cursor,仅返回其后的埋点事件"},limit:{type:"number",description:"返回条数上限,默认 20",default:20},includeRaw:{type:"boolean",description:"是否返回完整 tracking URL、_raw 原始载荷和 _context 上下文;默认 false,仅返回解析后的精简字段",default:!1}},required:["tabId"]}},{name:"browser_get_logs",description:"获取指定标签页持续采集的 console API、未捕获异常和浏览器日志。无需打开 DevTools panel;不传 after 时返回最新 N 条,传 after 时从最早未读项开始分页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},level:{type:"string",enum:["log","warn","error","info","all"],description:"日志级别过滤。log: 普通日志, warn: 警告, error: 错误, info: 信息, all: 所有级别。默认 all",default:"all"},since:{type:"number",description:"从多久之前开始获取日志(秒)。例如: 60 表示获取最近 1 分钟内的日志"},after:{type:"string",description:"tab checkpoint 或上一次查询返回的 cursor,仅返回其后的日志"},limit:{type:"number",description:"最大返回日志数量,默认 100;快照查询返回最新 N 条",default:100},filter:{type:"string",description:'过滤日志内容的正则表达式或字符串(可选)。支持正则表达式模式(不区分大小写),若正则无效则回退到字符串包含匹配。例如: "error|warning" 匹配包含 error 或 warning 的日志'}},required:["tabId"]}},{name:"browser_set_mock",description:"动态设置 API 接口的 Mock 数据,用于测试不同数据场景。修改后,浏览器中对该接口的所有请求都会返回 Mock 数据。适用于前端开发测试、边界情况验证、UI 状态测试等。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},apiName:{type:"string",description:'API 名称或正则表达式模式。例如: "mtop.cart.query" 精确匹配, ".*\\.cart\\..*" 匹配所有购物车接口'},mockData:{type:["object","string"],description:'【方式一】直接设置完整 Mock 响应数据(JSON 对象)。传入后该接口将完全返回此数据,不再请求真实服务端。示例: {"data":{"result":{"list":[]}},"ret":["SUCCESS"]}。注意:mockData 和 fields 二选一,同时提供时优先使用 fields。大体积响应体可传文件引用字符串 "@/abs/resp.json"(从该文件读取,建议绝对路径)以减少上下文占用'},fields:{type:"array",description:"【方式二】基于真实响应修改指定字段。系统会先获取该接口的原始响应数据,然后按指定路径修改字段值。适合在真实数据基础上做微调",items:{type:"object",properties:{path:{type:"string",description:'字段路径,支持点号和数组索引。例如: "data.result.passengerList[0].name.text"'},value:{description:"要设置的值,可以是任意类型(字符串、数字、对象、数组等)"}},required:["path","value"]}},enabled:{type:"boolean",description:"是否启用 Mock。true: 启用 Mock, false: 禁用 Mock 恢复真实数据。默认 true",default:!0},duration:{type:"number",description:"完整响应时长(毫秒)。可选,mock 生效时的总耗时,绕过真实服务器精确控制(用于测试加载状态、超时等场景)"},conditions:{type:"object",additionalProperties:!0,description:"请求 query/body 字段的子集匹配规则;保留字段 $index 从 0 开始指定同一场景的调用顺序。相同 $index 再次设置会原地覆盖,超过最后一项后持续使用最后一项"},payloadFile:{type:"string",description:"从文件读取 mock 数据(JSON 格式)。当 mockData 很大时,可将完整 JSON 写入文件,通过此参数指定文件路径。文件内容会被解析为 mockData。注意:此参数与 mockData/fields 互斥,优先级最高"}},required:["tabId","apiName"]}},{name:"browser_get_mocks",description:"查看当前所有已设置的 Mock 配置,包括接口名称、是否启用、以及 Mock 数据内容。用于排查 Mock 是否生效、Mock 数据是否正确等问题。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},apiName:{type:"string",description:'过滤指定接口,支持正则表达式。例如: "mtop.cart.query" 或 ".*\\.cart\\..*"。不传则返回所有 Mock'}},required:["tabId"]}},{name:"browser_send_request",description:"通过浏览器发起 HTTP 代理请求,自动携带目标域名的 Cookie(使用当前浏览器登录态)。支持 GET/POST/PUT/DELETE/PATCH、multipart 文本字段和本地文件上传,适用于需要用户登录态的接口调试、数据爬取、接口测试等场景。",inputSchema:{type:"object",properties:{url:{type:"string",description:"目标请求 URL,必须是完整 URL(含 http:// 或 https://)"},method:{type:"string",enum:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],description:"HTTP 请求方法,默认 GET",default:"GET"},headers:{type:"object",description:"自定义请求头(键值对),会与自动生成的 Cookie 头合并",additionalProperties:{type:"string"}},params:{type:"object",description:"URL 查询参数(键值对),会追加到 URL 中",additionalProperties:{type:"string"}},body:{description:"请求体。传入对象时自动序列化为 JSON 并设置 Content-Type: application/json;传入字符串时原样发送"},formData:{type:"object",description:"multipart/form-data 文本字段。字段值支持 string、number、boolean;不能与 body 同时使用",additionalProperties:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"}]}},files:{type:"array",description:"multipart 文件列表,最多 20 个且总计不超过 40 MiB。本地调用优先传绝对 filePath;远程调用可传 base64,并同时提供 filename,Base64 文件内容总计不超过 7 MiB",maxItems:20,items:{type:"object",properties:{fieldName:{type:"string",description:"multipart 字段名,例如 file"},filePath:{type:"string",description:"Mearl native-host 所在机器上的绝对文件路径"},base64:{type:"string",description:"文件内容的 Base64;与 filePath 二选一"},filename:{type:"string",description:"上传文件名;使用 base64 时必填"},contentType:{type:"string",description:"文件 MIME 类型;默认根据文件名推断"}},required:["fieldName"],oneOf:[{required:["filePath"]},{required:["base64","filename"]}]}},withCookies:{type:"boolean",description:"是否自动携带浏览器中该域名的 Cookie,默认 true",default:!0},responseType:{type:"string",enum:["json","text","auto"],description:'响应格式。auto: 自动检测(默认); json: 强制解析为 JSON; text: 返回原始文本。注意:auto 模式下若 Content-Type 为图片/音视频/PDF/压缩包等二进制类型,body 将以 base64 字符串返回,bodyType 为 "base64"',default:"auto"},timeout:{type:"number",description:"请求超时时间(毫秒),默认 30000(30 秒)",default:3e4}},required:["url"]}},{name:"browser_send_mtop_request",description:"通过已安装的请求协议能力,在当前浏览器页面上下文中发起 mtop API 请求,处理签名、Cookie token 和时间戳。适用于调试接口、验证返回数据和不同参数组合;目标页面需有对应登录态。",inputSchema:{type:"object",properties:{api:{type:"string",description:'mtop API 名称,例如: "mtop.trade.order.create"、"mtop.sample.view.render"。以 "mopen." 开头的会使用 mopen 签名算法'},data:{description:'请求数据(JSON 对象),即 mtop 请求中的 data 参数。例如: {"itemId": "12345"}'},version:{type:"string",description:'API 版本号,默认 "1.0"',default:"1.0"},method:{type:"string",enum:["GET","POST"],description:"HTTP 请求方法,默认 GET。POST 时 data 参数放在请求体中",default:"GET"},appKey:{type:"string",description:'appKey,默认 "12574478"'},env:{type:"string",enum:["prod","pre"],description:"请求环境。prod: 生产;pre: 预发。网关由已安装的协议能力提供。",default:"prod"},timeout:{type:"number",description:"请求超时时间(毫秒),默认 10000(10 秒)",default:1e4}},required:["api"]}},{name:"browser_set_rule",description:"添加或删除浏览器请求规则。enabled=false 且传 ruleId 时彻底删除规则;否则添加规则。扩展模式持久保存规则,CDP 模式的规则仅在当前控制会话生效。",inputSchema:{type:"object",properties:{ruleId:{type:"integer",minimum:1,description:"删除时必填:从 browser_get_rules 获取的规则 ID"},enabled:{type:"boolean",description:"省略时添加规则;false 时删除 ruleId 对应的规则"},actionType:{type:"string",enum:["redirect","block","allow","upgradeScheme","modifyHeaders"],description:"规则类型。redirect: 重定向请求到另一地址; block: 阻止请求; allow: 允许请求; upgradeScheme: 升级到 HTTPS; modifyHeaders: 修改请求/响应头"},filter:{type:"string",description:'URL 匹配规则(正则表达式)。例如: "^https://h5api\\.m\\.shop\\.com/.*" 匹配所有商城 h5api 请求'},redirectUrl:{type:"string",description:"【redirect 类型必填】重定向目标 URL。支持正则替换占位符 \\1 \\2 等(引用 filter 中的捕获组)"},requestHeaders:{type:"array",description:"【modifyHeaders 类型】要修改的请求头列表",items:{type:"object",properties:{header:{type:"string",description:'请求头名称,如 "x-custom-header"'},operation:{type:"string",enum:["set","append","remove"],description:"set: 设置/覆盖; append: 追加; remove: 删除"},value:{type:"string",description:"请求头值(remove 时可省略)"}},required:["header","operation"]}},responseHeaders:{type:"array",description:"【modifyHeaders 类型】要修改的响应头列表",items:{type:"object",properties:{header:{type:"string",description:"响应头名称"},operation:{type:"string",enum:["set","append","remove"],description:"set: 设置/覆盖; append: 追加; remove: 删除"},value:{type:"string",description:"响应头值(remove 时可省略)"}},required:["header","operation"]}},initiatorDomains:{type:"string",description:'发起请求的域名限制(逗号分隔)。只有从这些域名发起的请求才会匹配此规则。例如: "shop.com,tmall.com"'},resourceTypes:{type:"array",description:"资源类型限制;不填时使用当前浏览器模式的默认值",items:{type:"string",enum:["main_frame","sub_frame","script","stylesheet","image","xmlhttprequest","websocket","other"]}},priority:{type:"number",description:"规则优先级,数字越大优先级越高。多个规则匹配同一请求时,优先级高的生效。默认 1",default:1},description:{type:"string",description:"规则描述,便于识别规则用途"}},oneOf:[{required:["actionType","filter"],not:{required:["ruleId"]},properties:{enabled:{const:!0}}},{required:["ruleId","enabled"],properties:{enabled:{const:!1}}}]}},{name:"browser_get_rules",description:"查看当前浏览器模式的请求规则。扩展模式包含 Options 面板配置的持久规则;CDP 模式返回当前控制会话的请求头规则。",inputSchema:{type:"object",properties:{}}},{name:"browser_page_screenshot",description:'获取指定浏览器标签页的视觉截图,以 Base64 编码返回。支持全页截图或指定 CSS 选择器截取单个元素(类似 DevTools "Capture node screenshot")。适用于视觉判断、Canvas、跨域 iframe、UI 排查和保存快照;常规页面动作后优先读取其内置观察的增量结果,不要固定在每次动作后截图。',inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:"CSS 选择器。提供后只截取该元素区域(会自动滚动元素到可见区域),不提供则截取整个页面"},format:{type:"string",enum:["png","jpeg"],description:"截图格式。png: PNG 格式(无损,默认); jpeg: JPEG 格式(有损压缩,体积更小)",default:"png"},quality:{type:"number",description:"JPEG 质量(仅 format 为 jpeg 时有效)。范围 0-100,默认 80。数值越高质量越好但文件越大",default:80}},required:["tabId"]}},{name:"browser_launch",description:"启动浏览器实例。默认使用本地独立 Chrome;传已注册的 Provider ID 时,把该 Provider 声明的创建参数放在 providerOptions。配对实例会直接返回 pairing URL。具体 Provider 用法可运行 mearl <providerId> 查看。",inputSchema:{type:"object",properties:{name:{type:"string",description:"本地实例名称;使用默认 local Provider 时必填"},provider:{type:"string",description:"浏览器提供方,默认 local;也可传已注册的外部 Provider ID"},providerOptions:{type:"object",additionalProperties:!0,description:"所选外部 Provider 声明的结构化创建参数"},headless:{type:"boolean",description:"本地 Provider 是否使用 headless=new,默认 true"},userAgentMode:{type:"string",enum:["default","desktop"],description:"本地 UA 模式:default 使用默认 UA;desktop 使用匹配本机 Chrome 的 UA",default:"default"},persistent:{type:"boolean",description:"本地实例关闭后是否保留独立 Profile,默认 false",default:!1},url:{type:"string",description:"新浏览器打开的初始 URL"},executablePath:{type:"string",description:"Chrome 可执行文件路径;省略时自动发现,也可用环境变量配置"},copyCookieDomains:{oneOf:[{type:"array",items:{type:"string"}},{type:"string",minLength:1},{type:"object",properties:{presets:{type:"array",items:{type:"string",minLength:1}},domains:{type:"array",items:{type:"string"}}},additionalProperties:!1}],description:"从控制浏览器复制 Cookie,可传域名数组、已安装能力提供的范围名称,或 {presets, domains} 组合。保留 HttpOnly/Secure/SameSite/过期时间等属性;所需域名权限仍由宿主管理。"}},anyOf:[{required:["name"]},{required:["provider"]}]}},{name:"browser_close",description:"关闭一个 Provider 托管浏览器;持久化数据默认按 Provider 策略保留,deleteProfile=true 时一并删除。名称有歧义时使用完整 browserId。",inputSchema:{type:"object",properties:{browser:{type:"string",description:"browser_launch 返回的 browserId 或实例名称"},deleteProfile:{type:"boolean",description:"是否强制删除 Provider 持久化数据,默认 false",default:!1}},required:["browser"]}},{name:"browser_release",description:"仅在用户明确要求结束调试、退出接管或清理会话资源时调用,不作为普通任务收尾。它会释放 debugger/CDP 控制和会话级临时效果,后续浏览器操作可自动重新建立控制;Provider 实例的生命周期操作由 Browser Manager 处理。",inputSchema:{type:"object",properties:{}}},{name:"browser_tab_open",description:"打开或按 URL 规则复用标签页。默认新建并等待加载完成;reuse=prefer 可优先复用,reuse=require 可限制为只复用。响应的 opened/reused 可用于判断流程结束时是否应关闭该 Tab。",inputSchema:{type:"object",properties:{url:{type:"string",description:"要打开的页面 URL"},active:{type:"boolean",description:"是否激活目标标签页。默认 false;扩展免打扰默认开启,使用后台焦点模拟,关闭后才切换前台。activation.mode 区分 background/foreground,visibilityState 不代表窗口在前台",default:!1},openerTabId:{type:"number",description:"来源标签页 ID。侧边栏对话继续任务时传入,用于把新开或复用的标签页关联到同一对话"},closeExisting:{type:"boolean",description:"打开前是否先关闭 Agent 受控的已有标签页。默认 false",default:!1},group:{type:"string",description:"把新标签页加入指定标题的标签页分组(同窗口同名分组存在则加入,否则新建)。仅扩展模式支持,CDP 模式忽略"},reuse:{type:"string",enum:["never","prefer","require"],description:"never 始终新建;prefer 匹配到则复用、否则新建;require 只允许复用。默认 never",default:"never"},match:{type:"object",description:"复用标签页时的 URL 匹配规则",properties:{urlPattern:{type:"string",description:"支持 * 的完整 URL glob;省略时精确匹配 url"},ignoreSearch:{type:"boolean",description:"匹配时是否忽略 URL query,默认 false"},ignoreHash:{type:"boolean",description:"匹配时是否忽略 URL hash,默认 false"},onMultiple:{type:"string",enum:["error","first"],description:"匹配多个 Tab 时默认报错;first 显式取第一个"}}},restoreFocusOnClose:{type:"boolean",description:"新建 active Tab 关闭后是否恢复原活动标签页,默认 false",default:!1},emulation:{type:"object",description:"开 tab 即进入移动端模拟态,等价于随后立即调用 browser_set_device_emulation,但在导航前生效。deviceShell=true 时首屏就在 iframe WebView 与设备系统外壳中渲染。字段规则一致(无 enabled/reload)。",properties:{preset:{type:"string",enum:[...BROWSER_DEVICE_PRESET_NAMES2],description:"内置设备预设,一键提供 viewport/DPR/UA。当前机型在前,旧机型 ID 继续兼容;可与下面字段组合,显式字段覆盖预设值"},width:{type:"number",description:"视口宽度(覆盖 preset)"},height:{type:"number",description:"视口高度(覆盖 preset)"},deviceScaleFactor:{type:"number",description:"devicePixelRatio(覆盖 preset)"},scale:{type:"number",exclusiveMinimum:0,description:"画面视觉比例,不改变视口 CSS 尺寸或 devicePixelRatio;必须为有限正数,默认 1"},mobile:{type:"boolean",description:"是否启用移动渲染模式。默认从 preset 推断,无 preset 默认 true"},userAgent:{type:"string",description:"自定义 User-Agent(覆盖 preset)。无 preset 时必填"},orientation:{type:"string",enum:["portrait","landscape"],description:"横竖屏,landscape 会对调宽高。默认 portrait"},touch:{type:"boolean",description:"是否启用触摸事件并把鼠标事件转成 touch。默认从 preset 推断;无 preset 时跟随 mobile"},deviceShell:{type:"boolean",description:"是否使用 iframe WebView 并渲染顶部状态栏与底部操作区,默认 false"},splitScreen:{type:"boolean",description:"是否在横屏设备外壳中将首页与业务页分置左右 WebView;仅与 appProfile、deviceShell=true、orientation=landscape 同时生效,默认 false"}}},appProfile:{type:"string",description:"开 tab 即注入 App 客户端环境与 JSBridge(等价于随后调用 browser_set_app_profile,但在首次导航前生效)。不创建根 iframe;需要设备外壳时同时传 emulation.deviceShell=true"},os:{type:"string",enum:["ios","android"],description:"与 appProfile 配合;容器系统,默认 ios"},bridgeConfig:{type:"object",description:"与 appProfile 配合;声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}},不执行配置脚本"}},required:["url"]}},{name:"browser_tab_close",description:"关闭指定的浏览器标签页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"要关闭的标签页 ID(从 tab_open 或 tab_list 获取)"}},required:["tabId"]}},{name:"browser_get_capabilities",description:"只读查询当前目标浏览器的已安装 App、动作、设备预设、限制与 Skill/帮助入口。app 可指定目录中的完整 ID,按需获取桥方法与设置详情;不打开页面或启用模拟。支持 action 不代表已取得页面权限或真实授权。",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0},inputSchema:{type:"object",properties:{app:{type:"string",description:"可选,查询已安装 App ID 的详细能力"},browser:{type:"string",description:"目标浏览器 ID 或唯一名称;省略沿用当前选择"}}}},{name:"browser_tab_list",description:"列出当前浏览器窗口中所有标签页的信息,包括 ID、URL、标题和是否活动。",inputSchema:{type:"object",properties:{}}},{name:"browser_tab_group",description:"将同一窗口中的标签页加入分组,或取消分组并保留标签页。仅扩展模式支持。",inputSchema:{type:"object",properties:{tabIds:{type:"array",items:{type:"number"},description:"标签页 ID 列表,分组最多 100 个,取消分组最多 1000 个"},title:{type:"string",description:"分组标题;取消分组时省略"},ungroup:{type:"boolean",description:"为 true 时取消分组并保留标签页"}},required:["tabIds"]}},{name:"browser_page_click",description:"点击页面元素;selector、text、point 三种定位方式必须且只能提供一种。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:`原生 CSS 选择器(如 "[aria-label='提交']"、"#login-btn")或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e3",必须带 "@" 前缀)。注意字段名是 "selector" 而非 "ref"。不支持 :has-text/:visible 等 Playwright 扩展语法。与 text/point 互斥。`},text:{type:"string",description:'按可见文本(accessibility name)定位。例如 "退款明细"。匹配到多个时会报错并列出候选——可加 role 或 exact:true 收敛,或用 page_snapshot 拿 @ref。与 selector/point 互斥。'},point:{type:"object",description:"按视口坐标点击(CSS 像素,左上角为原点)。selector 和 text 都不适用时使用。与 selector/text 互斥。",properties:{x:{type:"number",description:"横坐标(CSS 像素)"},y:{type:"number",description:"纵坐标(CSS 像素)"}},required:["x","y"]},frameId:{type:"string",description:"仅扩展后端:CSS/text 查询或 active-frame 坐标所属的 frame;省略时容器使用当前业务 frame"},coordinateSpace:{type:"string",enum:["outer-viewport","active-frame"],description:"仅配合 point;默认 outer-viewport。仅扩展后端支持 active-frame,会换算 iframe 偏移与缩放"},role:{type:"string",description:'配合 text 使用,按 AX role 过滤消歧(如 "button"、"link"、"heading"、"StaticText")'},exact:{type:"boolean",description:"配合 text 使用,默认 true 精确匹配;false 时按子串匹配",default:!0},scope:{type:"string",description:'配合 text 使用,把 AX 文本匹配限制在指定 CSS 元素或 snapshot ref(如 "@e12")子树内'},clickMode:{type:"string",enum:["auto","dom","mouse","touch"],description:"默认 auto:可见页使用匹配设备的可信输入,隐藏页使用 DOM;dom/mouse/touch 可强制指定派发方式",default:"auto"},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId"]}},{name:"browser_page_drag",description:"连续拖动页面元素或视口坐标,适用于轮播图、滑块、Canvas 手势和拖放。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},from:{description:"拖动起点:CSS/@eN selector,或 {x,y} 视口坐标(CSS 像素)",anyOf:[{type:"string"},{type:"object",properties:{x:{type:"number"},y:{type:"number"}},required:["x","y"]}]},to:{description:"拖动终点:CSS/@eN selector,或 {x,y} 视口坐标(CSS 像素)",anyOf:[{type:"string"},{type:"object",properties:{x:{type:"number"},y:{type:"number"}},required:["x","y"]}]},dragMode:{type:"string",enum:["auto","dom","mouse","touch"],description:"默认 auto:可见页使用匹配设备的可信输入,隐藏页使用 DOM;dom/mouse/touch 可强制指定派发方式",default:"auto"},durationMs:{type:"number",minimum:0,maximum:5e3,description:"拖动持续时间(毫秒),默认 400;内部自动分段移动",default:400},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","from","to"]}},{name:"browser_page_type",description:"向输入框填写文本,兼容 React 等框架的受控组件。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:'原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e6",必须带 "@" 前缀)。字段名是 "selector"。不支持 :has-text/:visible 等 Playwright 扩展。'},text:{type:"string",description:"要输入的文本内容"},clearFirst:{type:"boolean",description:"是否先清空输入框原有内容。默认 true",default:!0},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","selector","text"]}},{name:"browser_page_scroll",description:'按方向滚动页面或指定容器;页面根不可滚动时自动发现活动滚动区,containerPolicy="nearest" 可从子节点解析最近的可滚动祖先。',inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},direction:{type:"string",enum:["up","down","top","bottom"],description:"滚动方向"},distance:{type:"number",description:"滚动距离(像素),仅 up/down 方向有效。默认 600",default:600},selector:{type:"string",description:'目标滚动容器的原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e6",必须带 "@" 前缀);不传时滚动页面。'},containerPolicy:{type:"string",enum:["self","nearest"],description:"默认 self,要求 selector 本身可滚动;nearest 会在其不可滚动时使用最近的可滚动祖先"},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","direction"]}},{name:"browser_page_hover",description:"将鼠标悬停在页面元素上。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:'原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e1",必须带 "@" 前缀)。字段名是 "selector"。不支持 :has-text/:visible 等 Playwright 扩展。'},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","selector"]}},{name:"browser_page_eval",description:"在页面默认上下文执行最小 JavaScript 表达式,作为结构化工具无法表达时的补充。默认返回 { result };observe 对象启用观察并返回 { action, observation };仅开启 diagnostics 时返回 { action, diagnostics },diagnostics=false 不启用包装。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},expression:{type:"string",description:"要执行的 JavaScript 表达式"},frameId:{type:"string",description:"browser_page_frames 返回的目标 frame ID,扩展/CDP 均支持;省略时容器/设备外壳使用当前业务 frame,普通页面使用主 frame。读取外层容器时显式传主 frame ID"},awaitPromise:{type:"boolean",description:"是否等待表达式返回的 Promise,默认 true",default:!0},observe:{type:"object",properties:OBSERVE_INPUT_SCHEMA.properties,description:"仅在表达式会修改页面且需要观察结果时显式传入;不传时轻量执行并直接返回结果"},diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","expression"]}},{name:"browser_page_inspect",description:"查询 DOM 元素的原生/ARIA 控件状态、数量、边框盒、计算样式、命中遮挡、溢出尺寸和最近滚动容器;也可读取 DevTools 当前选区或直接扫描全页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:'原生 CSS、page_snapshot 返回的 ref(如 "@e8"),或 DevTools Elements 当前选区 "$0";全页溢出诊断时可省略'},filter:{type:"string",enum:["all","overflowing","horizontal-overflow","vertical-overflow","scrollable"],description:"结果过滤;省略 selector 时必须指定非 all 的过滤条件"},styles:{type:"array",items:{type:"string"},description:"要返回的计算样式属性;默认 display/position/box-sizing/overflow-x/overflow-y"},maxResults:{type:"number",minimum:1,maximum:100,description:"最多返回的明细数,默认 20;未触发 scanTruncated 时 count 为完整命中数"},includeOuterHTML:{type:"boolean",description:"是否返回 outerHTML(最多 3000 字符);$0 默认 true,其他目标默认 false"}},required:["tabId"]}},{name:"browser_page_snapshot",description:"获取带 @ref 的页面结构树;ref 可直接用于操作,内部节点映射不输出。默认使用无障碍树,AX 信息缺失时可显式读取渲染 DOM。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},depth:{type:"number",description:"无障碍树的最大深度。默认 15,增大可获取更深层元素",default:15},mode:{type:"string",enum:["full","interactive","viewport","dom"],description:"full 为完整 AX 树;interactive 只保留当前视口内的 AX 语义控件,无控件时回退到 AX viewport;viewport 为当前可视 AX 树;dom 显式返回实际渲染文本、原生控件、显式 role 和高置信 clickable 节点。默认 full"},rootSelector:{type:"string",description:"只获取指定 CSS 元素的局部子树,可与 mode 组合;与 rootRef 互斥"},rootRef:{type:"string",description:'以已有 snapshot ref(如 "@e8")为根获取局部子树'},ancestorDepth:{type:"number",description:"rootRef 向上扩展的 DOM 祖先层数,默认 0,最大 20",minimum:0,maximum:20},query:{type:"object",description:"服务端按 name / role 过滤当前模式的树,只保留命中节点及祖先路径",properties:{text:{type:"string",description:"要匹配的 accessibility name"},role:{type:"string",description:"要匹配的 AX role"},exact:{type:"boolean",description:"text 默认精确匹配;false 时按子串匹配"}}},maxNodes:{type:"number",description:"最多输出节点数;超出时保留首尾。0 表示不限制"},maxChars:{type:"number",description:"最多输出字符数,默认 60000;超出时保留首尾。0 表示不限制"}},required:["tabId"]}},{name:"browser_page_press",description:"在页面中按下键盘按键或组合键。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},key:{type:"string",description:"按键名称。支持:Enter, Tab, Escape, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown, Space"},modifiers:{type:"array",items:{type:"string"},description:'修饰键数组,如 ["Alt", "Shift", "Control", "Meta"]'},pressMode:{type:"string",enum:["auto","dom","keyboard"],description:"派发模式;auto 默认在隐藏页降级为 DOM 键盘事件"},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","key"]}},{name:"browser_page_wait",description:"独立等待接口:仅用于没有前置动作时等待指定时间、已知 selector 状态、可见文本或页面 condition。四种模式必须且只能提供一个;点击、输入后的异步稳定判断由页面交互工具内置的观察完成。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},time:{type:"number",description:"固定等待毫秒数,与 selector/text/condition 四选一"},selector:{type:"string",description:"CSS 选择器,与 time/text/condition 四选一"},state:{type:"string",enum:["attached","detached","visible","hidden"],description:"selector 的目标状态,默认 attached",default:"attached"},text:{type:"string",description:"等待页面出现的可见文本,与 time/selector/condition 四选一"},exact:{type:"boolean",description:"text 是否精确匹配,默认 false",default:!1},condition:{type:"string",description:"在页面主上下文轮询的 JavaScript 表达式,返回 truthy 时结束,支持 Promise;与 time/selector/text 四选一"},timeout:{type:"number",description:"等待超时时间(毫秒),默认 10000ms",default:1e4},interval:{type:"number",description:"selector/condition 的轮询间隔(毫秒),默认 200ms",default:200}},required:["tabId"]}},{name:"browser_page_navigate",description:'在指定标签页中导航到 URL、设置 refresh:true 重新加载,或用 history:"back"|"forward" 沿浏览历史移动。三种模式互斥,返回最终 URL 和标题。',inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},url:{type:"string",description:"要导航到的 URL;与 refresh/history 互斥"},refresh:{type:"boolean",description:"为 true 时直接重新加载当前页面;与 url/history 互斥",default:!1},history:{type:"string",enum:["back","forward"],description:"沿当前标签页浏览历史后退或前进;与 url/refresh 互斥"}},required:["tabId"]}},{name:"browser_page_upload",description:'向 <input type="file"> 元素上传一个或多个本地文件。',inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:'原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e5",必须带 "@" 前缀),用于定位 <input type="file"> 元素。字段名是 "selector"。'},filePaths:{type:"array",items:{type:"string"},description:'要上传的本地文件路径数组,如 ["/Users/me/photo.jpg"]'},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","selector","filePaths"]}},{name:"browser_page_frames",description:"列出主 frame 和 iframe,返回可供 browser_page_eval 使用的 frameId。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"}},required:["tabId"]}},{name:"browser_set_device_emulation",description:"把目标标签页切换为移动端模拟态:视口尺寸 / DPR / UA / 触摸事件按指定设备生效,并可独立调整视觉比例。deviceShell=true 时把业务页放入 iframe WebView,并在外层渲染顶部状态栏与底部操作区;false/省略时保持纯 CDP 模拟。作用域仅限该 tab,启用后默认 reload,enabled=false 清除模拟与设备外壳。",inputSchema:{type:"object",properties:{enabled:{type:"boolean",description:"必填。true=启用模拟(按 preset/参数生效),false=清除模拟回到桌面态"},preset:{type:"string",enum:[...BROWSER_DEVICE_PRESET_NAMES2],description:"内置设备预设,一键提供 viewport/DPR/UA。当前机型在前,旧机型 ID 继续兼容;可与下面的字段组合,显式字段会覆盖预设值"},width:{type:"number",description:"视口宽度(覆盖 preset)"},height:{type:"number",description:"视口高度(覆盖 preset)"},deviceScaleFactor:{type:"number",description:"devicePixelRatio(覆盖 preset)"},scale:{type:"number",exclusiveMinimum:0,description:"画面视觉比例,不改变视口 CSS 尺寸或 devicePixelRatio;必须为有限正数,默认 1"},mobile:{type:"boolean",description:"是否启用移动渲染模式(影响 hover/pointer media query、viewport meta 行为)。默认从 preset 推断,无 preset 默认 true"},userAgent:{type:"string",description:"自定义 User-Agent(覆盖 preset)"},orientation:{type:"string",enum:["portrait","landscape"],description:"横竖屏,landscape 会对调宽高。默认 portrait"},touch:{type:"boolean",description:"是否启用触摸事件并把鼠标事件转成 touch。默认从 preset 推断;无 preset 时跟随 mobile"},deviceShell:{type:"boolean",description:"是否使用 iframe WebView 并渲染顶部状态栏与底部操作区,默认 false"},splitScreen:{type:"boolean",description:"是否在横屏 App 容器中将首页与业务页分置左右 WebView;仅在当前已启用 App 档案、deviceShell=true、orientation=landscape 时生效,默认 false"},reload:{type:"boolean",description:"启用模拟后是否重载页面(让 JS 读到新的 navigator.userAgent / window.innerWidth)。默认 true"},tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"}},required:["tabId","enabled"]}},{name:"browser_set_app_profile",description:"设置目标标签页的 App 客户端 UA;可用 App ID、限制和说明通过 browser_get_capabilities 查询。完整环境变量、JSBridge、桥协议和 MTop 页面接口环境由已安装能力提供。传 emulation 时由同一个调用联动设备模拟与 iframe 系统外壳;省略 emulation 时不改变设备状态。",inputSchema:{type:"object",properties:{enabled:{type:"boolean",description:"必填。true=启用容器模拟,false=清除并还原设备模拟"},profile:{type:"string",description:"容器档案名(enabled=true 时必填),决定 UA/桥对象/环境判断特征"},os:{type:"string",enum:["ios","android"],description:"容器系统,默认 ios"},refreshDefinition:{type:"boolean",description:"立即采用最新档案定义,保留用户显式设置"},lockDefinition:{type:"boolean",description:"固定当前定义;默认在下次刷新或文档导航时自动更新"},appVersion:{type:"string",description:"覆盖档案默认 App 版本号"},deviceModel:{type:"string",description:"Android 机型名(拼入 UA 与 __DEVICE_MODEL__)"},bridgeConfig:{type:"object",description:"声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}};扩展本地同档案配置会先合并"},mtopEnv:{type:"string",enum:["default","prod","pre"],description:"可选 MTop 页面接口环境。default 关闭环境改写;省略时保持当前设置。仅作用于目标 tab,扩展模式与该 tab 的快捷设置共享。"},emulation:{type:"object",description:"可选设备联动参数;字段覆盖档案推荐设备,空对象使用推荐设备,deviceShell 默认 true。省略时不设置或清除设备。",properties:{preset:{type:"string",enum:[...BROWSER_DEVICE_PRESET_NAMES2]},width:{type:"number"},height:{type:"number"},deviceScaleFactor:{type:"number"},scale:{type:"number",exclusiveMinimum:0},mobile:{type:"boolean"},userAgent:{type:"string"},orientation:{type:"string",enum:["portrait","landscape"]},touch:{type:"boolean"},deviceShell:{type:"boolean",description:"是否使用根 iframe WebView 并显示系统栏;在 emulation 内默认 true"},splitScreen:{type:"boolean",description:"是否在横屏设备外壳中将首页与业务页分置左右 WebView;仅与 deviceShell=true、orientation=landscape 同时生效,默认 false"}}},reload:{type:"boolean",description:"应用/清除后是否重载页面,默认 true"},tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"}},required:["tabId","enabled"]}},{name:"browser_set_timezone",description:"覆盖目标标签页的时区,作用域仅限该 tab,立即影响 Date / Intl 等页面时间 API。timezone 使用 IANA 时区标识(如 Asia/Shanghai、America/New_York);传空字符串恢复浏览器默认时区。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},timezone:{type:"string",description:"IANA 时区标识;空字符串表示清除覆盖"}},required:["tabId","timezone"]}},{name:"browser_get_cookie",description:"从目标浏览器读取一个指定非分区 Cookie,用于验证页面分支、实验或当前账号标识。必须明确传 Cookie 名,不支持列举全部 Cookie;HttpOnly Cookie 会被拒绝,禁止读取认证 Token。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"可选;指定标签页的 Cookie 存储区,省略时使用浏览器默认存储区"},name:{type:"string",description:"Cookie 名称"},url:{type:"string",description:"Cookie 查询 URL;未传 tabId 时必填,省略时使用指定标签页 URL"},domain:{type:"string",description:"可选精确域过滤,只允许 Cookie 查询 URL 的 host 或它的父域"},path:{type:"string",description:"可选精确 path 过滤"}},required:["name"],anyOf:[{required:["url"]},{required:["tabId"]}]}},{name:"browser_set_cookie",description:"在目标浏览器设置一个指定非分区 session Cookie。url 与 tabId 至少传一个;未传 tabId 时使用浏览器默认存储区。domain 只允许目标 URL 的 host 或它的父域。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"可选;指定标签页的 Cookie 存储区,reload=true 时必填"},url:{type:"string",description:"Cookie 目标 URL;未传 tabId 时必填,省略时使用指定标签页 URL"},name:{type:"string",description:"Cookie 名称"},value:{type:"string",description:"Cookie 值,可传空字符串;空字符串不会删除 Cookie"},domain:{type:"string",description:"Cookie 域,默认目标 URL 的 host;只允许目标 host 或它的父域"},path:{type:"string",description:"Cookie path,默认 /"},reload:{type:"boolean",description:"设置后是否刷新指定 tabId,默认 false;true 时必须传 tabId"}},required:["name","value"],anyOf:[{required:["url"]},{required:["tabId"]}]}},{name:"browser_run_actions",description:"批量顺序执行多个无需中间判断的原子操作,适合 hover→click 等必须紧密连续的序列。步骤内的页面动作不带内置观察;遇到第一个失败步骤立即停止,且不能嵌套 run_actions。需要条件、循环或处理返回数据时可用 browser_run_code;需要模型理解页面时使用逐步页面工具。不要用本工具固化「点击→等待→截图」循环。",inputSchema:{type:"object",properties:{actions:{type:"array",description:"要依次执行的 action 列表",items:{type:"object",properties:{action:{type:"string",description:"action 名称(不带 browser_ 前缀),如 page_hover、page_click;仅组合无需中间判断的步骤"},data:{type:"object",description:"该 action 的参数(与单独调用时相同)"}},required:["action"]}},tabId:{type:"number",description:"所有步骤共享的目标标签页 ID。步骤自身指定的 tabId 优先级更高"}},required:["tabId","actions"]}},{name:RUN_CODE_TOOL_NAME,description:'在 MCP server 宿主的独立 Node.js 进程执行 JavaScript,预注入 mearl SDK,支持顶层 await、条件、循环和数据处理。浏览器调用用 mearl.pageClick({tabId,selector}) 等现有 SDK 方法或 mearl.invoke(action,payload,options?);Skill 命令用 mearl.invokePlugin(name,{command,input},options?)。用 console.log(await mearl.help("pageClick")) 查共享命令帮助,help({plugin,command?}) 查插件帮助,mearl.structure(value) 查看有界结果结构。使用 console.log 输出必要结果,await 所有 SDK 调用。JS 变量每次重建;session 和 tabId 可跨调用复用。DOM 代码使用 mearl.pageEval。脚本拥有宿主 Node 权限,超时或取消不能撤销已派发操作。',inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript 源码,最大 1 MiB;使用 await import() 加载模块"},browser:{type:"string",description:"目标浏览器 ID 或唯一名称"},session:{type:"string",description:"首次调用 tab_open/page_snapshot 等传 new;后续复用 sessionId"},timeoutSec:{type:"number",exclusiveMinimum:0,maximum:2147483,description:"整个脚本的执行时限,默认 60 秒"}},required:["code"]}},{name:"browser_list",description:"列出所有浏览器。返回普通浏览器和 Provider 托管浏览器的 browserId、名称、类型、连接状态、稳定元数据及当前默认目标,但不返回带临时凭据的浏览器访问地址。只有 status=connected 的浏览器可用于后续操作。",inputSchema:{type:"object",properties:{}}},{name:"browser_select_browser",description:"选择后续所有浏览器操作的默认目标浏览器(有多个浏览器连接时)。传入 browser_list 返回且 status=connected 的 browserId 或名称即可锁定;传空字符串则清除锁定,回到自动模式(操作最近聚焦的浏览器)。",inputSchema:{type:"object",properties:{browser:{type:"string",description:"目标浏览器的 browserId / 名称;空字符串表示清除锁定、恢复自动选择"}},required:["browser"]}},{name:"browser_request_domain_permission",description:"申请访问指定域名的权限。调用后浏览器会弹出确认窗口让用户授权(90 秒超时),返回 granted 表示是否已获得授权。扩展模式下发送非内置域的 HTTP 请求(browser_send_request)前需先获得用户授权。",inputSchema:{type:"object",properties:{domain:{type:"string",description:"需要授权的域名,如 example.com"}},required:["domain"]}}];server.setRequestHandler(ListToolsRequestSchema,async()=>({tools:tools.map(tool=>tool.name===PLUGIN_INVOKE_TOOL_NAME||tool.name===RUN_CODE_TOOL_NAME?tool:{...tool,inputSchema:{...tool.inputSchema,...tool.name==="browser_page_upload"?{required:(tool.inputSchema.required??[]).filter(field=>field!=="filePaths")}:{},properties:{...tool.inputSchema.properties,...tool.name==="browser_release"?{closeCreatedTabs:{type:"boolean"},keepTabIds:{type:"array",items:{type:"number"}},preserveEnvironment:{type:"boolean"},keepArtifactIds:{type:"array",items:{type:"string"}}}:{},...tool.name==="browser_page_upload"?{files:{type:"array",items:{type:"object",properties:{filePath:{type:"string"},artifactId:{type:"string"}}}}}:{},session:{type:"string",description:"首次 tab_open/page_snapshot 传 new;后续复用返回的 session.sessionId"}}}})})),server.setRequestHandler(CallToolRequestSchema,async(request,extra)=>{let{arguments:args}=request.params,name=request.params.name==="browser_capture_checkpoint"?"browser_tab_checkpoint":request.params.name;try{if(name===RUN_CODE_TOOL_NAME){let input=args??{},result2=await executeScript(input.code,{...input.browser?{browser:input.browser}:{},...input.session?{session:input.session}:{},...input.timeoutSec!==void 0?{executionTimeoutSec:input.timeoutSec}:{},signal:extra?.signal,source:"mcp"}),tooLarge=Buffer.byteLength(JSON.stringify(result2))>=RESPONSE_SIZE_MAX;return{content:formatResponseWithSizeCheck(result2,name,input),...result2.success&&!tooLarge?{}:{isError:!0}}}if(name!==PLUGIN_INVOKE_TOOL_NAME&&!(name in MCP_TOOL_ACTIONS))throw new Error(`Unknown tool: ${name}`);let result;if(name===PLUGIN_INVOKE_TOOL_NAME)result=await invokePluginTool(args,client.invokePlugin);else{let{session,outputPath,...payload}=args??{};if(name==="browser_set_mock"&&payload.payloadFile){if(!existsSync(payload.payloadFile))throw new Error(`Payload file not found: ${payload.payloadFile}`);let fileData=JSON.parse(readFileSync(payload.payloadFile,"utf-8"));for(let field of["tabId","apiName","mockData","fields","enabled","duration","conditions"])fileData[field]!==void 0&&(payload[field]=fileData[field]);delete payload.payloadFile}let browser=name==="browser_get_capabilities"?payload.browser:void 0;if(name==="browser_get_capabilities"&&delete payload.browser,result=await client.invoke(MCP_TOOL_ACTIONS[name],payload,{...session?{session}:{},...browser?{browser}:{}}),name==="browser_page_download"&&outputPath&&(await client.saveArtifact(result.download,outputPath,session?{session}:{}),result={...result,outputPath}),name==="browser_page_screenshot")return{content:[{type:"image",data:result.data,mimeType:result.meta?.format==="jpeg"?"image/jpeg":"image/png"},{type:"text",text:JSON.stringify({meta:result.meta,...result.session?{session:result.session}:{}})}]};if(name==="browser_run_actions"){let screenshots=(result.results??[]).filter(step=>step.success&&step.action==="page_screenshot"&&step.data?.data);if(screenshots.length)return{content:[...screenshots.map(step=>({type:"image",data:step.data.data,mimeType:step.data.meta?.format==="jpeg"?"image/jpeg":"image/png"})),...formatResponseWithSizeCheck({...result,results:result.results.map(step=>step.action==="page_screenshot"&&step.success?{...step,data:{meta:step.data?.meta}}:step)},name,args)],...result.failedStep!==void 0?{isError:!0}:{}}}}return{content:formatResponseWithSizeCheck(result,name,args),...result?.action?.success===!1||result?.failedStep!==void 0?{isError:!0}:{}}}catch(error2){return log(`Error executing tool ${name}:`,error2),{content:[{type:"text",text:`Error: ${error2 instanceof Error?error2.message:String(error2)}`}],isError:!0}}});let transport=new StdioServerTransport;await server.connect(transport),log("MCP Server started and ready")}process.on("uncaughtException",error2=>{console.error("[MCP Server] Uncaught exception:",error2),process.exit(1)});process.on("unhandledRejection",error2=>{console.error("[MCP Server] Unhandled rejection:",error2),process.exit(1)});main().catch(error2=>{console.error("[MCP Server] Failed to start:",error2),process.exit(1)});
|
|
118
|
+
`),log("Starting Mearl MCP Server..."),log("MCP Server initialized, will connect to Chrome Extension when tools are called");let server=new Server({name:"mearl",version:MCP_SERVER_VERSION},{capabilities:{tools:{}},instructions:"取得 tabId 后持续显式复用,默认后台操作。首次进入或导航后取一次 browser_page_snapshot,按 viewport、局部根节点或 query 控制范围;AX 稀疏时才用 dom,每次快照只用本次新 ref。交互默认返回 { action, observation },先检查 action.success 再核验业务效果;precondition 表示未派发,没有 observation/diagnostics;dispatch-uncertain 表示可能已生效,先检查 action.attempt 与可用观察或最小快照,避免直接重试。delta 优先复用 effects 中的 ref/selector,changed=true 且 effects 为空不表示失败;navigation 的 ready 表示就绪,openedTabs 已提供可操作 tabId。增量缺少下一步目标、ref 失效、需要新滚动视口或 fullSnapshotRecommended 提示时补最小快照,不固定追加 wait/snapshot/screenshot。布局和遮挡用 inspect,视觉任务用 screenshot,结构化工具无法表达时才用最小 page_eval。observe:false 且未开启 diagnostics 时返回裸动作结果,没有 action/observation;仅开启诊断时返回 { action, diagnostics },诊断不等待 DOM/导航稳定。page_eval 默认返回 { result }。run_actions 只用于无需中间判断的紧密序列,步骤没有内置观察。按用户目标核验终态;browser_release 只在用户要求结束接管或清理会话时调用。"}),OBSERVE_INPUT_SCHEMA={type:["object","boolean"],default:{},description:"默认开启 DOM/相关请求/导航稳定观察,返回 { action, observation }。传 false 且未开启 diagnostics 时返回裸动作结果,没有 action/observation;开启 diagnostics 时返回 { action, diagnostics }。关闭观察不等待 DOM/导航稳定",properties:{quietMs:{type:"number",description:"最后一次 DOM 变化后等待的稳定窗口,默认 100ms"},firstChangeTimeoutMs:{type:"number",description:"没有发生 DOM 变化时最多等待多久,默认 500ms"},timeoutMs:{type:"number",description:"整个观察阶段的最大时间,默认 3000ms"},navigationGraceMs:{type:"number",description:"低信息量点击或按键后等待导航开始的基础宽限时间,默认 1000ms;若仍有网络活动会自动延长,有明确 effects 时不等待"},navigationTimeoutMs:{type:"number",description:"导航开始后等待页面就绪的最大时间,默认 15000ms"},networkIdleMs:{type:"number",description:"文档加载完成且相关 XHR/Fetch/Protocol 请求归零后继续保持静默的时间,默认 500ms,用于跳过业务骨架屏"},contentReadyAfterMs:{type:"number",description:"动作开始后允许用结构稳定兜底的保护期,默认 min(5000, navigationTimeoutMs / 2),并限制在导航超时之前;保护期内优先等待网络静默"}}},DIAGNOSTICS_INPUT_SCHEMA={type:["object","boolean"],default:!1,description:"默认关闭;true 返回动作期间新增 error logs/业务 requests,对象可自定义通道并显式开启 events。与 observe 独立;关闭观察时返回 { action, diagnostics },precondition 失败省略 diagnostics",properties:{logs:{type:["object","boolean"],properties:{level:{type:"string",enum:["log","warn","error","info","all"]},limit:{type:"number",default:100},filter:{type:"string"}}},requests:{type:["object","boolean"],properties:{source:{type:"string",enum:["protocol","requests","all"]},count:{type:"number",default:100},filter:{type:"string"},includeBody:{type:"boolean",default:!1},includeHeaders:{type:"boolean",default:!1},maxBodySize:{type:"number",description:"单个请求/响应体的最大字符数"},fields:{type:"array",items:{type:"string"},maxItems:100,description:"从响应体提取指定字段路径,如 data.list[0].id"},keysOnly:{type:"boolean",description:"只返回数据结构,不返回叶子值"}}},events:{type:["object","boolean"],properties:{source:{type:"string",enum:["rum","aplus","arms","all"]},event_type:{type:"string"},filter:{type:"string"},limit:{type:"number",default:100},includeRaw:{type:"boolean",default:!1}}}}},tools=[{name:"browser_control",description:"交给用户操作当前会话;用户在 Mearl 中交还后重新观察页面",inputSchema:{type:"object",properties:{operation:{type:"string",enum:["handoff","resume"]},reason:{type:"string"},tabId:{type:"number"}},required:["operation","session"]}},{name:"browser_page_download",description:"先监听再点击并等待下载,outputPath 可将文件分块保存到 MCP 宿主",inputSchema:{type:"object",properties:{tabId:{type:"number"},trigger:{type:"object"},url:{type:"string"},timeout:{type:"number"},outputPath:{type:"string"}},required:["tabId","trigger"]}},{name:PLUGIN_INVOKE_TOOL_NAME,description:"调用当前 MCP Server 宿主上的 Mearl Skill 插件,对应 CLI 的 mearl <plugin>。已登记在能力目录中的缺失插件可按需安装。插件名、子命令、认证方式和 input 契约以对应 Skill 为准;Node 插件使用当前宿主环境,浏览器操作使用当前选择或显式指定的 Browser ID。",inputSchema:{type:"object",properties:{plugin:{type:"string",description:"已注册的插件名,或当前能力目录中可按需安装的插件名"},command:{type:"string",description:"插件注册的子命令名"},input:{type:"object",description:"传给插件 handler 的业务参数,省略时为空对象",additionalProperties:!0},browser:{type:"string",description:"可选目标浏览器 ID 或名称;省略时继承 browser_select_browser 选择的目标"},timeoutSec:{type:"number",description:"可选的浏览器底层调用超时秒数"}},required:["plugin","command"]}},{name:"browser_tab_checkpoint",description:"为目标标签页建立日志、请求和埋点的可靠增量边界,对应 mearl tab_checkpoint。返回的 cursor 可传给 browser_get_logs/browser_get_requests/browser_get_events 的 after。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"}},required:["tabId"]}},{name:"browser_get_requests",description:"获取指定标签页持续采集的 API 请求历史,包含请求、响应与 pending 状态。无需打开 DevTools panel;不传 after 时返回最新 N 条,传 after 时从最早未读项开始分页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},count:{type:"number",description:"获取的请求数量,默认 10 个。最多可获取最近 1000 个请求",default:10},filter:{type:"string",description:'过滤 API 名称的正则表达式(可选)。例如: ".*\\.cart\\..*" 只返回购物车相关接口'},since:{type:"number",description:"从多久之前开始获取(秒)。例如: 60 表示获取最近 1 分钟内的请求"},after:{type:"string",description:"tab checkpoint 或上一次查询返回的 cursor,仅返回其后的请求"},includeBody:{type:"boolean",description:"是否包含请求体和响应体。指定 fields 时默认 false,否则默认 true;可显式设为 true 同时读取全文。"},includeHeaders:{type:"boolean",description:"是否包含请求头和响应头。false 时将省略 headers 和 responseHeaders 字段以减少数据量。默认 false",default:!1},maxBodySize:{type:"number",description:"单个请求/响应体的最大字节数。超过此大小将被截断。默认 50000(约 50KB)",default:5e4},fields:{type:"array",items:{type:"string"},description:'从响应体中提取指定字段,支持点号路径。例如: ["data.result.list", "data.total"] 只返回这些字段,大幅减少数据量'},keysOnly:{type:"boolean",description:"只返回数据结构(字段路径和类型),不返回实际值。设为 true 可先预览数据结构,再决定提取哪些字段。默认 false",default:!1},source:{type:"string",enum:["protocol","requests","all"],description:"数据源。protocol: 已安装协议识别的请求; requests: 普通 XHR/Fetch 请求; all: 全部请求(默认)"}},required:["tabId"]}},{name:"browser_get_events",description:"获取目标标签页后台采集的 RUM/aplus/ARMS 埋点事件,无需打开 DevTools panel。不传 after 时返回最新事件,传 after 时按完整上报批次从最早未读项开始分页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},source:{type:"string",enum:["rum","aplus","arms","all"],description:"事件来源。rum: RUM 性能监控事件; aplus: aplus 埋点事件; arms: ARMS 前端监控事件; all: 全部(默认)",default:"all"},event_type:{type:"string",description:'事件类型正则过滤。例如: "view" 匹配页面 view 事件, "CLK" 匹配点击埋点'},filter:{type:"string",description:"正则过滤,匹配事件的 name 或 url 字段"},since:{type:"number",description:"从多久之前开始获取(秒)。例如: 60 表示获取最近 1 分钟内的事件"},after:{type:"string",description:"tab checkpoint 或上一次查询返回的 cursor,仅返回其后的埋点事件"},limit:{type:"number",description:"返回条数上限,默认 20",default:20},includeRaw:{type:"boolean",description:"是否返回完整 tracking URL、_raw 原始载荷和 _context 上下文;默认 false,仅返回解析后的精简字段",default:!1}},required:["tabId"]}},{name:"browser_get_logs",description:"获取指定标签页持续采集的 console API、未捕获异常和浏览器日志。无需打开 DevTools panel;不传 after 时返回最新 N 条,传 after 时从最早未读项开始分页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},level:{type:"string",enum:["log","warn","error","info","all"],description:"日志级别过滤。log: 普通日志, warn: 警告, error: 错误, info: 信息, all: 所有级别。默认 all",default:"all"},since:{type:"number",description:"从多久之前开始获取日志(秒)。例如: 60 表示获取最近 1 分钟内的日志"},after:{type:"string",description:"tab checkpoint 或上一次查询返回的 cursor,仅返回其后的日志"},limit:{type:"number",description:"最大返回日志数量,默认 100;快照查询返回最新 N 条",default:100},filter:{type:"string",description:'过滤日志内容的正则表达式或字符串(可选)。支持正则表达式模式(不区分大小写),若正则无效则回退到字符串包含匹配。例如: "error|warning" 匹配包含 error 或 warning 的日志'}},required:["tabId"]}},{name:"browser_set_mock",description:"动态设置 API 接口的 Mock 数据,用于测试不同数据场景。修改后,浏览器中对该接口的所有请求都会返回 Mock 数据。适用于前端开发测试、边界情况验证、UI 状态测试等。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},apiName:{type:"string",description:'API 名称或正则表达式模式。例如: "cart.query" 精确匹配, ".*\\.cart\\..*" 匹配所有购物车接口'},mockData:{type:["object","string"],description:'【方式一】直接设置完整 Mock 响应数据(JSON 对象)。传入后该接口将完全返回此数据,不再请求真实服务端。示例: {"data":{"result":{"list":[]}},"ret":["SUCCESS"]}。注意:mockData 和 fields 二选一,同时提供时优先使用 fields。大体积响应体可传文件引用字符串 "@/abs/resp.json"(从该文件读取,建议绝对路径)以减少上下文占用'},fields:{type:"array",description:"【方式二】基于真实响应修改指定字段。系统会先获取该接口的原始响应数据,然后按指定路径修改字段值。适合在真实数据基础上做微调",items:{type:"object",properties:{path:{type:"string",description:'字段路径,支持点号和数组索引。例如: "data.result.passengerList[0].name.text"'},value:{description:"要设置的值,可以是任意类型(字符串、数字、对象、数组等)"}},required:["path","value"]}},enabled:{type:"boolean",description:"是否启用 Mock。true: 启用 Mock, false: 禁用 Mock 恢复真实数据。默认 true",default:!0},duration:{type:"number",description:"完整响应时长(毫秒)。可选,mock 生效时的总耗时,绕过真实服务器精确控制(用于测试加载状态、超时等场景)"},conditions:{type:"object",additionalProperties:!0,description:"请求 query/body 字段的子集匹配规则;保留字段 $index 从 0 开始指定同一场景的调用顺序。相同 $index 再次设置会原地覆盖,超过最后一项后持续使用最后一项"},payloadFile:{type:"string",description:"从文件读取 mock 数据(JSON 格式)。当 mockData 很大时,可将完整 JSON 写入文件,通过此参数指定文件路径。文件内容会被解析为 mockData。注意:此参数与 mockData/fields 互斥,优先级最高"}},required:["tabId","apiName"]}},{name:"browser_get_mocks",description:"查看当前所有已设置的 Mock 配置,包括接口名称、是否启用、以及 Mock 数据内容。用于排查 Mock 是否生效、Mock 数据是否正确等问题。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID,从 browser_tab_open 或 browser_tab_list 获取"},apiName:{type:"string",description:'过滤指定接口,支持正则表达式。例如: "cart.query" 或 ".*\\.cart\\..*"。不传则返回所有 Mock'}},required:["tabId"]}},{name:"browser_send_request",description:"通过浏览器发起 HTTP 代理请求,自动携带目标域名的 Cookie(使用当前浏览器登录态)。支持 GET/POST/PUT/DELETE/PATCH、multipart 文本字段和本地文件上传,适用于需要用户登录态的接口调试、数据爬取、接口测试等场景。",inputSchema:{type:"object",properties:{url:{type:"string",description:"目标请求 URL,必须是完整 URL(含 http:// 或 https://)"},method:{type:"string",enum:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"],description:"HTTP 请求方法,默认 GET",default:"GET"},headers:{type:"object",description:"自定义请求头(键值对),会与自动生成的 Cookie 头合并",additionalProperties:{type:"string"}},params:{type:"object",description:"URL 查询参数(键值对),会追加到 URL 中",additionalProperties:{type:"string"}},body:{description:"请求体。传入对象时自动序列化为 JSON 并设置 Content-Type: application/json;传入字符串时原样发送"},formData:{type:"object",description:"multipart/form-data 文本字段。字段值支持 string、number、boolean;不能与 body 同时使用",additionalProperties:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"}]}},files:{type:"array",description:"multipart 文件列表,最多 20 个且总计不超过 40 MiB。本地调用优先传绝对 filePath;远程调用可传 base64,并同时提供 filename,Base64 文件内容总计不超过 7 MiB",maxItems:20,items:{type:"object",properties:{fieldName:{type:"string",description:"multipart 字段名,例如 file"},filePath:{type:"string",description:"Mearl native-host 所在机器上的绝对文件路径"},base64:{type:"string",description:"文件内容的 Base64;与 filePath 二选一"},filename:{type:"string",description:"上传文件名;使用 base64 时必填"},contentType:{type:"string",description:"文件 MIME 类型;默认根据文件名推断"}},required:["fieldName"],oneOf:[{required:["filePath"]},{required:["base64","filename"]}]}},withCookies:{type:"boolean",description:"是否自动携带浏览器中该域名的 Cookie,默认 true",default:!0},responseType:{type:"string",enum:["json","text","auto"],description:'响应格式。auto: 自动检测(默认); json: 强制解析为 JSON; text: 返回原始文本。注意:auto 模式下若 Content-Type 为图片/音视频/PDF/压缩包等二进制类型,body 将以 base64 字符串返回,bodyType 为 "base64"',default:"auto"},timeout:{type:"number",description:"请求超时时间(毫秒),默认 30000(30 秒)",default:3e4}},required:["url"]}},{name:"browser_set_rule",description:"添加或删除浏览器请求规则。enabled=false 且传 ruleId 时彻底删除规则;否则添加规则。扩展模式持久保存规则,CDP 模式的规则仅在当前控制会话生效。",inputSchema:{type:"object",properties:{ruleId:{type:"integer",minimum:1,description:"删除时必填:从 browser_get_rules 获取的规则 ID"},enabled:{type:"boolean",description:"省略时添加规则;false 时删除 ruleId 对应的规则"},actionType:{type:"string",enum:["redirect","block","allow","upgradeScheme","modifyHeaders"],description:"规则类型。redirect: 重定向请求到另一地址; block: 阻止请求; allow: 允许请求; upgradeScheme: 升级到 HTTPS; modifyHeaders: 修改请求/响应头"},filter:{type:"string",description:'URL 匹配规则(正则表达式)。例如: "^https://h5api\\.m\\.shop\\.com/.*" 匹配所有商城 h5api 请求'},redirectUrl:{type:"string",description:"【redirect 类型必填】重定向目标 URL。支持正则替换占位符 \\1 \\2 等(引用 filter 中的捕获组)"},requestHeaders:{type:"array",description:"【modifyHeaders 类型】要修改的请求头列表",items:{type:"object",properties:{header:{type:"string",description:'请求头名称,如 "x-custom-header"'},operation:{type:"string",enum:["set","append","remove"],description:"set: 设置/覆盖; append: 追加; remove: 删除"},value:{type:"string",description:"请求头值(remove 时可省略)"}},required:["header","operation"]}},responseHeaders:{type:"array",description:"【modifyHeaders 类型】要修改的响应头列表",items:{type:"object",properties:{header:{type:"string",description:"响应头名称"},operation:{type:"string",enum:["set","append","remove"],description:"set: 设置/覆盖; append: 追加; remove: 删除"},value:{type:"string",description:"响应头值(remove 时可省略)"}},required:["header","operation"]}},initiatorDomains:{type:"string",description:'发起请求的域名限制(逗号分隔)。只有从这些域名发起的请求才会匹配此规则。例如: "shop.com,tmall.com"'},resourceTypes:{type:"array",description:"资源类型限制;不填时使用当前浏览器模式的默认值",items:{type:"string",enum:["main_frame","sub_frame","script","stylesheet","image","xmlhttprequest","websocket","other"]}},priority:{type:"number",description:"规则优先级,数字越大优先级越高。多个规则匹配同一请求时,优先级高的生效。默认 1",default:1},description:{type:"string",description:"规则描述,便于识别规则用途"}},oneOf:[{required:["actionType","filter"],not:{required:["ruleId"]},properties:{enabled:{const:!0}}},{required:["ruleId","enabled"],properties:{enabled:{const:!1}}}]}},{name:"browser_get_rules",description:"查看当前浏览器模式的请求规则。扩展模式包含 Options 面板配置的持久规则;CDP 模式返回当前控制会话的请求头规则。",inputSchema:{type:"object",properties:{}}},{name:"browser_page_screenshot",description:'获取指定浏览器标签页的视觉截图,以 Base64 编码返回。支持全页截图或指定 CSS 选择器截取单个元素(类似 DevTools "Capture node screenshot")。适用于视觉判断、Canvas、跨域 iframe、UI 排查和保存快照;常规页面动作后优先读取其内置观察的增量结果,不要固定在每次动作后截图。',inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:"CSS 选择器。提供后只截取该元素区域(会自动滚动元素到可见区域),不提供则截取整个页面"},format:{type:"string",enum:["png","jpeg"],description:"截图格式。png: PNG 格式(无损,默认); jpeg: JPEG 格式(有损压缩,体积更小)",default:"png"},quality:{type:"number",description:"JPEG 质量(仅 format 为 jpeg 时有效)。范围 0-100,默认 80。数值越高质量越好但文件越大",default:80}},required:["tabId"]}},{name:"browser_launch",description:"启动浏览器实例。默认使用本地独立 Chrome;传已注册的 Provider ID 时,把该 Provider 声明的创建参数放在 providerOptions。配对实例会直接返回 pairing URL。具体 Provider 用法可运行 mearl <providerId> 查看。",inputSchema:{type:"object",properties:{name:{type:"string",description:"本地实例名称;使用默认 local Provider 时必填"},provider:{type:"string",description:"浏览器提供方,默认 local;也可传已注册的外部 Provider ID"},providerOptions:{type:"object",additionalProperties:!0,description:"所选外部 Provider 声明的结构化创建参数"},headless:{type:"boolean",description:"本地 Provider 是否使用 headless=new,默认 true"},userAgentMode:{type:"string",enum:["default","desktop"],description:"本地 UA 模式:default 使用默认 UA;desktop 使用匹配本机 Chrome 的 UA",default:"default"},persistent:{type:"boolean",description:"本地实例关闭后是否保留独立 Profile,默认 false",default:!1},url:{type:"string",description:"新浏览器打开的初始 URL"},executablePath:{type:"string",description:"Chrome 可执行文件路径;省略时自动发现,也可用环境变量配置"},copyCookieDomains:{oneOf:[{type:"array",items:{type:"string"}},{type:"string",minLength:1},{type:"object",properties:{presets:{type:"array",items:{type:"string",minLength:1}},domains:{type:"array",items:{type:"string"}}},additionalProperties:!1}],description:"从控制浏览器复制 Cookie,可传域名数组、已安装能力提供的范围名称,或 {presets, domains} 组合。保留 HttpOnly/Secure/SameSite/过期时间等属性;所需域名权限仍由宿主管理。"}},anyOf:[{required:["name"]},{required:["provider"]}]}},{name:"browser_close",description:"关闭一个 Provider 托管浏览器;持久化数据默认按 Provider 策略保留,deleteProfile=true 时一并删除。名称有歧义时使用完整 browserId。",inputSchema:{type:"object",properties:{browser:{type:"string",description:"browser_launch 返回的 browserId 或实例名称"},deleteProfile:{type:"boolean",description:"是否强制删除 Provider 持久化数据,默认 false",default:!1}},required:["browser"]}},{name:"browser_release",description:"仅在用户明确要求结束调试、退出接管或清理会话资源时调用,不作为普通任务收尾。它会释放 debugger/CDP 控制和会话级临时效果,后续浏览器操作可自动重新建立控制;Provider 实例的生命周期操作由 Browser Manager 处理。",inputSchema:{type:"object",properties:{}}},{name:"browser_tab_open",description:"打开或按 URL 规则复用标签页。默认新建并等待加载完成;reuse=prefer 可优先复用,reuse=require 可限制为只复用。响应的 opened/reused 可用于判断流程结束时是否应关闭该 Tab。",inputSchema:{type:"object",properties:{url:{type:"string",description:"要打开的页面 URL"},active:{type:"boolean",description:"是否激活目标标签页。默认 false;扩展免打扰默认开启,使用后台焦点模拟,关闭后才切换前台。activation.mode 区分 background/foreground,visibilityState 不代表窗口在前台",default:!1},openerTabId:{type:"number",description:"来源标签页 ID。侧边栏对话继续任务时传入,用于把新开或复用的标签页关联到同一对话"},closeExisting:{type:"boolean",description:"打开前是否先关闭 Agent 受控的已有标签页。默认 false",default:!1},group:{type:"string",description:"把新标签页加入指定标题的标签页分组(同窗口同名分组存在则加入,否则新建)。仅扩展模式支持,CDP 模式忽略"},reuse:{type:"string",enum:["never","prefer","require"],description:"never 始终新建;prefer 匹配到则复用、否则新建;require 只允许复用。默认 never",default:"never"},match:{type:"object",description:"复用标签页时的 URL 匹配规则",properties:{urlPattern:{type:"string",description:"支持 * 的完整 URL glob;省略时精确匹配 url"},ignoreSearch:{type:"boolean",description:"匹配时是否忽略 URL query,默认 false"},ignoreHash:{type:"boolean",description:"匹配时是否忽略 URL hash,默认 false"},onMultiple:{type:"string",enum:["error","first"],description:"匹配多个 Tab 时默认报错;first 显式取第一个"}}},restoreFocusOnClose:{type:"boolean",description:"新建 active Tab 关闭后是否恢复原活动标签页,默认 false",default:!1},emulation:{type:"object",description:"开 tab 即进入移动端模拟态,等价于随后立即调用 browser_set_device_emulation,但在导航前生效。deviceShell=true 时首屏就在 iframe WebView 与设备系统外壳中渲染。字段规则一致(无 enabled/reload)。",properties:{preset:{type:"string",enum:[...BROWSER_DEVICE_PRESET_NAMES2],description:"内置设备预设,一键提供 viewport/DPR/UA。当前机型在前,旧机型 ID 继续兼容;可与下面字段组合,显式字段覆盖预设值"},width:{type:"number",description:"视口宽度(覆盖 preset)"},height:{type:"number",description:"视口高度(覆盖 preset)"},deviceScaleFactor:{type:"number",description:"devicePixelRatio(覆盖 preset)"},scale:{type:"number",exclusiveMinimum:0,description:"画面视觉比例,不改变视口 CSS 尺寸或 devicePixelRatio;必须为有限正数,默认 1"},mobile:{type:"boolean",description:"是否启用移动渲染模式。默认从 preset 推断,无 preset 默认 true"},userAgent:{type:"string",description:"自定义 User-Agent(覆盖 preset)。无 preset 时必填"},orientation:{type:"string",enum:["portrait","landscape"],description:"横竖屏,landscape 会对调宽高。默认 portrait"},touch:{type:"boolean",description:"是否启用触摸事件并把鼠标事件转成 touch。默认从 preset 推断;无 preset 时跟随 mobile"},deviceShell:{type:"boolean",description:"是否使用 iframe WebView 并渲染顶部状态栏与底部操作区,默认 false"},splitScreen:{type:"boolean",description:"是否在横屏设备外壳中将首页与业务页分置左右 WebView;仅与 appProfile、deviceShell=true、orientation=landscape 同时生效,默认 false"}}},appProfile:{type:"string",description:"开 tab 即注入 App 客户端环境与 JSBridge(等价于随后调用 browser_set_app_profile,但在首次导航前生效)。不创建根 iframe;需要设备外壳时同时传 emulation.deviceShell=true"},os:{type:"string",enum:["ios","android"],description:"与 appProfile 配合;容器系统,默认 ios"},bridgeConfig:{type:"object",description:"与 appProfile 配合;声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}},不执行配置脚本"}},required:["url"]}},{name:"browser_tab_close",description:"关闭指定的浏览器标签页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"要关闭的标签页 ID(从 tab_open 或 tab_list 获取)"}},required:["tabId"]}},{name:"browser_get_capabilities",description:"只读查询当前目标浏览器的已安装 App、动作、设备预设、限制与 Skill/帮助入口。app 可指定目录中的完整 ID,按需获取桥方法与设置详情;不打开页面或启用模拟。支持 action 不代表已取得页面权限或真实授权。",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0},inputSchema:{type:"object",properties:{app:{type:"string",description:"可选,查询已安装 App ID 的详细能力"},browser:{type:"string",description:"目标浏览器 ID 或唯一名称;省略沿用当前选择"}}}},{name:"browser_tab_list",description:"列出当前浏览器窗口中所有标签页的信息,包括 ID、URL、标题和是否活动。",inputSchema:{type:"object",properties:{}}},{name:"browser_tab_group",description:"将同一窗口中的标签页加入分组,或取消分组并保留标签页。仅扩展模式支持。",inputSchema:{type:"object",properties:{tabIds:{type:"array",items:{type:"number"},description:"标签页 ID 列表,分组最多 100 个,取消分组最多 1000 个"},title:{type:"string",description:"分组标题;取消分组时省略"},ungroup:{type:"boolean",description:"为 true 时取消分组并保留标签页"}},required:["tabIds"]}},{name:"browser_page_click",description:"点击页面元素;selector、text、point 三种定位方式必须且只能提供一种。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:`原生 CSS 选择器(如 "[aria-label='提交']"、"#login-btn")或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e3",必须带 "@" 前缀)。注意字段名是 "selector" 而非 "ref"。不支持 :has-text/:visible 等 Playwright 扩展语法。与 text/point 互斥。`},text:{type:"string",description:'按可见文本(accessibility name)定位。例如 "退款明细"。匹配到多个时会报错并列出候选——可加 role 或 exact:true 收敛,或用 page_snapshot 拿 @ref。与 selector/point 互斥。'},point:{type:"object",description:"按视口坐标点击(CSS 像素,左上角为原点)。selector 和 text 都不适用时使用。与 selector/text 互斥。",properties:{x:{type:"number",description:"横坐标(CSS 像素)"},y:{type:"number",description:"纵坐标(CSS 像素)"}},required:["x","y"]},frameId:{type:"string",description:"仅扩展后端:CSS/text 查询或 active-frame 坐标所属的 frame;省略时容器使用当前业务 frame"},coordinateSpace:{type:"string",enum:["outer-viewport","active-frame"],description:"仅配合 point;默认 outer-viewport。仅扩展后端支持 active-frame,会换算 iframe 偏移与缩放"},role:{type:"string",description:'配合 text 使用,按 AX role 过滤消歧(如 "button"、"link"、"heading"、"StaticText")'},exact:{type:"boolean",description:"配合 text 使用,默认 true 精确匹配;false 时按子串匹配",default:!0},scope:{type:"string",description:'配合 text 使用,把 AX 文本匹配限制在指定 CSS 元素或 snapshot ref(如 "@e12")子树内'},clickMode:{type:"string",enum:["auto","dom","mouse","touch"],description:"默认 auto:可见页使用匹配设备的可信输入,隐藏页使用 DOM;dom/mouse/touch 可强制指定派发方式",default:"auto"},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId"]}},{name:"browser_page_drag",description:"连续拖动页面元素或视口坐标,适用于轮播图、滑块、Canvas 手势和拖放。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},from:{description:"拖动起点:CSS/@eN selector,或 {x,y} 视口坐标(CSS 像素)",anyOf:[{type:"string"},{type:"object",properties:{x:{type:"number"},y:{type:"number"}},required:["x","y"]}]},to:{description:"拖动终点:CSS/@eN selector,或 {x,y} 视口坐标(CSS 像素)",anyOf:[{type:"string"},{type:"object",properties:{x:{type:"number"},y:{type:"number"}},required:["x","y"]}]},dragMode:{type:"string",enum:["auto","dom","mouse","touch"],description:"默认 auto:可见页使用匹配设备的可信输入,隐藏页使用 DOM;dom/mouse/touch 可强制指定派发方式",default:"auto"},durationMs:{type:"number",minimum:0,maximum:5e3,description:"拖动持续时间(毫秒),默认 400;内部自动分段移动",default:400},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","from","to"]}},{name:"browser_page_type",description:"向输入框填写文本,兼容 React 等框架的受控组件。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:'原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e6",必须带 "@" 前缀)。字段名是 "selector"。不支持 :has-text/:visible 等 Playwright 扩展。'},text:{type:"string",description:"要输入的文本内容"},clearFirst:{type:"boolean",description:"是否先清空输入框原有内容。默认 true",default:!0},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","selector","text"]}},{name:"browser_page_scroll",description:'按方向滚动页面或指定容器;页面根不可滚动时自动发现活动滚动区,containerPolicy="nearest" 可从子节点解析最近的可滚动祖先。',inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},direction:{type:"string",enum:["up","down","top","bottom"],description:"滚动方向"},distance:{type:"number",description:"滚动距离(像素),仅 up/down 方向有效。默认 600",default:600},selector:{type:"string",description:'目标滚动容器的原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e6",必须带 "@" 前缀);不传时滚动页面。'},containerPolicy:{type:"string",enum:["self","nearest"],description:"默认 self,要求 selector 本身可滚动;nearest 会在其不可滚动时使用最近的可滚动祖先"},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","direction"]}},{name:"browser_page_hover",description:"将鼠标悬停在页面元素上。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:'原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e1",必须带 "@" 前缀)。字段名是 "selector"。不支持 :has-text/:visible 等 Playwright 扩展。'},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","selector"]}},{name:"browser_page_eval",description:"在页面默认上下文执行最小 JavaScript 表达式,作为结构化工具无法表达时的补充。默认返回 { result };observe 对象启用观察并返回 { action, observation };仅开启 diagnostics 时返回 { action, diagnostics },diagnostics=false 不启用包装。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},expression:{type:"string",description:"要执行的 JavaScript 表达式"},frameId:{type:"string",description:"browser_page_frames 返回的目标 frame ID,扩展/CDP 均支持;省略时容器/设备外壳使用当前业务 frame,普通页面使用主 frame。读取外层容器时显式传主 frame ID"},awaitPromise:{type:"boolean",description:"是否等待表达式返回的 Promise,默认 true",default:!0},observe:{type:"object",properties:OBSERVE_INPUT_SCHEMA.properties,description:"仅在表达式会修改页面且需要观察结果时显式传入;不传时轻量执行并直接返回结果"},diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","expression"]}},{name:"browser_page_inspect",description:"查询 DOM 元素的原生/ARIA 控件状态、数量、边框盒、计算样式、命中遮挡、溢出尺寸和最近滚动容器;也可读取 DevTools 当前选区或直接扫描全页。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:'原生 CSS、page_snapshot 返回的 ref(如 "@e8"),或 DevTools Elements 当前选区 "$0";全页溢出诊断时可省略'},filter:{type:"string",enum:["all","overflowing","horizontal-overflow","vertical-overflow","scrollable"],description:"结果过滤;省略 selector 时必须指定非 all 的过滤条件"},styles:{type:"array",items:{type:"string"},description:"要返回的计算样式属性;默认 display/position/box-sizing/overflow-x/overflow-y"},maxResults:{type:"number",minimum:1,maximum:100,description:"最多返回的明细数,默认 20;未触发 scanTruncated 时 count 为完整命中数"},includeOuterHTML:{type:"boolean",description:"是否返回 outerHTML(最多 3000 字符);$0 默认 true,其他目标默认 false"}},required:["tabId"]}},{name:"browser_page_snapshot",description:"获取带 @ref 的页面结构树;ref 可直接用于操作,内部节点映射不输出。默认使用无障碍树,AX 信息缺失时可显式读取渲染 DOM。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},depth:{type:"number",description:"无障碍树的最大深度。默认 15,增大可获取更深层元素",default:15},mode:{type:"string",enum:["full","interactive","viewport","dom"],description:"full 为完整 AX 树;interactive 只保留当前视口内的 AX 语义控件,无控件时回退到 AX viewport;viewport 为当前可视 AX 树;dom 显式返回实际渲染文本、原生控件、显式 role 和高置信 clickable 节点。默认 full"},rootSelector:{type:"string",description:"只获取指定 CSS 元素的局部子树,可与 mode 组合;与 rootRef 互斥"},rootRef:{type:"string",description:'以已有 snapshot ref(如 "@e8")为根获取局部子树'},ancestorDepth:{type:"number",description:"rootRef 向上扩展的 DOM 祖先层数,默认 0,最大 20",minimum:0,maximum:20},query:{type:"object",description:"服务端按 name / role 过滤当前模式的树,只保留命中节点及祖先路径",properties:{text:{type:"string",description:"要匹配的 accessibility name"},role:{type:"string",description:"要匹配的 AX role"},exact:{type:"boolean",description:"text 默认精确匹配;false 时按子串匹配"}}},maxNodes:{type:"number",description:"最多输出节点数;超出时保留首尾。0 表示不限制"},maxChars:{type:"number",description:"最多输出字符数,默认 60000;超出时保留首尾。0 表示不限制"}},required:["tabId"]}},{name:"browser_page_press",description:"在页面中按下键盘按键或组合键。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},key:{type:"string",description:"按键名称。支持:Enter, Tab, Escape, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown, Space"},dialogId:{type:"string",description:"page_snapshot 或中断回执中的 dialog.id;仅配合 Enter 接受或 Escape 取消原生弹窗,不自动重放旧动作。"},promptText:{type:"string",description:"仅用于 dialogId + Enter 接受原生 prompt 时填写文本。"},modifiers:{type:"array",items:{type:"string"},description:'修饰键数组,如 ["Alt", "Shift", "Control", "Meta"]'},pressMode:{type:"string",enum:["auto","dom","keyboard"],description:"派发模式;auto 默认在隐藏页降级为 DOM 键盘事件"},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","key"]}},{name:"browser_page_wait",description:"独立等待接口:仅用于没有前置动作时等待指定时间、已知 selector 状态、可见文本或页面 condition。四种模式必须且只能提供一个;点击、输入后的异步稳定判断由页面交互工具内置的观察完成。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},time:{type:"number",description:"固定等待毫秒数,与 selector/text/condition 四选一"},selector:{type:"string",description:"CSS 选择器,与 time/text/condition 四选一"},state:{type:"string",enum:["attached","detached","visible","hidden"],description:"selector 的目标状态,默认 attached",default:"attached"},text:{type:"string",description:"等待页面出现的可见文本,与 time/selector/condition 四选一"},exact:{type:"boolean",description:"text 是否精确匹配,默认 false",default:!1},condition:{type:"string",description:"在页面主上下文轮询的 JavaScript 表达式,返回 truthy 时结束,支持 Promise;与 time/selector/text 四选一"},timeout:{type:"number",description:"等待超时时间(毫秒),默认 10000ms",default:1e4},interval:{type:"number",description:"selector/condition 的轮询间隔(毫秒),默认 200ms",default:200}},required:["tabId"]}},{name:"browser_page_navigate",description:'在指定标签页中导航到 URL、设置 refresh:true 重新加载,或用 history:"back"|"forward" 沿浏览历史移动。三种模式互斥,返回最终 URL 和标题。',inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},url:{type:"string",description:"要导航到的 URL;与 refresh/history 互斥"},refresh:{type:"boolean",description:"为 true 时直接重新加载当前页面;与 url/history 互斥",default:!1},history:{type:"string",enum:["back","forward"],description:"沿当前标签页浏览历史后退或前进;与 url/refresh 互斥"}},required:["tabId"]}},{name:"browser_page_upload",description:'向 <input type="file"> 元素上传一个或多个本地文件。',inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},selector:{type:"string",description:'原生 CSS 选择器,或 page_snapshot / 页面动作 observation 返回的 ref(如 "@e5",必须带 "@" 前缀),用于定位 <input type="file"> 元素。字段名是 "selector"。'},filePaths:{type:"array",items:{type:"string"},description:'要上传的本地文件路径数组,如 ["/Users/me/photo.jpg"]'},observe:OBSERVE_INPUT_SCHEMA,diagnostics:DIAGNOSTICS_INPUT_SCHEMA},required:["tabId","selector","filePaths"]}},{name:"browser_page_frames",description:"列出主 frame 和 iframe,返回可供 browser_page_eval 使用的 frameId。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"}},required:["tabId"]}},{name:"browser_set_device_emulation",description:"把目标标签页切换为移动端模拟态:视口尺寸 / DPR / UA / 触摸事件按指定设备生效,并可独立调整视觉比例。deviceShell=true 时把业务页放入 iframe WebView,并在外层渲染顶部状态栏与底部操作区;false/省略时保持纯 CDP 模拟。作用域仅限该 tab,启用后默认 reload,enabled=false 清除模拟与设备外壳。",inputSchema:{type:"object",properties:{enabled:{type:"boolean",description:"必填。true=启用模拟(按 preset/参数生效),false=清除模拟回到桌面态"},preset:{type:"string",enum:[...BROWSER_DEVICE_PRESET_NAMES2],description:"内置设备预设,一键提供 viewport/DPR/UA。当前机型在前,旧机型 ID 继续兼容;可与下面的字段组合,显式字段会覆盖预设值"},width:{type:"number",description:"视口宽度(覆盖 preset)"},height:{type:"number",description:"视口高度(覆盖 preset)"},deviceScaleFactor:{type:"number",description:"devicePixelRatio(覆盖 preset)"},scale:{type:"number",exclusiveMinimum:0,description:"画面视觉比例,不改变视口 CSS 尺寸或 devicePixelRatio;必须为有限正数,默认 1"},mobile:{type:"boolean",description:"是否启用移动渲染模式(影响 hover/pointer media query、viewport meta 行为)。默认从 preset 推断,无 preset 默认 true"},userAgent:{type:"string",description:"自定义 User-Agent(覆盖 preset)"},orientation:{type:"string",enum:["portrait","landscape"],description:"横竖屏,landscape 会对调宽高。默认 portrait"},touch:{type:"boolean",description:"是否启用触摸事件并把鼠标事件转成 touch。默认从 preset 推断;无 preset 时跟随 mobile"},deviceShell:{type:"boolean",description:"是否使用 iframe WebView 并渲染顶部状态栏与底部操作区,默认 false"},splitScreen:{type:"boolean",description:"是否在横屏 App 容器中将首页与业务页分置左右 WebView;仅在当前已启用 App 档案、deviceShell=true、orientation=landscape 时生效,默认 false"},reload:{type:"boolean",description:"启用模拟后是否重载页面(让 JS 读到新的 navigator.userAgent / window.innerWidth)。默认 true"},tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"}},required:["tabId","enabled"]}},{name:"browser_set_app_profile",description:"设置目标标签页的 App 客户端 UA;可用 App ID、限制和说明通过 browser_get_capabilities 查询。完整环境变量、JSBridge、桥协议和 Protocol 页面接口环境由已安装能力提供。传 emulation 时由同一个调用联动设备模拟与 iframe 系统外壳;省略 emulation 时不改变设备状态。",inputSchema:{type:"object",properties:{enabled:{type:"boolean",description:"必填。true=启用容器模拟,false=清除并还原设备模拟"},profile:{type:"string",description:"容器档案名(enabled=true 时必填),决定 UA/桥对象/环境判断特征"},os:{type:"string",enum:["ios","android"],description:"容器系统,默认 ios"},refreshDefinition:{type:"boolean",description:"立即采用最新档案定义,保留用户显式设置"},lockDefinition:{type:"boolean",description:"固定当前定义;默认在下次刷新或文档导航时自动更新"},appVersion:{type:"string",description:"覆盖档案默认 App 版本号"},deviceModel:{type:"string",description:"Android 机型名(拼入 UA 与 __DEVICE_MODEL__)"},bridgeConfig:{type:"object",description:"声明式覆盖桥方法,形如 {methods:{api:{behavior|response|noop,silent?}}};扩展本地同档案配置会先合并"},networkControl:{type:["object","null"],properties:{id:{type:"string"},value:{type:"string"}},required:["id","value"],additionalProperties:!1,description:"可选已安装网络控件 {id,value};null 清除,省略时保持当前设置。"},emulation:{type:"object",description:"可选设备联动参数;字段覆盖档案推荐设备,空对象使用推荐设备,deviceShell 默认 true。省略时不设置或清除设备。",properties:{preset:{type:"string",enum:[...BROWSER_DEVICE_PRESET_NAMES2]},width:{type:"number"},height:{type:"number"},deviceScaleFactor:{type:"number"},scale:{type:"number",exclusiveMinimum:0},mobile:{type:"boolean"},userAgent:{type:"string"},orientation:{type:"string",enum:["portrait","landscape"]},touch:{type:"boolean"},deviceShell:{type:"boolean",description:"是否使用根 iframe WebView 并显示系统栏;在 emulation 内默认 true"},splitScreen:{type:"boolean",description:"是否在横屏设备外壳中将首页与业务页分置左右 WebView;仅与 deviceShell=true、orientation=landscape 同时生效,默认 false"}}},reload:{type:"boolean",description:"应用/清除后是否重载页面,默认 true"},tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"}},required:["tabId","enabled"]}},{name:"browser_set_timezone",description:"覆盖目标标签页的时区,作用域仅限该 tab,立即影响 Date / Intl 等页面时间 API。timezone 使用 IANA 时区标识(如 Asia/Shanghai、America/New_York);传空字符串恢复浏览器默认时区。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"目标标签页 ID(从 browser_tab_open 或 browser_tab_list 获取)"},timezone:{type:"string",description:"IANA 时区标识;空字符串表示清除覆盖"}},required:["tabId","timezone"]}},{name:"browser_get_cookie",description:"从目标浏览器读取一个指定非分区 Cookie,用于验证页面分支、实验或当前账号标识。必须明确传 Cookie 名,不支持列举全部 Cookie;HttpOnly Cookie 会被拒绝,禁止读取认证 Token。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"可选;指定标签页的 Cookie 存储区,省略时使用浏览器默认存储区"},name:{type:"string",description:"Cookie 名称"},url:{type:"string",description:"Cookie 查询 URL;未传 tabId 时必填,省略时使用指定标签页 URL"},domain:{type:"string",description:"可选精确域过滤,只允许 Cookie 查询 URL 的 host 或它的父域"},path:{type:"string",description:"可选精确 path 过滤"}},required:["name"],anyOf:[{required:["url"]},{required:["tabId"]}]}},{name:"browser_set_cookie",description:"在目标浏览器设置一个指定非分区 session Cookie。url 与 tabId 至少传一个;未传 tabId 时使用浏览器默认存储区。domain 只允许目标 URL 的 host 或它的父域。",inputSchema:{type:"object",properties:{tabId:{type:"number",description:"可选;指定标签页的 Cookie 存储区,reload=true 时必填"},url:{type:"string",description:"Cookie 目标 URL;未传 tabId 时必填,省略时使用指定标签页 URL"},name:{type:"string",description:"Cookie 名称"},value:{type:"string",description:"Cookie 值,可传空字符串;空字符串不会删除 Cookie"},domain:{type:"string",description:"Cookie 域,默认目标 URL 的 host;只允许目标 host 或它的父域"},path:{type:"string",description:"Cookie path,默认 /"},reload:{type:"boolean",description:"设置后是否刷新指定 tabId,默认 false;true 时必须传 tabId"}},required:["name","value"],anyOf:[{required:["url"]},{required:["tabId"]}]}},{name:"browser_run_actions",description:"批量顺序执行多个无需中间判断的原子操作,适合 hover→click 等必须紧密连续的序列。步骤内的页面动作不带内置观察;遇到第一个失败步骤立即停止,且不能嵌套 run_actions。需要条件、循环或处理返回数据时可用 browser_run_code;需要模型理解页面时使用逐步页面工具。不要用本工具固化「点击→等待→截图」循环。",inputSchema:{type:"object",properties:{actions:{type:"array",description:"要依次执行的 action 列表",items:{type:"object",properties:{action:{type:"string",description:"action 名称(不带 browser_ 前缀),如 page_hover、page_click;仅组合无需中间判断的步骤"},data:{type:"object",description:"该 action 的参数(与单独调用时相同)"}},required:["action"]}},tabId:{type:"number",description:"所有步骤共享的目标标签页 ID。步骤自身指定的 tabId 优先级更高"}},required:["tabId","actions"]}},{name:RUN_CODE_TOOL_NAME,description:'在 MCP server 宿主的独立 Node.js 进程执行 JavaScript,预注入 mearl SDK,支持顶层 await、条件、循环和数据处理。浏览器调用用 mearl.pageClick({tabId,selector}) 等现有 SDK 方法或 mearl.invoke(action,payload,options?);Skill 命令用 mearl.invokePlugin(name,{command,input},options?)。用 console.log(await mearl.help("pageClick")) 查共享命令帮助,help({plugin,command?}) 查插件帮助,mearl.structure(value) 查看有界结果结构。使用 console.log 输出必要结果,await 所有 SDK 调用。JS 变量每次重建;session 和 tabId 可跨调用复用。DOM 代码使用 mearl.pageEval。脚本拥有宿主 Node 权限,超时或取消不能撤销已派发操作。',inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript 源码,最大 1 MiB;使用 await import() 加载模块"},browser:{type:"string",description:"目标浏览器 ID 或唯一名称"},session:{type:"string",description:"首次调用 tab_open/page_snapshot 等传 new;后续复用 sessionId"},timeoutSec:{type:"number",exclusiveMinimum:0,maximum:2147483,description:"整个脚本的执行时限,默认 60 秒"}},required:["code"]}},{name:"browser_list",description:"列出所有浏览器。返回普通浏览器和 Provider 托管浏览器的 browserId、名称、类型、连接状态、稳定元数据及当前默认目标,但不返回带临时凭据的浏览器访问地址。只有 status=connected 的浏览器可用于后续操作。",inputSchema:{type:"object",properties:{}}},{name:"browser_select_browser",description:"选择后续所有浏览器操作的默认目标浏览器(有多个浏览器连接时)。传入 browser_list 返回且 status=connected 的 browserId 或名称即可锁定;传空字符串则清除锁定,回到自动模式(操作最近聚焦的浏览器)。",inputSchema:{type:"object",properties:{browser:{type:"string",description:"目标浏览器的 browserId / 名称;空字符串表示清除锁定、恢复自动选择"}},required:["browser"]}},{name:"browser_request_permission",description:"申请访问指定域名的权限。调用后浏览器会弹出确认窗口让用户授权(90 秒超时),返回 granted 表示是否已获得授权。扩展模式下发送非内置域的 HTTP 请求(browser_send_request)前需先获得用户授权。",inputSchema:{type:"object",properties:{domain:{type:"string",description:"需要授权的域名,如 example.com"}},required:["domain"]}}];server.setRequestHandler(ListToolsRequestSchema,async()=>({tools:tools.map(tool=>tool.name===PLUGIN_INVOKE_TOOL_NAME||tool.name===RUN_CODE_TOOL_NAME?tool:{...tool,inputSchema:{...tool.inputSchema,...tool.name==="browser_page_upload"?{required:(tool.inputSchema.required??[]).filter(field=>field!=="filePaths")}:{},properties:{...tool.inputSchema.properties,...tool.name==="browser_release"?{closeCreatedTabs:{type:"boolean"},keepTabIds:{type:"array",items:{type:"number"}},preserveEnvironment:{type:"boolean"},keepArtifactIds:{type:"array",items:{type:"string"}}}:{},...tool.name==="browser_page_upload"?{files:{type:"array",items:{type:"object",properties:{filePath:{type:"string"},artifactId:{type:"string"}}}}}:{},session:{type:"string",description:"首次 tab_open/page_snapshot 传 new;后续复用返回的 session.sessionId"}}}})})),server.setRequestHandler(CallToolRequestSchema,async(request,extra)=>{let{arguments:args}=request.params,name=request.params.name==="browser_capture_checkpoint"?"browser_tab_checkpoint":request.params.name;try{if(name===RUN_CODE_TOOL_NAME){let input=args??{},result2=await executeScript(input.code,{...input.browser?{browser:input.browser}:{},...input.session?{session:input.session}:{},...input.timeoutSec!==void 0?{executionTimeoutSec:input.timeoutSec}:{},signal:extra?.signal,source:"mcp"}),tooLarge=Buffer.byteLength(JSON.stringify(result2))>=RESPONSE_SIZE_MAX;return{content:formatResponseWithSizeCheck(result2,name,input),...result2.success&&!tooLarge?{}:{isError:!0}}}if(name!==PLUGIN_INVOKE_TOOL_NAME&&!(name in MCP_TOOL_ACTIONS))throw new Error(`Unknown tool: ${name}`);let result;if(name===PLUGIN_INVOKE_TOOL_NAME)result=await invokePluginTool(args,client.invokePlugin);else{let{session,outputPath,...payload}=args??{};if(name==="browser_set_mock"&&payload.payloadFile){if(!existsSync(payload.payloadFile))throw new Error(`Payload file not found: ${payload.payloadFile}`);let fileData=JSON.parse(readFileSync(payload.payloadFile,"utf-8"));for(let field of["tabId","apiName","mockData","fields","enabled","duration","conditions"])fileData[field]!==void 0&&(payload[field]=fileData[field]);delete payload.payloadFile}let browser=name==="browser_get_capabilities"?payload.browser:void 0;if(name==="browser_get_capabilities"&&delete payload.browser,result=await client.invoke(MCP_TOOL_ACTIONS[name],payload,{...session?{session}:{},...browser?{browser}:{}}),name==="browser_page_download"&&outputPath&&(await client.saveArtifact(result.download,outputPath,session?{session}:{}),result={...result,outputPath}),name==="browser_page_screenshot")return{content:[{type:"image",data:result.data,mimeType:result.meta?.format==="jpeg"?"image/jpeg":"image/png"},{type:"text",text:JSON.stringify({meta:result.meta,...result.session?{session:result.session}:{}})}]};if(name==="browser_run_actions"){let screenshots=(result.results??[]).filter(step=>step.success&&step.action==="page_screenshot"&&step.data?.data);if(screenshots.length)return{content:[...screenshots.map(step=>({type:"image",data:step.data.data,mimeType:step.data.meta?.format==="jpeg"?"image/jpeg":"image/png"})),...formatResponseWithSizeCheck({...result,results:result.results.map(step=>step.action==="page_screenshot"&&step.success?{...step,data:{meta:step.data?.meta}}:step)},name,args)],...result.failedStep!==void 0?{isError:!0}:{}}}}return{content:formatResponseWithSizeCheck(result,name,args),...result?.action?.success===!1||result?.failedStep!==void 0?{isError:!0}:{}}}catch(error2){return log(`Error executing tool ${name}:`,error2),{content:[{type:"text",text:`Error: ${error2 instanceof Error?error2.message:String(error2)}`}],isError:!0}}});let transport=new StdioServerTransport;await server.connect(transport),log("MCP Server started and ready")}process.on("uncaughtException",error2=>{console.error("[MCP Server] Uncaught exception:",error2),process.exit(1)});process.on("unhandledRejection",error2=>{console.error("[MCP Server] Unhandled rejection:",error2),process.exit(1)});main().catch(error2=>{console.error("[MCP Server] Failed to start:",error2),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mearl/mcp-server",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.8",
|
|
4
4
|
"description": "MCP Server for Mearl - enables AI to interact with Chrome browser requests and logs",
|
|
5
|
-
"mcpName": "io.github.
|
|
5
|
+
"mcpName": "io.github.mearlhq/mearl",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/index.js",
|
|
8
8
|
"bin": {
|
|
@@ -26,20 +26,20 @@
|
|
|
26
26
|
"author": "",
|
|
27
27
|
"license": "Apache-2.0",
|
|
28
28
|
"engines": {
|
|
29
|
-
"node": ">=
|
|
29
|
+
"node": ">=20.18.0"
|
|
30
30
|
},
|
|
31
31
|
"publishConfig": {
|
|
32
32
|
"registry": "https://registry.npmjs.org"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"commander": "^
|
|
35
|
+
"commander": "^14.0.3",
|
|
36
36
|
"prompts": "^2.4.2",
|
|
37
|
-
"@mearl/
|
|
38
|
-
"@mearl/
|
|
39
|
-
"@mearl/
|
|
37
|
+
"@mearl/client": "3.0.0-beta.8",
|
|
38
|
+
"@mearl/native-host": "3.0.0-beta.8",
|
|
39
|
+
"@mearl/setup": "3.0.0-beta.8"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@modelcontextprotocol/sdk": "1.
|
|
42
|
+
"@modelcontextprotocol/sdk": "1.32.0",
|
|
43
43
|
"@types/node": "^24.9.1",
|
|
44
44
|
"@types/prompts": "^2.4.9",
|
|
45
45
|
"esbuild": "^0.28.2",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
},
|
|
48
48
|
"repository": {
|
|
49
49
|
"type": "git",
|
|
50
|
-
"url": "git+https://github.com/
|
|
50
|
+
"url": "git+https://github.com/mearlhq/mearl.git",
|
|
51
51
|
"directory": "packages/mcp-server"
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|