@sap-ux/fiori-mcp-server 0.5.2 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1650,7 +1650,7 @@ ${n.message}`:h,_=[v,t,e].filter(Boolean).join(`
|
|
|
1650
1650
|
|
|
1651
1651
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let p=l[1];if(t===l[0]){o(l);continue}if(n.external){let d=n.external.registry.get(l[0])?.id;if(t!==l[0]&&d){o(l);continue}}if(this.metadataRegistry.get(l[0])?.id){o(l);continue}if(p.cycle){o(l);continue}if(p.count>1&&n.reused==="ref"){o(l);continue}}let s=(l,p)=>{let f=this.seen.get(l),d=f.def??f.schema,h={...d};if(f.ref===null)return;let m=f.ref;if(f.ref=null,m){s(m,p);let v=this.seen.get(m).schema;v.$ref&&(p.target==="draft-7"||p.target==="draft-4"||p.target==="openapi-3.0")?(d.allOf=d.allOf??[],d.allOf.push(v)):(Object.assign(d,v),Object.assign(d,h))}f.isParent||this.override({zodSchema:l,jsonSchema:d,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())s(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":this.target==="draft-4"?c.$schema="http://json-schema.org/draft-04/schema#":this.target==="openapi-3.0"||console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(t)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,i.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let p=l[1];p.def&&p.defId&&(u[p.defId]=p.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function Rx(e,t){if(e instanceof BA){let n=new bk(t),i={};for(let s of e._idmap.entries()){let[c,u]=s;n.process(u)}let a={},o={registry:e,uri:t?.uri,defs:i};for(let s of e._idmap.entries()){let[c,u]=s;a[c]=n.emit(u,{...t,external:o})}if(Object.keys(i).length>0){let s=n.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[s]:i}}return{schemas:a}}let r=new bk(t);return r.process(e),r.emit(e,t)}function Jc(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Jc(n.element,r);if(n.type==="set")return Jc(n.valueType,r);if(n.type==="lazy")return Jc(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Jc(n.innerType,r);if(n.type==="intersection")return Jc(n.left,r)||Jc(n.right,r);if(n.type==="record"||n.type==="map")return Jc(n.keyType,r)||Jc(n.valueType,r);if(n.type==="pipe")return Jc(n.in,r)||Jc(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Jc(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Jc(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Jc(i,r))return!0;return!!(n.rest&&Jc(n.rest,r))}return!1}var kGe={};function iC(e){return!!e._zod}function o0(e,t){return iC(e)?Cx(e,t):e.safeParse(t)}function W6(e){var t,r;if(!e)return;let n;if(iC(e)?n=(r=(t=e._zod)===null||t===void 0?void 0:t.def)===null||r===void 0?void 0:r.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function FGe(e){var t;if(iC(e)){let o=(t=e._zod)===null||t===void 0?void 0:t.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=e._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=e.value;if(i!==void 0)return i}var Lx={};Ni(Lx,{$brand:()=>LL,$input:()=>a6,$output:()=>i6,NEVER:()=>w3,TimePrecision:()=>u6,ZodAny:()=>HGe,ZodArray:()=>WGe,ZodBase64:()=>Hle,ZodBase64URL:()=>Gle,ZodBigInt:()=>Sk,ZodBigIntFormat:()=>Wle,ZodBoolean:()=>Ok,ZodCIDRv4:()=>Ble,ZodCIDRv6:()=>zle,ZodCUID:()=>$le,ZodCUID2:()=>Mle,ZodCatch:()=>fKe,ZodCodec:()=>npe,ZodCustom:()=>u5,ZodCustomStringFormat:()=>xk,ZodDate:()=>o5,ZodDefault:()=>oKe,ZodDiscriminatedUnion:()=>XGe,ZodE164:()=>Kle,ZodEmail:()=>Ile,ZodEmoji:()=>Lle,ZodEnum:()=>Ek,ZodError:()=>yle,ZodFile:()=>nKe,ZodFirstPartyTypeKind:()=>ape,ZodFunction:()=>_Ke,ZodGUID:()=>t5,ZodIPv4:()=>Vle,ZodIPv6:()=>Ule,ZodISODate:()=>J6,ZodISODateTime:()=>X6,ZodISODuration:()=>Q6,ZodISOTime:()=>Z6,ZodIntersection:()=>JGe,ZodIssueCode:()=>Cwr,ZodJWT:()=>Yle,ZodKSUID:()=>qle,ZodLazy:()=>vKe,ZodLiteral:()=>rKe,ZodMAC:()=>VGe,ZodMap:()=>eKe,ZodNaN:()=>hKe,ZodNanoID:()=>kle,ZodNever:()=>KGe,ZodNonOptional:()=>tpe,ZodNull:()=>zGe,ZodNullable:()=>aKe,ZodNumber:()=>Tk,ZodNumberFormat:()=>aC,ZodObject:()=>s5,ZodOptional:()=>epe,ZodPipe:()=>rpe,ZodPrefault:()=>cKe,ZodPromise:()=>EKe,ZodReadonly:()=>mKe,ZodRealError:()=>Vu,ZodRecord:()=>Zle,ZodSet:()=>tKe,ZodString:()=>_k,ZodStringFormat:()=>ui,ZodSuccess:()=>pKe,ZodSymbol:()=>UGe,ZodTemplateLiteral:()=>yKe,ZodTransform:()=>iKe,ZodTuple:()=>ZGe,ZodType:()=>Ar,ZodULID:()=>Fle,ZodURL:()=>i5,ZodUUID:()=>hy,ZodUndefined:()=>BGe,ZodUnion:()=>Jle,ZodUnknown:()=>GGe,ZodVoid:()=>YGe,ZodXID:()=>jle,_ZodString:()=>Nle,_default:()=>sKe,_function:()=>Ewr,any:()=>a5,array:()=>Bt,base64:()=>UCr,base64url:()=>BCr,bigint:()=>ewr,boolean:()=>Ji,catch:()=>dKe,check:()=>_wr,cidrv4:()=>qCr,cidrv6:()=>VCr,clone:()=>Ts,codec:()=>ywr,coerce:()=>ope,config:()=>ga,core:()=>rp,cuid:()=>ICr,cuid2:()=>RCr,custom:()=>ipe,date:()=>owr,decode:()=>Tle,decodeAsync:()=>Sle,describe:()=>xwr,discriminatedUnion:()=>c5,e164:()=>zCr,email:()=>TCr,emoji:()=>DCr,encode:()=>xle,encodeAsync:()=>Ole,endsWith:()=>ZA,enum:()=>$n,file:()=>dwr,flattenError:()=>DA,float32:()=>XCr,float64:()=>JCr,formatError:()=>NA,function:()=>Ewr,getErrorMap:()=>Pwr,globalRegistry:()=>rc,gt:()=>Bh,gte:()=>nc,guid:()=>OCr,hash:()=>WCr,hex:()=>YCr,hostname:()=>KCr,httpUrl:()=>PCr,includes:()=>XA,instanceof:()=>Owr,int:()=>Dle,int32:()=>ZCr,int64:()=>twr,intersection:()=>Ck,ipv4:()=>MCr,ipv6:()=>jCr,iso:()=>e5,json:()=>Awr,jwt:()=>HCr,keyof:()=>swr,ksuid:()=>$Cr,lazy:()=>bKe,length:()=>Nx,literal:()=>dt,locales:()=>UA,looseObject:()=>np,lowercase:()=>YA,lt:()=>Uh,lte:()=>qu,mac:()=>FCr,map:()=>lwr,maxLength:()=>Dx,maxSize:()=>Px,meta:()=>Twr,mime:()=>QA,minLength:()=>dy,minSize:()=>a0,multipleOf:()=>i0,nan:()=>gwr,nanoid:()=>NCr,nativeEnum:()=>fwr,negative:()=>F6,never:()=>Xle,nonnegative:()=>q6,nonoptional:()=>lKe,nonpositive:()=>j6,normalize:()=>eC,null:()=>Ak,nullable:()=>r5,nullish:()=>hwr,number:()=>kn,object:()=>Ae,optional:()=>pt,overwrite:()=>Pd,parse:()=>vle,parseAsync:()=>ble,partialRecord:()=>uwr,pipe:()=>n5,positive:()=>M6,prefault:()=>uKe,preprocess:()=>l5,prettifyError:()=>I3,promise:()=>bwr,property:()=>V6,readonly:()=>gKe,record:()=>vi,refine:()=>xKe,regex:()=>KA,regexes:()=>ju,registry:()=>JL,safeDecode:()=>Cle,safeDecodeAsync:()=>Ple,safeEncode:()=>Ale,safeEncodeAsync:()=>wle,safeParse:()=>Ele,safeParseAsync:()=>_le,set:()=>pwr,setErrorMap:()=>wwr,size:()=>GA,slugify:()=>vk,startsWith:()=>JA,strictObject:()=>cwr,string:()=>re,stringFormat:()=>GCr,stringbool:()=>Swr,success:()=>mwr,superRefine:()=>TKe,symbol:()=>nwr,templateLiteral:()=>vwr,toJSONSchema:()=>Rx,toLowerCase:()=>rC,toUpperCase:()=>nC,transform:()=>Qle,treeifyError:()=>N3,trim:()=>tC,tuple:()=>QGe,uint32:()=>QCr,uint64:()=>rwr,ulid:()=>LCr,undefined:()=>iwr,union:()=>pn,unknown:()=>li,uppercase:()=>WA,url:()=>Rle,util:()=>Le,uuid:()=>SCr,uuidv4:()=>ACr,uuidv6:()=>CCr,uuidv7:()=>wCr,void:()=>awr,xid:()=>kCr});var e5={};Ni(e5,{ZodISODate:()=>J6,ZodISODateTime:()=>X6,ZodISODuration:()=>Q6,ZodISOTime:()=>Z6,date:()=>hle,datetime:()=>dle,duration:()=>gle,time:()=>mle});var X6=ne("ZodISODateTime",(e,t)=>{o8.init(e,t),ui.init(e,t)});function dle(e){return l6(X6,e)}var J6=ne("ZodISODate",(e,t)=>{s8.init(e,t),ui.init(e,t)});function hle(e){return p6(J6,e)}var Z6=ne("ZodISOTime",(e,t)=>{c8.init(e,t),ui.init(e,t)});function mle(e){return f6(Z6,e)}var Q6=ne("ZodISODuration",(e,t)=>{u8.init(e,t),ui.init(e,t)});function gle(e){return d6(Q6,e)}var qGe=(e,t)=>{VL.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>NA(e,r)},flatten:{value:r=>DA(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,CA,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,CA,2)}},isEmpty:{get(){return e.issues.length===0}}})},yle=ne("ZodError",qGe),Vu=ne("ZodError",qGe,{Parent:Error});var vle=IA(Vu),ble=LA(Vu),Ele=$A(Vu),_le=MA(Vu),xle=R3(Vu),Tle=L3(Vu),Ole=k3(Vu),Sle=$3(Vu),Ale=M3(Vu),Cle=F3(Vu),wle=j3(Vu),Ple=q3(Vu);var Ar=ne("ZodType",(e,t)=>(Wt.init(e,t),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone(Le.mergeDefs(t,{checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]})),e.clone=(r,n)=>Ts(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>vle(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>Ele(e,r,n),e.parseAsync=async(r,n)=>ble(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>_le(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>xle(e,r,n),e.decode=(r,n)=>Tle(e,r,n),e.encodeAsync=async(r,n)=>Ole(e,r,n),e.decodeAsync=async(r,n)=>Sle(e,r,n),e.safeEncode=(r,n)=>Ale(e,r,n),e.safeDecode=(r,n)=>Cle(e,r,n),e.safeEncodeAsync=async(r,n)=>wle(e,r,n),e.safeDecodeAsync=async(r,n)=>Ple(e,r,n),e.refine=(r,n)=>e.check(xKe(r,n)),e.superRefine=r=>e.check(TKe(r)),e.overwrite=r=>e.check(Pd(r)),e.optional=()=>pt(e),e.nullable=()=>r5(e),e.nullish=()=>pt(r5(e)),e.nonoptional=r=>lKe(e,r),e.array=()=>Bt(e),e.or=r=>pn([e,r]),e.and=r=>Ck(e,r),e.transform=r=>n5(e,Qle(r)),e.default=r=>sKe(e,r),e.prefault=r=>uKe(e,r),e.catch=r=>dKe(e,r),e.pipe=r=>n5(e,r),e.readonly=()=>gKe(e),e.describe=r=>{let n=e.clone();return rc.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return rc.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return rc.get(e);let n=e.clone();return rc.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),Nle=ne("_ZodString",(e,t)=>{n0.init(e,t),Ar.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(KA(...n)),e.includes=(...n)=>e.check(XA(...n)),e.startsWith=(...n)=>e.check(JA(...n)),e.endsWith=(...n)=>e.check(ZA(...n)),e.min=(...n)=>e.check(dy(...n)),e.max=(...n)=>e.check(Dx(...n)),e.length=(...n)=>e.check(Nx(...n)),e.nonempty=(...n)=>e.check(dy(1,...n)),e.lowercase=n=>e.check(YA(n)),e.uppercase=n=>e.check(WA(n)),e.trim=()=>e.check(tC()),e.normalize=(...n)=>e.check(eC(...n)),e.toLowerCase=()=>e.check(rC()),e.toUpperCase=()=>e.check(nC()),e.slugify=()=>e.check(vk())}),_k=ne("ZodString",(e,t)=>{n0.init(e,t),Nle.init(e,t),e.email=r=>e.check(ZL(Ile,r)),e.url=r=>e.check(HA(i5,r)),e.jwt=r=>e.check(yk(Yle,r)),e.emoji=r=>e.check(nk(Lle,r)),e.guid=r=>e.check(zA(t5,r)),e.uuid=r=>e.check(QL(hy,r)),e.uuidv4=r=>e.check(ek(hy,r)),e.uuidv6=r=>e.check(tk(hy,r)),e.uuidv7=r=>e.check(rk(hy,r)),e.nanoid=r=>e.check(ik(kle,r)),e.guid=r=>e.check(zA(t5,r)),e.cuid=r=>e.check(ak($le,r)),e.cuid2=r=>e.check(ok(Mle,r)),e.ulid=r=>e.check(sk(Fle,r)),e.base64=r=>e.check(hk(Hle,r)),e.base64url=r=>e.check(mk(Gle,r)),e.xid=r=>e.check(ck(jle,r)),e.ksuid=r=>e.check(uk(qle,r)),e.ipv4=r=>e.check(lk(Vle,r)),e.ipv6=r=>e.check(pk(Ule,r)),e.cidrv4=r=>e.check(fk(Ble,r)),e.cidrv6=r=>e.check(dk(zle,r)),e.e164=r=>e.check(gk(Kle,r)),e.datetime=r=>e.check(dle(r)),e.date=r=>e.check(hle(r)),e.time=r=>e.check(mle(r)),e.duration=r=>e.check(gle(r))});function re(e){return o6(_k,e)}var ui=ne("ZodStringFormat",(e,t)=>{Kn.init(e,t),Nle.init(e,t)}),Ile=ne("ZodEmail",(e,t)=>{J3.init(e,t),ui.init(e,t)});function TCr(e){return ZL(Ile,e)}var t5=ne("ZodGUID",(e,t)=>{W3.init(e,t),ui.init(e,t)});function OCr(e){return zA(t5,e)}var hy=ne("ZodUUID",(e,t)=>{X3.init(e,t),ui.init(e,t)});function SCr(e){return QL(hy,e)}function ACr(e){return ek(hy,e)}function CCr(e){return tk(hy,e)}function wCr(e){return rk(hy,e)}var i5=ne("ZodURL",(e,t)=>{Z3.init(e,t),ui.init(e,t)});function Rle(e){return HA(i5,e)}function PCr(e){return HA(i5,{protocol:/^https?$/,hostname:ju.domain,...Le.normalizeParams(e)})}var Lle=ne("ZodEmoji",(e,t)=>{Q3.init(e,t),ui.init(e,t)});function DCr(e){return nk(Lle,e)}var kle=ne("ZodNanoID",(e,t)=>{e8.init(e,t),ui.init(e,t)});function NCr(e){return ik(kle,e)}var $le=ne("ZodCUID",(e,t)=>{t8.init(e,t),ui.init(e,t)});function ICr(e){return ak($le,e)}var Mle=ne("ZodCUID2",(e,t)=>{r8.init(e,t),ui.init(e,t)});function RCr(e){return ok(Mle,e)}var Fle=ne("ZodULID",(e,t)=>{n8.init(e,t),ui.init(e,t)});function LCr(e){return sk(Fle,e)}var jle=ne("ZodXID",(e,t)=>{i8.init(e,t),ui.init(e,t)});function kCr(e){return ck(jle,e)}var qle=ne("ZodKSUID",(e,t)=>{a8.init(e,t),ui.init(e,t)});function $Cr(e){return uk(qle,e)}var Vle=ne("ZodIPv4",(e,t)=>{l8.init(e,t),ui.init(e,t)});function MCr(e){return lk(Vle,e)}var VGe=ne("ZodMAC",(e,t)=>{f8.init(e,t),ui.init(e,t)});function FCr(e){return c6(VGe,e)}var Ule=ne("ZodIPv6",(e,t)=>{p8.init(e,t),ui.init(e,t)});function jCr(e){return pk(Ule,e)}var Ble=ne("ZodCIDRv4",(e,t)=>{d8.init(e,t),ui.init(e,t)});function qCr(e){return fk(Ble,e)}var zle=ne("ZodCIDRv6",(e,t)=>{h8.init(e,t),ui.init(e,t)});function VCr(e){return dk(zle,e)}var Hle=ne("ZodBase64",(e,t)=>{m8.init(e,t),ui.init(e,t)});function UCr(e){return hk(Hle,e)}var Gle=ne("ZodBase64URL",(e,t)=>{g8.init(e,t),ui.init(e,t)});function BCr(e){return mk(Gle,e)}var Kle=ne("ZodE164",(e,t)=>{y8.init(e,t),ui.init(e,t)});function zCr(e){return gk(Kle,e)}var Yle=ne("ZodJWT",(e,t)=>{v8.init(e,t),ui.init(e,t)});function HCr(e){return yk(Yle,e)}var xk=ne("ZodCustomStringFormat",(e,t)=>{b8.init(e,t),ui.init(e,t)});function GCr(e,t,r={}){return Ix(xk,e,t,r)}function KCr(e){return Ix(xk,"hostname",ju.hostname,e)}function YCr(e){return Ix(xk,"hex",ju.hex,e)}function WCr(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,i=ju[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return Ix(xk,n,i,t)}var Tk=ne("ZodNumber",(e,t)=>{HL.init(e,t),Ar.init(e,t),e.gt=(n,i)=>e.check(Bh(n,i)),e.gte=(n,i)=>e.check(nc(n,i)),e.min=(n,i)=>e.check(nc(n,i)),e.lt=(n,i)=>e.check(Uh(n,i)),e.lte=(n,i)=>e.check(qu(n,i)),e.max=(n,i)=>e.check(qu(n,i)),e.int=n=>e.check(Dle(n)),e.safe=n=>e.check(Dle(n)),e.positive=n=>e.check(Bh(0,n)),e.nonnegative=n=>e.check(nc(0,n)),e.negative=n=>e.check(Uh(0,n)),e.nonpositive=n=>e.check(qu(0,n)),e.multipleOf=(n,i)=>e.check(i0(n,i)),e.step=(n,i)=>e.check(i0(n,i)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function kn(e){return h6(Tk,e)}var aC=ne("ZodNumberFormat",(e,t)=>{E8.init(e,t),Tk.init(e,t)});function Dle(e){return g6(aC,e)}function XCr(e){return y6(aC,e)}function JCr(e){return v6(aC,e)}function ZCr(e){return b6(aC,e)}function QCr(e){return E6(aC,e)}var Ok=ne("ZodBoolean",(e,t)=>{qA.init(e,t),Ar.init(e,t)});function Ji(e){return _6(Ok,e)}var Sk=ne("ZodBigInt",(e,t)=>{GL.init(e,t),Ar.init(e,t),e.gte=(n,i)=>e.check(nc(n,i)),e.min=(n,i)=>e.check(nc(n,i)),e.gt=(n,i)=>e.check(Bh(n,i)),e.gte=(n,i)=>e.check(nc(n,i)),e.min=(n,i)=>e.check(nc(n,i)),e.lt=(n,i)=>e.check(Uh(n,i)),e.lte=(n,i)=>e.check(qu(n,i)),e.max=(n,i)=>e.check(qu(n,i)),e.positive=n=>e.check(Bh(BigInt(0),n)),e.negative=n=>e.check(Uh(BigInt(0),n)),e.nonpositive=n=>e.check(qu(BigInt(0),n)),e.nonnegative=n=>e.check(nc(BigInt(0),n)),e.multipleOf=(n,i)=>e.check(i0(n,i));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function ewr(e){return T6(Sk,e)}var Wle=ne("ZodBigIntFormat",(e,t)=>{_8.init(e,t),Sk.init(e,t)});function twr(e){return S6(Wle,e)}function rwr(e){return A6(Wle,e)}var UGe=ne("ZodSymbol",(e,t)=>{x8.init(e,t),Ar.init(e,t)});function nwr(e){return C6(UGe,e)}var BGe=ne("ZodUndefined",(e,t)=>{T8.init(e,t),Ar.init(e,t)});function iwr(e){return w6(BGe,e)}var zGe=ne("ZodNull",(e,t)=>{O8.init(e,t),Ar.init(e,t)});function Ak(e){return P6(zGe,e)}var HGe=ne("ZodAny",(e,t)=>{S8.init(e,t),Ar.init(e,t)});function a5(){return D6(HGe)}var GGe=ne("ZodUnknown",(e,t)=>{A8.init(e,t),Ar.init(e,t)});function li(){return N6(GGe)}var KGe=ne("ZodNever",(e,t)=>{C8.init(e,t),Ar.init(e,t)});function Xle(e){return I6(KGe,e)}var YGe=ne("ZodVoid",(e,t)=>{w8.init(e,t),Ar.init(e,t)});function awr(e){return R6(YGe,e)}var o5=ne("ZodDate",(e,t)=>{P8.init(e,t),Ar.init(e,t),e.min=(n,i)=>e.check(nc(n,i)),e.max=(n,i)=>e.check(qu(n,i));let r=e._zod.bag;e.minDate=r.minimum?new Date(r.minimum):null,e.maxDate=r.maximum?new Date(r.maximum):null});function owr(e){return L6(o5,e)}var WGe=ne("ZodArray",(e,t)=>{D8.init(e,t),Ar.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(dy(r,n)),e.nonempty=r=>e.check(dy(1,r)),e.max=(r,n)=>e.check(Dx(r,n)),e.length=(r,n)=>e.check(Nx(r,n)),e.unwrap=()=>e.element});function Bt(e,t){return fle(WGe,e,t)}function swr(e){let t=e._zod.def.shape;return $n(Object.keys(t))}var s5=ne("ZodObject",(e,t)=>{ple.init(e,t),Ar.init(e,t),Le.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>$n(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:li()}),e.loose=()=>e.clone({...e._zod.def,catchall:li()}),e.strict=()=>e.clone({...e._zod.def,catchall:Xle()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Le.extend(e,r),e.safeExtend=r=>Le.safeExtend(e,r),e.merge=r=>Le.merge(e,r),e.pick=r=>Le.pick(e,r),e.omit=r=>Le.omit(e,r),e.partial=(...r)=>Le.partial(epe,e,r[0]),e.required=(...r)=>Le.required(tpe,e,r[0])});function Ae(e,t){let r={type:"object",shape:e??{},...Le.normalizeParams(t)};return new s5(r)}function cwr(e,t){return new s5({type:"object",shape:e,catchall:Xle(),...Le.normalizeParams(t)})}function np(e,t){return new s5({type:"object",shape:e,catchall:li(),...Le.normalizeParams(t)})}var Jle=ne("ZodUnion",(e,t)=>{KL.init(e,t),Ar.init(e,t),e.options=t.options});function pn(e,t){return new Jle({type:"union",options:e,...Le.normalizeParams(t)})}var XGe=ne("ZodDiscriminatedUnion",(e,t)=>{Jle.init(e,t),N8.init(e,t)});function c5(e,t,r){return new XGe({type:"union",options:t,discriminator:e,...Le.normalizeParams(r)})}var JGe=ne("ZodIntersection",(e,t)=>{I8.init(e,t),Ar.init(e,t)});function Ck(e,t){return new JGe({type:"intersection",left:e,right:t})}var ZGe=ne("ZodTuple",(e,t)=>{YL.init(e,t),Ar.init(e,t),e.rest=r=>e.clone({...e._zod.def,rest:r})});function QGe(e,t,r){let n=t instanceof Wt,i=n?r:t,a=n?t:null;return new ZGe({type:"tuple",items:e,rest:a,...Le.normalizeParams(i)})}var Zle=ne("ZodRecord",(e,t)=>{R8.init(e,t),Ar.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function vi(e,t,r){return new Zle({type:"record",keyType:e,valueType:t,...Le.normalizeParams(r)})}function uwr(e,t,r){let n=Ts(e);return n._zod.values=void 0,new Zle({type:"record",keyType:n,valueType:t,...Le.normalizeParams(r)})}var eKe=ne("ZodMap",(e,t)=>{L8.init(e,t),Ar.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function lwr(e,t,r){return new eKe({type:"map",keyType:e,valueType:t,...Le.normalizeParams(r)})}var tKe=ne("ZodSet",(e,t)=>{k8.init(e,t),Ar.init(e,t),e.min=(...r)=>e.check(a0(...r)),e.nonempty=r=>e.check(a0(1,r)),e.max=(...r)=>e.check(Px(...r)),e.size=(...r)=>e.check(GA(...r))});function pwr(e,t){return new tKe({type:"set",valueType:e,...Le.normalizeParams(t)})}var Ek=ne("ZodEnum",(e,t)=>{$8.init(e,t),Ar.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{let a={};for(let o of n)if(r.has(o))a[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ek({...t,checks:[],...Le.normalizeParams(i),entries:a})},e.exclude=(n,i)=>{let a={...t.entries};for(let o of n)if(r.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Ek({...t,checks:[],...Le.normalizeParams(i),entries:a})}});function $n(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Ek({type:"enum",entries:r,...Le.normalizeParams(t)})}function fwr(e,t){return new Ek({type:"enum",entries:e,...Le.normalizeParams(t)})}var rKe=ne("ZodLiteral",(e,t)=>{M8.init(e,t),Ar.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function dt(e,t){return new rKe({type:"literal",values:Array.isArray(e)?e:[e],...Le.normalizeParams(t)})}var nKe=ne("ZodFile",(e,t)=>{F8.init(e,t),Ar.init(e,t),e.min=(r,n)=>e.check(a0(r,n)),e.max=(r,n)=>e.check(Px(r,n)),e.mime=(r,n)=>e.check(QA(Array.isArray(r)?r:[r],n))});function dwr(e){return U6(nKe,e)}var iKe=ne("ZodTransform",(e,t)=>{j8.init(e,t),Ar.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Jb(e.constructor.name);r.addIssue=a=>{if(typeof a=="string")r.issues.push(Le.issue(a,r.value,t));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),r.issues.push(Le.issue(o))}};let i=t.transform(r.value,r);return i instanceof Promise?i.then(a=>(r.value=a,r)):(r.value=i,r)}});function Qle(e){return new iKe({type:"transform",transform:e})}var epe=ne("ZodOptional",(e,t)=>{q8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function pt(e){return new epe({type:"optional",innerType:e})}var aKe=ne("ZodNullable",(e,t)=>{V8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function r5(e){return new aKe({type:"nullable",innerType:e})}function hwr(e){return pt(r5(e))}var oKe=ne("ZodDefault",(e,t)=>{U8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function sKe(e,t){return new oKe({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Le.shallowClone(t)}})}var cKe=ne("ZodPrefault",(e,t)=>{B8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function uKe(e,t){return new cKe({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Le.shallowClone(t)}})}var tpe=ne("ZodNonOptional",(e,t)=>{z8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function lKe(e,t){return new tpe({type:"nonoptional",innerType:e,...Le.normalizeParams(t)})}var pKe=ne("ZodSuccess",(e,t)=>{H8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function mwr(e){return new pKe({type:"success",innerType:e})}var fKe=ne("ZodCatch",(e,t)=>{G8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dKe(e,t){return new fKe({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var hKe=ne("ZodNaN",(e,t)=>{K8.init(e,t),Ar.init(e,t)});function gwr(e){return $6(hKe,e)}var rpe=ne("ZodPipe",(e,t)=>{Y8.init(e,t),Ar.init(e,t),e.in=t.in,e.out=t.out});function n5(e,t){return new rpe({type:"pipe",in:e,out:t})}var npe=ne("ZodCodec",(e,t)=>{rpe.init(e,t),VA.init(e,t)});function ywr(e,t,r){return new npe({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}var mKe=ne("ZodReadonly",(e,t)=>{W8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function gKe(e){return new mKe({type:"readonly",innerType:e})}var yKe=ne("ZodTemplateLiteral",(e,t)=>{X8.init(e,t),Ar.init(e,t)});function vwr(e,t){return new yKe({type:"template_literal",parts:e,...Le.normalizeParams(t)})}var vKe=ne("ZodLazy",(e,t)=>{Q8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.getter()});function bKe(e){return new vKe({type:"lazy",getter:e})}var EKe=ne("ZodPromise",(e,t)=>{Z8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function bwr(e){return new EKe({type:"promise",innerType:e})}var _Ke=ne("ZodFunction",(e,t)=>{J8.init(e,t),Ar.init(e,t)});function Ewr(e){return new _Ke({type:"function",input:Array.isArray(e?.input)?QGe(e?.input):e?.input??Bt(li()),output:e?.output??li()})}var u5=ne("ZodCustom",(e,t)=>{e6.init(e,t),Ar.init(e,t)});function _wr(e){let t=new ri({check:"custom"});return t._zod.check=e,t}function ipe(e,t){return B6(u5,e??(()=>!0),t)}function xKe(e,t={}){return z6(u5,e,t)}function TKe(e){return H6(e)}var xwr=G6,Twr=K6;function Owr(e,t={error:`Input not instance of ${e.name}`}){let r=new u5({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...Le.normalizeParams(t)});return r._zod.bag.Class=e,r}var Swr=(...e)=>Y6({Codec:npe,Boolean:Ok,String:_k},...e);function Awr(e){let t=bKe(()=>pn([re(e),kn(),Ji(),Ak(),Bt(t),vi(re(),t)]));return t}function l5(e,t){return n5(Qle(e),t)}var Cwr={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function wwr(e){ga({customError:e})}function Pwr(){return ga().customError}var ape;ape||(ape={});var ope={};Ni(ope,{bigint:()=>Rwr,boolean:()=>Iwr,date:()=>Lwr,number:()=>Nwr,string:()=>Dwr});function Dwr(e){return s6(_k,e)}function Nwr(e){return m6(Tk,e)}function Iwr(e){return x6(Ok,e)}function Rwr(e){return O6(Sk,e)}function Lwr(e){return k6(o5,e)}ga(t6());var cpe="2025-11-25";var OKe=[cpe,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Hh="io.modelcontextprotocol/related-task",f5="2.0",zh=ipe(e=>e!==null&&(typeof e=="object"||typeof e=="function")),SKe=pn([re(),kn().int()]),AKe=re(),$wr=np({ttl:pn([kn(),Ak()]).optional(),pollInterval:kn().optional()}),upe=np({taskId:re()}),Mwr=np({progressToken:SKe.optional(),[Hh]:upe.optional()}),Uu=np({task:$wr.optional(),_meta:Mwr.optional()}),Os=Ae({method:re(),params:Uu.optional()}),kx=np({_meta:Ae({[Hh]:pt(upe)}).passthrough().optional()}),nf=Ae({method:re(),params:kx.optional()}),ic=np({_meta:np({[Hh]:upe.optional()}).optional()}),d5=pn([re(),kn().int()]),CKe=Ae({jsonrpc:dt(f5),id:d5,...Os.shape}).strict(),lpe=e=>CKe.safeParse(e).success,wKe=Ae({jsonrpc:dt(f5),...nf.shape}).strict(),PKe=e=>wKe.safeParse(e).success,DKe=Ae({jsonrpc:dt(f5),id:d5,result:ic}).strict(),wk=e=>DKe.safeParse(e).success,an;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(an||(an={}));var NKe=Ae({jsonrpc:dt(f5),id:d5,error:Ae({code:kn().int(),message:re(),data:pt(li())})}).strict(),IKe=e=>NKe.safeParse(e).success,RKe=pn([CKe,wKe,DKe,NKe]),h5=ic.strict(),Fwr=kx.extend({requestId:d5,reason:re().optional()}),m5=nf.extend({method:dt("notifications/cancelled"),params:Fwr}),jwr=Ae({src:re(),mimeType:re().optional(),sizes:Bt(re()).optional()}),Pk=Ae({icons:Bt(jwr).optional()}),oC=Ae({name:re(),title:re().optional()}),LKe=oC.extend({...oC.shape,...Pk.shape,version:re(),websiteUrl:re().optional()}),qwr=Ck(Ae({applyDefaults:Ji().optional()}),vi(re(),li())),Vwr=l5(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ck(Ae({form:qwr.optional(),url:zh.optional()}),vi(re(),li()).optional())),Uwr=Ae({list:pt(Ae({}).passthrough()),cancel:pt(Ae({}).passthrough()),requests:pt(Ae({sampling:pt(Ae({createMessage:pt(Ae({}).passthrough())}).passthrough()),elicitation:pt(Ae({create:pt(Ae({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),Bwr=Ae({list:pt(Ae({}).passthrough()),cancel:pt(Ae({}).passthrough()),requests:pt(Ae({tools:pt(Ae({call:pt(Ae({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),zwr=Ae({experimental:vi(re(),zh).optional(),sampling:Ae({context:zh.optional(),tools:zh.optional()}).optional(),elicitation:Vwr.optional(),roots:Ae({listChanged:Ji().optional()}).optional(),tasks:pt(Uwr)}),Hwr=Uu.extend({protocolVersion:re(),capabilities:zwr,clientInfo:LKe}),ppe=Os.extend({method:dt("initialize"),params:Hwr});var Gwr=Ae({experimental:vi(re(),zh).optional(),logging:zh.optional(),completions:zh.optional(),prompts:pt(Ae({listChanged:pt(Ji())})),resources:Ae({subscribe:Ji().optional(),listChanged:Ji().optional()}).optional(),tools:Ae({listChanged:Ji().optional()}).optional(),tasks:pt(Bwr)}).passthrough(),Kwr=ic.extend({protocolVersion:re(),capabilities:Gwr,serverInfo:LKe,instructions:re().optional()}),fpe=nf.extend({method:dt("notifications/initialized")});var g5=Os.extend({method:dt("ping")}),Ywr=Ae({progress:kn(),total:pt(kn()),message:pt(re())}),Wwr=Ae({...kx.shape,...Ywr.shape,progressToken:SKe}),y5=nf.extend({method:dt("notifications/progress"),params:Wwr}),Xwr=Uu.extend({cursor:AKe.optional()}),Dk=Os.extend({params:Xwr.optional()}),Nk=ic.extend({nextCursor:pt(AKe)}),Ik=Ae({taskId:re(),status:$n(["working","input_required","completed","failed","cancelled"]),ttl:pn([kn(),Ak()]),createdAt:re(),lastUpdatedAt:re(),pollInterval:pt(kn()),statusMessage:pt(re())}),sC=ic.extend({task:Ik}),Jwr=kx.merge(Ik),Rk=nf.extend({method:dt("notifications/tasks/status"),params:Jwr}),v5=Os.extend({method:dt("tasks/get"),params:Uu.extend({taskId:re()})}),b5=ic.merge(Ik),E5=Os.extend({method:dt("tasks/result"),params:Uu.extend({taskId:re()})}),_5=Dk.extend({method:dt("tasks/list")}),x5=Nk.extend({tasks:Bt(Ik)}),kKe=Os.extend({method:dt("tasks/cancel"),params:Uu.extend({taskId:re()})}),$Ke=ic.merge(Ik),MKe=Ae({uri:re(),mimeType:pt(re()),_meta:vi(re(),li()).optional()}),FKe=MKe.extend({text:re()}),dpe=re().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),jKe=MKe.extend({blob:dpe}),qKe=Ae({...oC.shape,...Pk.shape,uri:re(),description:pt(re()),mimeType:pt(re()),_meta:pt(np({}))}),Zwr=Ae({...oC.shape,...Pk.shape,uriTemplate:re(),description:pt(re()),mimeType:pt(re()),_meta:pt(np({}))}),Qwr=Dk.extend({method:dt("resources/list")}),ePr=Nk.extend({resources:Bt(qKe)}),tPr=Dk.extend({method:dt("resources/templates/list")}),rPr=Nk.extend({resourceTemplates:Bt(Zwr)}),hpe=Uu.extend({uri:re()}),nPr=hpe,iPr=Os.extend({method:dt("resources/read"),params:nPr}),aPr=ic.extend({contents:Bt(pn([FKe,jKe]))}),oPr=nf.extend({method:dt("notifications/resources/list_changed")}),sPr=hpe,cPr=Os.extend({method:dt("resources/subscribe"),params:sPr}),uPr=hpe,lPr=Os.extend({method:dt("resources/unsubscribe"),params:uPr}),pPr=kx.extend({uri:re()}),fPr=nf.extend({method:dt("notifications/resources/updated"),params:pPr}),dPr=Ae({name:re(),description:pt(re()),required:pt(Ji())}),hPr=Ae({...oC.shape,...Pk.shape,description:pt(re()),arguments:pt(Bt(dPr)),_meta:pt(np({}))}),mPr=Dk.extend({method:dt("prompts/list")}),gPr=Nk.extend({prompts:Bt(hPr)}),yPr=Uu.extend({name:re(),arguments:vi(re(),re()).optional()}),vPr=Os.extend({method:dt("prompts/get"),params:yPr}),mpe=Ae({type:dt("text"),text:re(),_meta:vi(re(),li()).optional()}),gpe=Ae({type:dt("image"),data:dpe,mimeType:re(),_meta:vi(re(),li()).optional()}),ype=Ae({type:dt("audio"),data:dpe,mimeType:re(),_meta:vi(re(),li()).optional()}),bPr=Ae({type:dt("tool_use"),name:re(),id:re(),input:Ae({}).passthrough(),_meta:pt(Ae({}).passthrough())}).passthrough(),EPr=Ae({type:dt("resource"),resource:pn([FKe,jKe]),_meta:vi(re(),li()).optional()}),_Pr=qKe.extend({type:dt("resource_link")}),vpe=pn([mpe,gpe,ype,_Pr,EPr]),xPr=Ae({role:$n(["user","assistant"]),content:vpe}),TPr=ic.extend({description:pt(re()),messages:Bt(xPr)}),OPr=nf.extend({method:dt("notifications/prompts/list_changed")}),SPr=Ae({title:re().optional(),readOnlyHint:Ji().optional(),destructiveHint:Ji().optional(),idempotentHint:Ji().optional(),openWorldHint:Ji().optional()}),APr=Ae({taskSupport:$n(["required","optional","forbidden"]).optional()}),VKe=Ae({...oC.shape,...Pk.shape,description:re().optional(),inputSchema:Ae({type:dt("object"),properties:vi(re(),zh).optional(),required:Bt(re()).optional()}).catchall(li()),outputSchema:Ae({type:dt("object"),properties:vi(re(),zh).optional(),required:Bt(re()).optional()}).catchall(li()).optional(),annotations:pt(SPr),execution:pt(APr),_meta:vi(re(),li()).optional()}),bpe=Dk.extend({method:dt("tools/list")}),CPr=Nk.extend({tools:Bt(VKe)}),T5=ic.extend({content:Bt(vpe).default([]),structuredContent:vi(re(),li()).optional(),isError:pt(Ji())}),sSi=T5.or(ic.extend({toolResult:li()})),wPr=Uu.extend({name:re(),arguments:pt(vi(re(),li()))}),Lk=Os.extend({method:dt("tools/call"),params:wPr}),PPr=nf.extend({method:dt("notifications/tools/list_changed")}),kk=$n(["debug","info","notice","warning","error","critical","alert","emergency"]),DPr=Uu.extend({level:kk}),Epe=Os.extend({method:dt("logging/setLevel"),params:DPr}),NPr=kx.extend({level:kk,logger:re().optional(),data:li()}),IPr=nf.extend({method:dt("notifications/message"),params:NPr}),RPr=Ae({name:re().optional()}),LPr=Ae({hints:pt(Bt(RPr)),costPriority:pt(kn().min(0).max(1)),speedPriority:pt(kn().min(0).max(1)),intelligencePriority:pt(kn().min(0).max(1))}),kPr=Ae({mode:pt($n(["auto","required","none"]))}),$Pr=Ae({type:dt("tool_result"),toolUseId:re().describe("The unique identifier for the corresponding tool call."),content:Bt(vpe).default([]),structuredContent:Ae({}).passthrough().optional(),isError:pt(Ji()),_meta:pt(Ae({}).passthrough())}).passthrough(),MPr=c5("type",[mpe,gpe,ype]),p5=c5("type",[mpe,gpe,ype,bPr,$Pr]),FPr=Ae({role:$n(["user","assistant"]),content:pn([p5,Bt(p5)]),_meta:pt(Ae({}).passthrough())}).passthrough(),jPr=Uu.extend({messages:Bt(FPr),modelPreferences:LPr.optional(),systemPrompt:re().optional(),includeContext:$n(["none","thisServer","allServers"]).optional(),temperature:kn().optional(),maxTokens:kn().int(),stopSequences:Bt(re()).optional(),metadata:zh.optional(),tools:pt(Bt(VKe)),toolChoice:pt(kPr)}),qPr=Os.extend({method:dt("sampling/createMessage"),params:jPr}),_pe=ic.extend({model:re(),stopReason:pt($n(["endTurn","stopSequence","maxTokens"]).or(re())),role:$n(["user","assistant"]),content:MPr}),xpe=ic.extend({model:re(),stopReason:pt($n(["endTurn","stopSequence","maxTokens","toolUse"]).or(re())),role:$n(["user","assistant"]),content:pn([p5,Bt(p5)])}),VPr=Ae({type:dt("boolean"),title:re().optional(),description:re().optional(),default:Ji().optional()}),UPr=Ae({type:dt("string"),title:re().optional(),description:re().optional(),minLength:kn().optional(),maxLength:kn().optional(),format:$n(["email","uri","date","date-time"]).optional(),default:re().optional()}),BPr=Ae({type:$n(["number","integer"]),title:re().optional(),description:re().optional(),minimum:kn().optional(),maximum:kn().optional(),default:kn().optional()}),zPr=Ae({type:dt("string"),title:re().optional(),description:re().optional(),enum:Bt(re()),default:re().optional()}),HPr=Ae({type:dt("string"),title:re().optional(),description:re().optional(),oneOf:Bt(Ae({const:re(),title:re()})),default:re().optional()}),GPr=Ae({type:dt("string"),title:re().optional(),description:re().optional(),enum:Bt(re()),enumNames:Bt(re()).optional(),default:re().optional()}),KPr=pn([zPr,HPr]),YPr=Ae({type:dt("array"),title:re().optional(),description:re().optional(),minItems:kn().optional(),maxItems:kn().optional(),items:Ae({type:dt("string"),enum:Bt(re())}),default:Bt(re()).optional()}),WPr=Ae({type:dt("array"),title:re().optional(),description:re().optional(),minItems:kn().optional(),maxItems:kn().optional(),items:Ae({anyOf:Bt(Ae({const:re(),title:re()}))}),default:Bt(re()).optional()}),XPr=pn([YPr,WPr]),JPr=pn([GPr,KPr,XPr]),ZPr=pn([JPr,VPr,UPr,BPr]),QPr=Uu.extend({mode:dt("form").optional(),message:re(),requestedSchema:Ae({type:dt("object"),properties:vi(re(),ZPr),required:Bt(re()).optional()})}),eDr=Uu.extend({mode:dt("url"),message:re(),elicitationId:re(),url:re().url()}),tDr=pn([QPr,eDr]),rDr=Os.extend({method:dt("elicitation/create"),params:tDr}),nDr=kx.extend({elicitationId:re()}),iDr=nf.extend({method:dt("notifications/elicitation/complete"),params:nDr}),O5=ic.extend({action:$n(["accept","decline","cancel"]),content:l5(e=>e===null?void 0:e,vi(re(),pn([re(),kn(),Ji(),Bt(re())])).optional())}),aDr=Ae({type:dt("ref/resource"),uri:re()});var oDr=Ae({type:dt("ref/prompt"),name:re()}),sDr=Uu.extend({ref:pn([oDr,aDr]),argument:Ae({name:re(),value:re()}),context:Ae({arguments:vi(re(),re()).optional()}).optional()}),cDr=Os.extend({method:dt("completion/complete"),params:sDr});var uDr=ic.extend({completion:np({values:Bt(re()).max(100),total:pt(kn().int()),hasMore:pt(Ji())})}),lDr=Ae({uri:re().startsWith("file://"),name:re().optional(),_meta:vi(re(),li()).optional()}),pDr=Os.extend({method:dt("roots/list")}),Tpe=ic.extend({roots:Bt(lDr)}),fDr=nf.extend({method:dt("notifications/roots/list_changed")}),cSi=pn([g5,ppe,cDr,Epe,vPr,mPr,Qwr,tPr,iPr,cPr,lPr,Lk,bpe,v5,E5,_5]),uSi=pn([m5,y5,fpe,fDr,Rk]),lSi=pn([h5,_pe,xpe,O5,Tpe,b5,x5,sC]),pSi=pn([g5,qPr,rDr,pDr,v5,E5,_5]),fSi=pn([m5,y5,IPr,fPr,oPr,PPr,OPr,Rk,iDr]),dSi=pn([h5,Kwr,uDr,TPr,gPr,ePr,rPr,aPr,T5,CPr,b5,x5,sC]),Cr=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===an.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new spe(i.elicitations,r)}return new e(t,r,n)}},spe=class extends Cr{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(an.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){var t,r;return(r=(t=this.data)===null||t===void 0?void 0:t.elicitations)!==null&&r!==void 0?r:[]}};function s0(e){return e==="completed"||e==="failed"||e==="cancelled"}var dDr=Symbol("Let zodToJsonSchema decide on which parser to use");var KSi=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ope(e){let t=W6(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");let n=FGe(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Spe(e,t){let r=o0(e,t);if(!r.success)throw r.error;return r.data}var bDr=6e4,S5=class{constructor(t){this._options=t,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(m5,r=>{this._oncancel(r)}),this.setNotificationHandler(y5,r=>{this._onprogress(r)}),this.setRequestHandler(g5,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(v5,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Cr(an.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(E5,async(r,n)=>{let i=async()=>{var a;let o=r.params.taskId;if(this._taskMessageQueue){let c;for(;c=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(c.type==="response"||c.type==="error"){let u=c.message,l=u.id,p=this._requestResolvers.get(l);if(p)if(this._requestResolvers.delete(l),c.type==="response")p(u);else{let f=u,d=new Cr(f.error.code,f.error.message,f.error.data);p(d)}else{let f=c.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${l}`))}continue}await((a=this._transport)===null||a===void 0?void 0:a.send(c.message,{relatedRequestId:n.requestId}))}}let s=await this._taskStore.getTask(o,n.sessionId);if(!s)throw new Cr(an.InvalidParams,`Task not found: ${o}`);if(!s0(s.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(s0(s.status)){let c=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...c,_meta:{...c._meta,[Hh]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(_5,async(r,n)=>{var i;try{let{tasks:a,nextCursor:o}=await this._taskStore.listTasks((i=r.params)===null||i===void 0?void 0:i.cursor,n.sessionId);return{tasks:a,nextCursor:o,_meta:{}}}catch(a){throw new Cr(an.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(kKe,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Cr(an.InvalidParams,`Task not found: ${r.params.taskId}`);if(s0(i.status))throw new Cr(an.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new Cr(an.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof Cr?i:new Cr(an.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){let r=this._requestHandlerAbortControllers.get(t.params.requestId);r?.abort(t.params.reason)}_setupTimeout(t,r,n,i,a=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),Cr.fromError(an.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){var r,n,i;this._transport=t;let a=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{a?.(),this._onclose()};let o=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{o?.(c),this._onerror(c)};let s=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{s?.(c,u),wk(c)||IKe(c)?this._onresponse(c):lpe(c)?this._onrequest(c,u):PKe(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var t;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let n=Cr.fromError(an.ConnectionClosed,"Connection closed");this._transport=void 0,(t=this.onclose)===null||t===void 0||t.call(this);for(let i of r.values())i(n)}_onerror(t){var r;(r=this.onerror)===null||r===void 0||r.call(this,t)}_onnotification(t){var r;let n=(r=this._notificationHandlers.get(t.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(t)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(t,r){var n,i,a,o,s,c;let u=(n=this._requestHandlers.get(t.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,l=this._transport,p=(o=(a=(i=t.params)===null||i===void 0?void 0:i._meta)===null||a===void 0?void 0:a[Hh])===null||o===void 0?void 0:o.taskId;if(u===void 0){let v={jsonrpc:"2.0",id:t.id,error:{code:an.MethodNotFound,message:"Method not found"}};p&&this._taskMessageQueue?this._enqueueTaskMessage(p,{type:"error",message:v,timestamp:Date.now()},l?.sessionId).catch(_=>this._onerror(new Error(`Failed to enqueue error response: ${_}`))):l?.send(v).catch(_=>this._onerror(new Error(`Failed to send an error response: ${_}`)));return}let f=new AbortController;this._requestHandlerAbortControllers.set(t.id,f);let d=(s=t.params)===null||s===void 0?void 0:s.task,h=this._taskStore?this.requestTaskStore(t,l?.sessionId):void 0,m={signal:f.signal,sessionId:l?.sessionId,_meta:(c=t.params)===null||c===void 0?void 0:c._meta,sendNotification:async v=>{let _={relatedRequestId:t.id};p&&(_.relatedTask={taskId:p}),await this.notification(v,_)},sendRequest:async(v,_,O)=>{var T,S;let A={...O,relatedRequestId:t.id};p&&!A.relatedTask&&(A.relatedTask={taskId:p});let P=(S=(T=A.relatedTask)===null||T===void 0?void 0:T.taskId)!==null&&S!==void 0?S:p;return P&&h&&await h.updateTaskStatus(P,"input_required"),await this.request(v,_,A)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:p,taskStore:h,taskRequestedTtl:d?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{d&&this.assertTaskHandlerCapability(t.method)}).then(()=>u(t,m)).then(async v=>{if(f.signal.aborted)return;let _={result:v,jsonrpc:"2.0",id:t.id};p&&this._taskMessageQueue?await this._enqueueTaskMessage(p,{type:"response",message:_,timestamp:Date.now()},l?.sessionId):await l?.send(_)},async v=>{var _;if(f.signal.aborted)return;let O={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(v.code)?v.code:an.InternalError,message:(_=v.message)!==null&&_!==void 0?_:"Internal error",...v.data!==void 0&&{data:v.data}}};p&&this._taskMessageQueue?await this._enqueueTaskMessage(p,{type:"error",message:O,timestamp:Date.now()},l?.sessionId):await l?.send(O)}).catch(v=>this._onerror(new Error(`Failed to send response: ${v}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,i=Number(r),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}a(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),wk(t))n(t);else{let o=new Cr(t.error.code,t.error.message,t.error.data);n(o)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let a=!1;if(wk(t)&&t.result&&typeof t.result=="object"){let o=t.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,r))}}if(a||this._progressHandlers.delete(r),wk(t))i(t);else{let o=Cr.fromError(t.error.code,t.error.message,t.error.data);i(o)}}get transport(){return this._transport}async close(){var t;await((t=this._transport)===null||t===void 0?void 0:t.close())}async*requestStream(t,r,n){var i,a,o,s;let{task:c}=n??{};if(!c){try{yield{type:"result",result:await this.request(t,r,n)}}catch(l){yield{type:"error",error:l instanceof Cr?l:new Cr(an.InternalError,String(l))}}return}let u;try{let l=await this.request(t,sC,n);if(l.task)u=l.task.taskId,yield{type:"taskCreated",task:l.task};else throw new Cr(an.InternalError,"Task creation did not return a task");for(;;){let p=await this.getTask({taskId:u},n);if(yield{type:"taskStatus",task:p},s0(p.status)){p.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:u},r,n)}:p.status==="failed"?yield{type:"error",error:new Cr(an.InternalError,`Task ${u} failed`)}:p.status==="cancelled"&&(yield{type:"error",error:new Cr(an.InternalError,`Task ${u} was cancelled`)});return}if(p.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:u},r,n)};return}let f=(o=(i=p.pollInterval)!==null&&i!==void 0?i:(a=this._options)===null||a===void 0?void 0:a.defaultTaskPollInterval)!==null&&o!==void 0?o:1e3;await new Promise(d=>setTimeout(d,f)),(s=n?.signal)===null||s===void 0||s.throwIfAborted()}}catch(l){yield{type:"error",error:l instanceof Cr?l:new Cr(an.InternalError,String(l))}}}request(t,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{var p,f,d,h,m,v,_;let O=F=>{l(F)};if(!this._transport){O(new Error("Not connected"));return}if(((p=this._options)===null||p===void 0?void 0:p.enforceStrictCapabilities)===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(F){O(F);return}(f=n?.signal)===null||f===void 0||f.throwIfAborted();let T=this._requestMessageId++,S={...t,jsonrpc:"2.0",id:T};n?.onprogress&&(this._progressHandlers.set(T,n.onprogress),S.params={...t.params,_meta:{...((d=t.params)===null||d===void 0?void 0:d._meta)||{},progressToken:T}}),s&&(S.params={...S.params,task:s}),c&&(S.params={...S.params,_meta:{...((h=S.params)===null||h===void 0?void 0:h._meta)||{},[Hh]:c}});let A=F=>{var K;this._responseHandlers.delete(T),this._progressHandlers.delete(T),this._cleanupTimeout(T),(K=this._transport)===null||K===void 0||K.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:T,reason:String(F)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let $=F instanceof Cr?F:new Cr(an.RequestTimeout,String(F));l($)};this._responseHandlers.set(T,F=>{var K;if(!(!((K=n?.signal)===null||K===void 0)&&K.aborted)){if(F instanceof Error)return l(F);try{let $=o0(r,F.result);$.success?u($.data):l($.error)}catch($){l($)}}}),(m=n?.signal)===null||m===void 0||m.addEventListener("abort",()=>{var F;A((F=n?.signal)===null||F===void 0?void 0:F.reason)});let P=(v=n?.timeout)!==null&&v!==void 0?v:bDr,k=()=>A(Cr.fromError(an.RequestTimeout,"Request timed out",{timeout:P}));this._setupTimeout(T,P,n?.maxTotalTimeout,k,(_=n?.resetTimeoutOnProgress)!==null&&_!==void 0?_:!1);let D=c?.taskId;if(D){let F=K=>{let $=this._responseHandlers.get(T);$?$(K):this._onerror(new Error(`Response handler missing for side-channeled request ${T}`))};this._requestResolvers.set(T,F),this._enqueueTaskMessage(D,{type:"request",message:S,timestamp:Date.now()}).catch(K=>{this._cleanupTimeout(T),l(K)})}else this._transport.send(S,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(F=>{this._cleanupTimeout(T),l(F)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},b5,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},x5,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},$Ke,r)}async notification(t,r){var n,i,a,o,s;if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let c=(n=r?.relatedTask)===null||n===void 0?void 0:n.taskId;if(c){let f={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...((i=t.params)===null||i===void 0?void 0:i._meta)||{},[Hh]:r.relatedTask}}};await this._enqueueTaskMessage(c,{type:"notification",message:f,timestamp:Date.now()});return}if(((o=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&o!==void 0?o:[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{var f,d;if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let h={...t,jsonrpc:"2.0"};r?.relatedTask&&(h={...h,params:{...h.params,_meta:{...((f=h.params)===null||f===void 0?void 0:f._meta)||{},[Hh]:r.relatedTask}}}),(d=this._transport)===null||d===void 0||d.send(h,r).catch(m=>this._onerror(m))});return}let p={...t,jsonrpc:"2.0"};r?.relatedTask&&(p={...p,params:{...p.params,_meta:{...((s=p.params)===null||s===void 0?void 0:s._meta)||{},[Hh]:r.relatedTask}}}),await this._transport.send(p,r)}setRequestHandler(t,r){let n=Ope(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=Spe(t,i);return Promise.resolve(r(o,a))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=Ope(t);this._notificationHandlers.set(n,i=>{let a=Spe(t,i);return Promise.resolve(r(a))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){var i;if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=(i=this._options)===null||i===void 0?void 0:i.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,a)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let i of n)if(i.type==="request"&&lpe(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new Cr(an.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){var n,i,a;let o=(i=(n=this._options)===null||n===void 0?void 0:n.defaultTaskPollInterval)!==null&&i!==void 0?i:1e3;try{let s=await((a=this._taskStore)===null||a===void 0?void 0:a.getTask(t));s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,c)=>{if(r.aborted){c(new Cr(an.InvalidRequest,"Request cancelled"));return}let u=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(u),c(new Cr(an.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await n.createTask(i,t.id,{method:t.method,params:t.params},r)},getTask:async i=>{let a=await n.getTask(i,r);if(!a)throw new Cr(an.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await n.storeTaskResult(i,a,o,r);let s=await n.getTask(i,r);if(s){let c=Rk.parse({method:"notifications/tasks/status",params:s});await this.notification(c),s0(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,a,o)=>{let s=await n.getTask(i,r);if(!s)throw new Cr(an.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(s0(s.status))throw new Cr(an.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,o,r);let c=await n.getTask(i,r);if(c){let u=Rk.parse({method:"notifications/tasks/status",params:c});await this.notification(u),s0(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function UKe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function BKe(e,t){let r={...e};for(let n in t){let i=n,a=t[i];if(a===void 0)continue;let o=r[i];UKe(o)&&UKe(a)?r[i]={...o,...a}:r[i]=a}return r}var kWe=Ct(oz(),1),$We=Ct(LWe(),1);function s2r(){let e=new kWe.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$We.default)(e),e}var cz=class{constructor(t){this._ajv=t??s2r()}getValidator(t){var r;let n="$id"in t&&typeof t.$id=="string"?(r=this._ajv.getSchema(t.$id))!==null&&r!==void 0?r:this._ajv.compile(t):this._ajv.compile(t);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var uz=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function MWe(e,t,r){var n;if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!(!((n=e.tools)===null||n===void 0)&&n.call))throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function FWe(e,t,r){var n,i;if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!(!((n=e.sampling)===null||n===void 0)&&n.createMessage))throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!(!((i=e.elicitation)===null||i===void 0)&&i.create))throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var lz=class extends S5{constructor(t,r){var n,i;super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(kk.options.map((a,o)=>[a,o])),this.isMessageIgnored=(a,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(a)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._instructions=r?.instructions,this._jsonSchemaValidator=(i=r?.jsonSchemaValidator)!==null&&i!==void 0?i:new cz,this.setRequestHandler(ppe,a=>this._oninitialize(a)),this.setNotificationHandler(fpe,()=>{var a;return(a=this.oninitialized)===null||a===void 0?void 0:a.call(this)}),this._capabilities.logging&&this.setRequestHandler(Epe,async(a,o)=>{var s;let c=o.sessionId||((s=o.requestInfo)===null||s===void 0?void 0:s.headers["mcp-session-id"])||void 0,{level:u}=a.params,l=kk.safeParse(u);return l.success&&this._loggingLevels.set(c,l.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new uz(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=BKe(this._capabilities,t)}setRequestHandler(t,r){var n,i,a;let o=W6(t),s=o?.method;if(!s)throw new Error("Schema is missing a method literal");let c;if(iC(s)){let l=s,p=(n=l._zod)===null||n===void 0?void 0:n.def;c=(i=p?.value)!==null&&i!==void 0?i:l.value}else{let l=s,p=l._def;c=(a=p?.value)!==null&&a!==void 0?a:l.value}if(typeof c!="string")throw new Error("Schema method literal must be a string");if(c==="tools/call"){let l=async(p,f)=>{let d=o0(Lk,p);if(!d.success){let _=d.error instanceof Error?d.error.message:String(d.error);throw new Cr(an.InvalidParams,`Invalid tools/call request: ${_}`)}let{params:h}=d.data,m=await Promise.resolve(r(p,f));if(h.task){let _=o0(sC,m);if(!_.success){let O=_.error instanceof Error?_.error.message:String(_.error);throw new Cr(an.InvalidParams,`Invalid task creation result: ${O}`)}return _.data}let v=o0(T5,m);if(!v.success){let _=v.error instanceof Error?v.error.message:String(v.error);throw new Cr(an.InvalidParams,`Invalid tools/call result: ${_}`)}return v.data};return super.setRequestHandler(t,l)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){var r,n,i;switch(t){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!(!((n=this._clientCapabilities)===null||n===void 0)&&n.elicitation))throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!(!((i=this._clientCapabilities)===null||i===void 0)&&i.roots))throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){var r,n;switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);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 ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!(!((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.elicitation)===null||n===void 0)&&n.url))throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);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 ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);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 ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){var r,n;FWe((n=(r=this._clientCapabilities)===null||r===void 0?void 0:r.tasks)===null||n===void 0?void 0:n.requests,t,"Client")}assertTaskHandlerCapability(t){var r;this._capabilities&&MWe((r=this._capabilities.tasks)===null||r===void 0?void 0:r.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:OKe.includes(r)?r:cpe,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"},h5)}async createMessage(t,r){var n,i;if((t.tools||t.toolChoice)&&!(!((i=(n=this._clientCapabilities)===null||n===void 0?void 0:n.sampling)===null||i===void 0)&&i.tools))throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let a=t.messages[t.messages.length-1],o=Array.isArray(a.content)?a.content:[a.content],s=o.some(p=>p.type==="tool_result"),c=t.messages.length>1?t.messages[t.messages.length-2]:void 0,u=c?Array.isArray(c.content)?c.content:[c.content]:[],l=u.some(p=>p.type==="tool_use");if(s){if(o.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let p=new Set(u.filter(d=>d.type==="tool_use").map(d=>d.id)),f=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(p.size!==f.size||![...p].every(d=>f.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},xpe,r):this.request({method:"sampling/createMessage",params:t},_pe,r)}async elicitInput(t,r){var n,i,a,o,s;switch((n=t.mode)!==null&&n!==void 0?n:"form"){case"url":{if(!(!((a=(i=this._clientCapabilities)===null||i===void 0?void 0:i.elicitation)===null||a===void 0)&&a.url))throw new Error("Client does not support url elicitation.");let u=t;return this.request({method:"elicitation/create",params:u},O5,r)}case"form":{if(!(!((s=(o=this._clientCapabilities)===null||o===void 0?void 0:o.elicitation)===null||s===void 0)&&s.form))throw new Error("Client does not support form elicitation.");let u=t.mode==="form"?t:{...t,mode:"form"},l=await this.request({method:"elicitation/create",params:u},O5,r);if(l.action==="accept"&&l.content&&u.requestedSchema)try{let f=this._jsonSchemaValidator.getValidator(u.requestedSchema)(l.content);if(!f.valid)throw new Cr(an.InvalidParams,`Elicitation response content does not match requested schema: ${f.errorMessage}`)}catch(p){throw p instanceof Cr?p:new Cr(an.InternalError,`Error validating elicitation response: ${p instanceof Error?p.message:String(p)}`)}return l}}}createElicitationCompletionNotifier(t,r){var n,i;if(!(!((i=(n=this._clientCapabilities)===null||n===void 0?void 0:n.elicitation)===null||i===void 0)&&i.url))throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},Tpe,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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"})}};var gde=Ct(require("node:process"),1);var pz=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
1652
1652
|
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),u2r(r)}clear(){this._buffer=void 0}};function u2r(e){return RKe.parse(JSON.parse(e))}function jWe(e){return JSON.stringify(e)+`
|
|
1653
|
-
`}var fz=class{constructor(t=gde.default.stdin,r=gde.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new pz,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,n)}}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(var t,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(t=this.onmessage)===null||t===void 0||t.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){var t;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(t=this.onclose)===null||t===void 0||t.call(this)}send(t){return new Promise(r=>{let n=jWe(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var VWe="0.5.2";var f2={name:"@sap-ux/fiori-mcp-server",description:"SAP Fiori - Model Context Protocol (MCP) server",version:VWe,keywords:["SAP Fiori tools","SAP Fiori elements","SAP Fiori freestyle","MCP","AI"],repository:{type:"git",url:"https://github.com/SAP/open-ux-tools.git",directory:"packages/fiori-mcp-server"},bugs:{url:"https://github.com/SAP/open-ux-tools/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%3Afiori-mcp-server"},license:"Apache-2.0",main:"dist/index.js",scripts:{"build-esbuild-base":"esbuild --bundle --platform=node --target=node20 --outdir=dist --external:vscode --external:@lancedb/lancedb --external:@xenova/transformers --external:@sap-ux/fiori-docs-embeddings --external:@sap-ux/store --main-fields=module,main src/index.ts","build-dev":"pnpm run build-esbuild-base --sourcemap=inline","build-compile":"tsc --noEmit","build-bundle":"pnpm run build-esbuild-base --minify",build:"npm-run-all build-compile build-bundle",watch:"tsc --watch",bundle:"npm-run-all build tgz:package tgz:rename","tgz:package":"pnpm pack","tgz:rename":"node -e \"const fs=require('fs'), p=require('./package.json'), d=new Date().toISOString().split('T')[0], oldName=p.name.startsWith('@') ? `${p.name.replace('@', '').replace('/', '-')}-${p.version}.tgz` : `${p.name}-${p.version}.tgz`; fs.renameSync(oldName, `${oldName.replace('.tgz','')}-${d}.tgz`)\"",clean:"rimraf --glob dist test/test-output *.tsbuildinfo",format:"prettier --write '**/*.{js,json,ts,yaml,yml}' --ignore-path ../../.prettierignore",lint:"eslint","lint:fix":"eslint --fix",test:"jest --ci --forceExit --detectOpenHandles --colors",inspector:"npx @modelcontextprotocol/inspector node dist/index.js",start:'npx -y supergateway --port 9881 --sessionTimeout 300000 --stdio "node ./dist/index.js"',"view:integration":"promptfoo view -y","test:integration:once":"promptfoo eval --config test/integration/scenarios/promptfooconfig.yaml --max-concurrency 1 --repeat 1 --output reports/integration.txt","test:integration:dev":"promptfoo eval --config test/integration/scenarios/test-dev.yaml --max-concurrency 1 --repeat 1 --output reports/integration.txt","test:integration:multiple":"npm run test:promptfoo -- --repeat 5"},files:["LICENSE","dist","!dist/**/*.map"],bin:{"fiori-mcp":"./dist/index.js"},devDependencies:{"npm-run-all2":"8.0.4",esbuild:"0.25.6","@modelcontextprotocol/sdk":"1.24.1","@sap-ux/axios-extension":"workspace:*","@sap/ux-specification":"1.139.2","@sap-ux/project-access":"workspace:*","@sap-ux/fiori-annotation-api":"workspace:*","@sap-ux/annotation-converter":"0.10.8","@sap-ux/edmx-parser":"0.9.6","@sap-ux/fiori-docs-embeddings":"workspace:*","@sap-ux/i18n":"workspace:*","@sap-ux/logger":"workspace:*","@sap-ux/odata-annotation-core-types":"workspace:*","@sap-ux/odata-entity-model":"workspace:*","@sap-ux/text-document-utils":"workspace:*","@types/diff":"5.0.9","@types/json-schema":"7.0.5","@types/mem-fs":"1.1.2","@types/mem-fs-editor":"7.0.1","@sap-ux/btp-utils":"workspace:*","@sap-ux/feature-toggle":"workspace:*","@sap-ux/nodejs-utils":"workspace:*","@sap-ux/telemetry":"workspace:*",i18next:"25.3.0","os-name":"4.0.1",zod:"4.1.13","@sap-ai-sdk/foundation-models":"2.3.0","@sap-ai-sdk/langchain":"2.3.0",promptfoo:"0.119.14","@langchain/mcp-adapters":"1.0.2","@langchain/core":"1.1.1"},dependencies:{"@sap-ux/fiori-docs-embeddings":"workspace:*","@sap-ux/store":"workspace:*","@xenova/transformers":"2.17.2","@lancedb/lancedb":"0.22.0","mem-fs":"2.1.0","mem-fs-editor":"9.4.0"},engines:{node:">=20.x"}};var zWe=Ae({name:re().describe("Name of the Fiori application. Usually derived from the `sap.app/id` field in the application's manifest.json."),appPath:re().describe("Absolute path to the Fiori application's root directory."),projectPath:re().describe("Absolute path to the root directory of the project containing this Fiori application. For EDMXBackend (standalone) projects, this is the same as `appPath`. For CAP projects, this points to the CAP project root, which may contain multiple Fiori applications."),projectType:$n(["EDMXBackend","CAPJava","CAPNodejs"]).describe("Type of project the application belongs to."),odataVersion:re().describe("OData protocol version used by the application's main service.")}),Kx=pn([re(),Bt(pn([re(),kn()]))]),HWe=Ae({functionalityId:Kx.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),description:re()}),UWe=$n(["object","array","string","number","boolean","null","integer","any"]),BWe=Ae({type:pn([UWe,Bt(UWe)]).optional(),description:re().optional(),properties:a5().optional()}).catchall(a5()),GWe=BWe.extend({properties:vi(re(),pn([BWe,Ji()])).optional()});var KWe=Ae({searchPath:Bt(re()).describe("Path to search for Fiori applications (defaults to current directory). If VSCode - list of VS Code workspace folder paths(`workspace.workspaceFolders`)")}),YWe=Ae({appPath:re().describe("Path to the root folder of the Fiori application (where package.json and ui5.yaml reside) if one exists or to the current directory. Path should be an absolute path.")}),WWe=Ae({appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path."),functionalityId:Kx.describe("The ID of the functionality to get details for")}),XWe=Ae({functionalityId:Kx.describe("The ID of the functionality to execute"),parameters:vi(re(),li()).describe("Parameters for the functionality execution"),appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path.")}).describe('Input object for executing a functionality. Only three top-level properties are allowed: "functionalityId", "parameters", and "appPath". All other dynamic or functionality-specific inputs must be included inside the "parameters" object. Do not place any additional fields at the root level.'),NDi=Ae({query:re().min(2).describe("The search query for fiori elements, annotations, sapui5, fiori tools documentation")});var RDi=re().describe("Search results as formatted text"),JWe=Ae({applications:Bt(zWe)}),ZWe=Ae({applicationPath:re(),functionalities:Bt(HWe)}),QWe=Ae({functionalityId:Kx.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),name:re(),description:re(),technicalDescription:re().optional(),parameters:GWe,prerequisites:Bt(re()).optional(),impact:re().optional(),examples:Bt(re()).optional(),pageName:re().optional()}),eXe=Ae({functionalityId:Kx,status:re(),message:re(),parameters:li(),appPath:re(),changes:Bt(re()),timestamp:re()});var Qme=Ct(require("node:fs/promises")),hf=Ct(require("node:path"));var df=Ct(N0());function o9r(){let e=globalThis.LOG_LEVEL,t=process.env.LOG_LEVEL,r=process.argv.find(i=>i.startsWith("--log-level="))?.split("=")[1],n=e||t||r;if(n)switch(n.toUpperCase()){case"ERROR":return df.LogLevel.Error;case"WARN":return df.LogLevel.Warn;case"INFO":return df.LogLevel.Info;case"DEBUG":return df.LogLevel.Debug;case"VERBOSE":return df.LogLevel.Verbose;case"SILLY":return df.LogLevel.Silly;default:break}return df.LogLevel.Error}var s9r=o9r(),$t=new df.ToolsLogger({logLevel:s9r,transports:[new df.ConsoleTransport],logPrefix:"fiori-mcp"});async function wat(){try{let r;try{r=require("@sap-ux/fiori-docs-embeddings")}catch{try{r=await import("@sap-ux/fiori-docs-embeddings")}catch{r=null}}if(!r||typeof r.getDataPath!="function")throw new Error("Package not found or invalid");let n=r.getDataPath();return await Qme.default.access(n),$t.log("\u2713 Using @sap-ux/fiori-docs-embeddings package"),{dataPath:n,embeddingsPath:hf.default.join(n,"embeddings"),searchPath:hf.default.join(n,"search"),docsPath:hf.default.join(n,"docs"),isExternalPackage:!0,isAvailable:!0}}catch{$t.warn("Could not load @sap-ux/fiori-docs-embeddings package, trying local data...")}let e=hf.default.join(__dirname,"../../data");try{return await Qme.default.access(e),$t.log("\u2713 Using local data directory"),{dataPath:e,embeddingsPath:hf.default.join(e,"embeddings"),searchPath:hf.default.join(e,"search"),docsPath:hf.default.join(e,"docs"),isExternalPackage:!1,isAvailable:!0}}catch{$t.warn("Local data directory not available either")}let t=hf.default.join(__dirname,"../../data");return $t.warn("\u26A0\uFE0F No embeddings data available - running in limited mode"),{dataPath:t,embeddingsPath:hf.default.join(t,"embeddings"),searchPath:hf.default.join(t,"search"),docsPath:hf.default.join(t,"docs"),isExternalPackage:!1,isAvailable:!1}}var vc=Ct(bm()),nF=require("node:path");async function uu(e){try{e=(0,nF.join)(e);try{let t=await(0,vc.createApplicationAccess)(e);return{root:t.project.root,appId:t.getAppId(),applicationAccess:t}}catch(t){$t.warn(`Application was not found by given path. Error: ${t}`);let r=await(0,vc.findProjectRoot)(e),n=await(0,vc.getProject)(r);if(n)return{root:n.root,appId:""}}}catch(t){$t.warn(`Project was not found by given path. Error: ${t}`);return}}var b7=e=>{let t;switch(e){case vc.DirName.View:{t=(0,nF.join)(vc.DirName.Ext,vc.DirName.View);break}case vc.DirName.Fragment:{t=(0,nF.join)(vc.DirName.Ext,vc.DirName.Fragment);break}case vc.DirName.Controller:{t=(0,nF.join)(vc.DirName.Ext,vc.DirName.Controller);break}default:t=e}return t},Em=(e,t,r=new Set)=>{if(!e||typeof e!="object")return{};if(e.$ref?.startsWith("#/definitions/")){let i=e.$ref,a=i.replace("#/definitions/",""),o=t.definitions?.[a]??null;if(r.has(i))return{...o};if(r.add(i),o){let s={...e};return delete s.$ref,Em({...o,...s},t,r)}}let n={...e};return n.properties&&(n.properties=Object.fromEntries(Object.entries(n.properties).map(([i,a])=>[i,Em(a,t,r)]))),n.items&&(Array.isArray(n.items)?n.items=n.items.map(i=>Em(i,t,r)):n.items=Em(n.items,t,r)),n.allOf&&(n.allOf=n.allOf.map(i=>Em(i,t,r))),n.anyOf&&(n.anyOf=n.anyOf.map(i=>Em(i,t,r))),n.oneOf&&(n.oneOf=n.oneOf.map(i=>Em(i,t,r))),typeof n.additionalProperties=="object"&&(n.additionalProperties=Em(n.additionalProperties,t,r)),n},xxt=(e,t)=>({type:"object",properties:{[e]:t}}),xa=e=>{let t=Rx(e);return delete t.$schema,t},_m=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof yle?new Error(`Missing required fields in parameters. ${JSON.stringify(r.issues,null,4)}`):new Error("Unknown error. Recheck input parameters.")}};var YIt=require("node:util"),WIt=require("node:child_process"),XIt=Ct(WAe());async function AW(e="1.18.5"){let t="@sap/generator-fiori";if((await(0,XIt.findInstalledPackages)(t,{minVersion:e}))?.length<1)throw new Error(`Fiori generator not found. Please install the Fiori generator >=${e} with 'npm install -g ${t}' and retry this call`)}var CW=(0,YIt.promisify)(WIt.exec);var JIt=require("@lancedb/lancedb");var XAe=Ct(require("fs/promises")),JAe=Ct(require("node:path")),wW=class{connection=null;tables=[];tableIndex=null;metadata=null;dataPath;constructor(t){this.dataPath=t||""}async initialize(){try{$t.log("Loading vector database from pre-built embeddings...");let t=await wat();if(!t.isAvailable)throw new Error("No embeddings data available");this.dataPath=t.embeddingsPath,$t.log(`Using embeddings path: ${this.dataPath} (external: ${t.isExternalPackage})`);let r=JAe.default.join(this.dataPath,"metadata.json"),n=await XAe.default.readFile(r,"utf-8");this.metadata=JSON.parse(n),$t.log("\u2713 Embedding metadata loaded:"),$t.log(` Model: ${this?.metadata?.model}`),$t.log(` Dimensions: ${this?.metadata?.dimensions}`),$t.log(` Total vectors: ${this?.metadata?.totalVectors}`),$t.log(` Created: ${this?.metadata?.createdAt}`),this.connection=await(0,JIt.connect)(this.dataPath);let i=JAe.default.join(this.dataPath,"table_index.json");try{let a=await XAe.default.readFile(i,"utf-8");this.tableIndex=JSON.parse(a),this.tables=[];for(let o of this.tableIndex?.tables||[]){let s=await this.connection.openTable(o);this.tables.push(s)}$t.log(`\u2713 Loaded ${this.tables.length} split tables`)}catch{$t.log("No table index found, trying single table...");try{let a=await this.connection.openTable("documents");this.tables=[a],this.tableIndex={tables:["documents"],totalTables:1,maxVectorsPerTable:-1,totalVectors:this.metadata?.totalVectors||0}}catch(a){throw new Error(`No tables found: ${a}`)}}$t.log("\u2713 Vector database loaded and ready")}catch(t){throw new Error(`Failed to load vector database: ${t}`)}}async semanticSearch(t,r=10,n){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let i=[];for(let o of this.tables){let s=o.vectorSearch(t).limit(r*2);n&&(s=s.where(`category = "${n}"`));let c=await s.toArray();i.push(...c)}return i.sort((o,s)=>(o._distance||0)-(s._distance||0)),i.slice(0,r).map(o=>({document:{id:o.document_id,vector:o.vector,content:o.content,title:o.title,category:o.category,path:o.path,chunk_index:o.chunk_index,metadata:{tags:this.parseJsonField(o.tags_json)||[],headers:this.parseJsonField(o.headers_json)||[],lastModified:new Date(o.lastModified),wordCount:o.wordCount,excerpt:o.excerpt}},score:1-(o._distance||0),distance:o._distance||0}))}catch(i){throw $t.error(`Semantic search failed: ${i}`),new Error(`Semantic search failed: ${i}`)}}async findSimilarToText(t,r=5){return $t.warn("findSimilarToText requires embedding generation - not available in simplified mode"),[]}async findSimilarToDocument(t,r=5){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let n=null;for(let s of this.tables){let c=await s.search("").where(`document_id = "${t}" AND chunk_index = 0`).limit(1).toArray();if(c.length>0){n=c[0].vector;break}}if(!n)return[];let i=[];for(let s of this.tables){let c=await s.vectorSearch(n).where(`document_id != "${t}"`).limit(r*2).toArray();i.push(...c)}let a=new Map;for(let s of i){let c=s.document_id,u=1-(s._distance||0);(!a.has(c)||a.get(c).score<u)&&a.set(c,{...s,score:u,distance:s._distance||0})}return Array.from(a.values()).sort((s,c)=>c.score-s.score).slice(0,r).map(s=>({document:{id:s.document_id,vector:s.vector,content:s.content,title:s.title,category:s.category,path:s.path,chunk_index:s.chunk_index,metadata:{tags:this.parseJsonField(s.tags_json)||[],headers:this.parseJsonField(s.headers_json)||[],lastModified:new Date(s.lastModified),wordCount:s.wordCount,excerpt:s.excerpt}},score:s.score,distance:s.distance}))}catch(n){return $t.error(`Find similar documents failed: ${n}`),[]}}async getDocumentsByCategory(t,r){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let n=[];for(let a of this.tables){let o=a.search("").where(`category = "${t}" AND chunk_index = 0`);r&&(o=o.limit(Math.ceil(r/this.tables.length)+10));let s=await o.toArray();n.push(...s)}return(r?n.slice(0,r):n).map(a=>({document:{id:a.document_id,vector:a.vector,content:a.content,title:a.title,category:a.category,path:a.path,chunk_index:a.chunk_index,metadata:{tags:this.parseJsonField(a.tags_json)||[],headers:this.parseJsonField(a.headers_json)||[],lastModified:new Date(a.lastModified),wordCount:a.wordCount,excerpt:a.excerpt}},score:1,distance:0}))}catch(n){return $t.error(`Get documents by category failed: ${n}`),[]}}getMetadata(){return this.metadata}parseJsonField(t){try{return t?JSON.parse(t):[]}catch{return[]}}isInitialized(){return this.tables.length>0&&this.metadata!==null}async close(){this.connection&&(this.connection=null,this.tables=[],$t.log("Vector database connection closed"))}};var PW=class{pipeline=null;initialized=!1;async initialize(){if(!this.initialized)try{let{pipeline:t}=await import("@xenova/transformers");this.pipeline=await t("feature-extraction","Xenova/all-MiniLM-L6-v2",{quantized:!1}),this.initialized=!0}catch(t){throw new Error(`Failed to initialize text embedding service: ${t}. Make sure @xenova/transformers is available.`)}}async generateEmbedding(t){if(!this.initialized||!this.pipeline)throw new Error("Text embedding service not initialized. Call initialize() first.");try{let r=t.replace(/\n+/g," ").replace(/\s+/g," ").trim().substring(0,8192);if(!r)throw new Error("Empty text provided for embedding");let n=await this.pipeline(r,{pooling:"mean",normalize:!0});return Array.from(n.data)}catch(r){throw new Error(`Failed to generate embedding: ${r}`)}}isInitialized(){return this.initialized}};async function ZAe(e,t=!1){let{query:r,maxResults:n}=e;try{let i=new wW,a=new PW;await i.initialize(),await a.initialize();let o=await a.generateEmbedding(r),s=await i.semanticSearch(o,n??10);if(t){let c="";for(let[u,l]of s.entries())c+=`Result ${u+1}:
|
|
1653
|
+
`}var fz=class{constructor(t=gde.default.stdin,r=gde.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new pz,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{var i;(i=this.onerror)===null||i===void 0||i.call(this,n)}}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(var t,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(t=this.onmessage)===null||t===void 0||t.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){var t;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(t=this.onclose)===null||t===void 0||t.call(this)}send(t){return new Promise(r=>{let n=jWe(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var VWe="0.6.0";var f2={name:"@sap-ux/fiori-mcp-server",description:"SAP Fiori - Model Context Protocol (MCP) server",version:VWe,keywords:["SAP Fiori tools","SAP Fiori elements","SAP Fiori freestyle","MCP","AI"],repository:{type:"git",url:"https://github.com/SAP/open-ux-tools.git",directory:"packages/fiori-mcp-server"},bugs:{url:"https://github.com/SAP/open-ux-tools/issues?q=is%3Aopen+is%3Aissue+label%3Abug+label%3Afiori-mcp-server"},license:"Apache-2.0",main:"dist/index.js",scripts:{"build-esbuild-base":"esbuild --bundle --platform=node --target=node20 --outdir=dist --external:vscode --external:@lancedb/lancedb --external:@xenova/transformers --external:@sap-ux/fiori-docs-embeddings --external:@sap-ux/store --main-fields=module,main src/index.ts","build-dev":"pnpm run build-esbuild-base --sourcemap=inline","build-compile":"tsc --noEmit","build-bundle":"pnpm run build-esbuild-base --minify",build:"npm-run-all build-compile build-bundle",watch:"tsc --watch",bundle:"npm-run-all build tgz:package tgz:rename","tgz:package":"pnpm pack","tgz:rename":"node -e \"const fs=require('fs'), p=require('./package.json'), d=new Date().toISOString().split('T')[0], oldName=p.name.startsWith('@') ? `${p.name.replace('@', '').replace('/', '-')}-${p.version}.tgz` : `${p.name}-${p.version}.tgz`; fs.renameSync(oldName, `${oldName.replace('.tgz','')}-${d}.tgz`)\"",clean:"rimraf --glob dist test/test-output *.tsbuildinfo",format:"prettier --write '**/*.{js,json,ts,yaml,yml}' --ignore-path ../../.prettierignore",lint:"eslint","lint:fix":"eslint --fix",test:"jest --ci --forceExit --detectOpenHandles --colors",inspector:"npx @modelcontextprotocol/inspector node dist/index.js",start:'npx -y supergateway --port 9881 --sessionTimeout 300000 --stdio "node ./dist/index.js"',"view:integration":"promptfoo view -y","test:integration:once":"promptfoo eval --config test/integration/scenarios/promptfooconfig.yaml --max-concurrency 1 --repeat 1 --output reports/integration.txt","test:integration:dev":"promptfoo eval --config test/integration/scenarios/test-dev.yaml --max-concurrency 1 --repeat 1 --output reports/integration.txt","test:integration:multiple":"npm run test:promptfoo -- --repeat 5"},files:["LICENSE","dist","!dist/**/*.map"],bin:{"fiori-mcp":"./dist/index.js"},devDependencies:{"npm-run-all2":"8.0.4",esbuild:"0.25.6","@modelcontextprotocol/sdk":"1.24.1","@sap-ux/axios-extension":"workspace:*","@sap/ux-specification":"1.139.2","@sap-ux/project-access":"workspace:*","@sap-ux/fiori-annotation-api":"workspace:*","@sap-ux/annotation-converter":"0.10.9","@sap-ux/edmx-parser":"0.9.6","@sap-ux/fiori-docs-embeddings":"workspace:*","@sap-ux/i18n":"workspace:*","@sap-ux/logger":"workspace:*","@sap-ux/odata-annotation-core-types":"workspace:*","@sap-ux/odata-entity-model":"workspace:*","@sap-ux/text-document-utils":"workspace:*","@types/diff":"5.0.9","@types/json-schema":"7.0.5","@types/mem-fs":"1.1.2","@types/mem-fs-editor":"7.0.1","@sap-ux/btp-utils":"workspace:*","@sap-ux/feature-toggle":"workspace:*","@sap-ux/nodejs-utils":"workspace:*","@sap-ux/telemetry":"workspace:*",i18next:"25.3.0","os-name":"4.0.1",zod:"4.1.13","@sap-ai-sdk/foundation-models":"2.3.0","@sap-ai-sdk/langchain":"2.3.0",promptfoo:"0.119.14","@langchain/mcp-adapters":"1.0.2","@langchain/core":"1.1.1"},dependencies:{"@sap-ux/fiori-docs-embeddings":"workspace:*","@sap-ux/store":"workspace:*","@xenova/transformers":"2.17.2","@lancedb/lancedb":"0.22.0","mem-fs":"2.1.0","mem-fs-editor":"9.4.0"},engines:{node:">=20.x"}};var zWe=Ae({name:re().describe("Name of the Fiori application. Usually derived from the `sap.app/id` field in the application's manifest.json."),appPath:re().describe("Absolute path to the Fiori application's root directory."),projectPath:re().describe("Absolute path to the root directory of the project containing this Fiori application. For EDMXBackend (standalone) projects, this is the same as `appPath`. For CAP projects, this points to the CAP project root, which may contain multiple Fiori applications."),projectType:$n(["EDMXBackend","CAPJava","CAPNodejs"]).describe("Type of project the application belongs to."),odataVersion:re().describe("OData protocol version used by the application's main service.")}),Kx=pn([re(),Bt(pn([re(),kn()]))]),HWe=Ae({functionalityId:Kx.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),description:re()}),UWe=$n(["object","array","string","number","boolean","null","integer","any"]),BWe=Ae({type:pn([UWe,Bt(UWe)]).optional(),description:re().optional(),properties:a5().optional()}).catchall(a5()),GWe=BWe.extend({properties:vi(re(),pn([BWe,Ji()])).optional()});var KWe=Ae({searchPath:Bt(re()).describe("Path to search for Fiori applications (defaults to current directory). If VSCode - list of VS Code workspace folder paths(`workspace.workspaceFolders`)")}),YWe=Ae({appPath:re().describe("Path to the root folder of the Fiori application (where package.json and ui5.yaml reside) if one exists or to the current directory. Path should be an absolute path.")}),WWe=Ae({appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path."),functionalityId:Kx.describe("The ID of the functionality to get details for")}),XWe=Ae({functionalityId:Kx.describe("The ID of the functionality to execute"),parameters:vi(re(),li()).describe("Parameters for the functionality execution"),appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path.")}).describe('Input object for executing a functionality. Only three top-level properties are allowed: "functionalityId", "parameters", and "appPath". All other dynamic or functionality-specific inputs must be included inside the "parameters" object. Do not place any additional fields at the root level.'),NDi=Ae({query:re().min(2).describe("The search query for fiori elements, annotations, sapui5, fiori tools documentation")});var RDi=re().describe("Search results as formatted text"),JWe=Ae({applications:Bt(zWe)}),ZWe=Ae({applicationPath:re(),functionalities:Bt(HWe)}),QWe=Ae({functionalityId:Kx.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),name:re(),description:re(),technicalDescription:re().optional(),parameters:GWe,prerequisites:Bt(re()).optional(),impact:re().optional(),examples:Bt(re()).optional(),pageName:re().optional()}),eXe=Ae({functionalityId:Kx,status:re(),message:re(),parameters:li(),appPath:re(),changes:Bt(re()),timestamp:re()});var Qme=Ct(require("node:fs/promises")),hf=Ct(require("node:path"));var df=Ct(N0());function o9r(){let e=globalThis.LOG_LEVEL,t=process.env.LOG_LEVEL,r=process.argv.find(i=>i.startsWith("--log-level="))?.split("=")[1],n=e||t||r;if(n)switch(n.toUpperCase()){case"ERROR":return df.LogLevel.Error;case"WARN":return df.LogLevel.Warn;case"INFO":return df.LogLevel.Info;case"DEBUG":return df.LogLevel.Debug;case"VERBOSE":return df.LogLevel.Verbose;case"SILLY":return df.LogLevel.Silly;default:break}return df.LogLevel.Error}var s9r=o9r(),$t=new df.ToolsLogger({logLevel:s9r,transports:[new df.ConsoleTransport],logPrefix:"fiori-mcp"});async function wat(){try{let r;try{r=require("@sap-ux/fiori-docs-embeddings")}catch{try{r=await import("@sap-ux/fiori-docs-embeddings")}catch{r=null}}if(!r||typeof r.getDataPath!="function")throw new Error("Package not found or invalid");let n=r.getDataPath();return await Qme.default.access(n),$t.log("\u2713 Using @sap-ux/fiori-docs-embeddings package"),{dataPath:n,embeddingsPath:hf.default.join(n,"embeddings"),searchPath:hf.default.join(n,"search"),docsPath:hf.default.join(n,"docs"),isExternalPackage:!0,isAvailable:!0}}catch{$t.warn("Could not load @sap-ux/fiori-docs-embeddings package, trying local data...")}let e=hf.default.join(__dirname,"../../data");try{return await Qme.default.access(e),$t.log("\u2713 Using local data directory"),{dataPath:e,embeddingsPath:hf.default.join(e,"embeddings"),searchPath:hf.default.join(e,"search"),docsPath:hf.default.join(e,"docs"),isExternalPackage:!1,isAvailable:!0}}catch{$t.warn("Local data directory not available either")}let t=hf.default.join(__dirname,"../../data");return $t.warn("\u26A0\uFE0F No embeddings data available - running in limited mode"),{dataPath:t,embeddingsPath:hf.default.join(t,"embeddings"),searchPath:hf.default.join(t,"search"),docsPath:hf.default.join(t,"docs"),isExternalPackage:!1,isAvailable:!1}}var vc=Ct(bm()),nF=require("node:path");async function uu(e){try{e=(0,nF.join)(e);try{let t=await(0,vc.createApplicationAccess)(e);return{root:t.project.root,appId:t.getAppId(),applicationAccess:t}}catch(t){$t.warn(`Application was not found by given path. Error: ${t}`);let r=await(0,vc.findProjectRoot)(e),n=await(0,vc.getProject)(r);if(n)return{root:n.root,appId:""}}}catch(t){$t.warn(`Project was not found by given path. Error: ${t}`);return}}var b7=e=>{let t;switch(e){case vc.DirName.View:{t=(0,nF.join)(vc.DirName.Ext,vc.DirName.View);break}case vc.DirName.Fragment:{t=(0,nF.join)(vc.DirName.Ext,vc.DirName.Fragment);break}case vc.DirName.Controller:{t=(0,nF.join)(vc.DirName.Ext,vc.DirName.Controller);break}default:t=e}return t},Em=(e,t,r=new Set)=>{if(!e||typeof e!="object")return{};if(e.$ref?.startsWith("#/definitions/")){let i=e.$ref,a=i.replace("#/definitions/",""),o=t.definitions?.[a]??null;if(r.has(i))return{...o};if(r.add(i),o){let s={...e};return delete s.$ref,Em({...o,...s},t,r)}}let n={...e};return n.properties&&(n.properties=Object.fromEntries(Object.entries(n.properties).map(([i,a])=>[i,Em(a,t,r)]))),n.items&&(Array.isArray(n.items)?n.items=n.items.map(i=>Em(i,t,r)):n.items=Em(n.items,t,r)),n.allOf&&(n.allOf=n.allOf.map(i=>Em(i,t,r))),n.anyOf&&(n.anyOf=n.anyOf.map(i=>Em(i,t,r))),n.oneOf&&(n.oneOf=n.oneOf.map(i=>Em(i,t,r))),typeof n.additionalProperties=="object"&&(n.additionalProperties=Em(n.additionalProperties,t,r)),n},xxt=(e,t)=>({type:"object",properties:{[e]:t}}),xa=e=>{let t=Rx(e);return delete t.$schema,t},_m=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof yle?new Error(`Missing required fields in parameters. ${JSON.stringify(r.issues,null,4)}`):new Error("Unknown error. Recheck input parameters.")}};var YIt=require("node:util"),WIt=require("node:child_process"),XIt=Ct(WAe());async function AW(e="1.18.5"){let t="@sap/generator-fiori";if((await(0,XIt.findInstalledPackages)(t,{minVersion:e}))?.length<1)throw new Error(`Fiori generator not found. Please install the Fiori generator >=${e} with 'npm install -g ${t}' and retry this call`)}var CW=(0,YIt.promisify)(WIt.exec);var JIt=require("@lancedb/lancedb");var XAe=Ct(require("fs/promises")),JAe=Ct(require("node:path")),wW=class{connection=null;tables=[];tableIndex=null;metadata=null;dataPath;constructor(t){this.dataPath=t||""}async initialize(){try{$t.log("Loading vector database from pre-built embeddings...");let t=await wat();if(!t.isAvailable)throw new Error("No embeddings data available");this.dataPath=t.embeddingsPath,$t.log(`Using embeddings path: ${this.dataPath} (external: ${t.isExternalPackage})`);let r=JAe.default.join(this.dataPath,"metadata.json"),n=await XAe.default.readFile(r,"utf-8");this.metadata=JSON.parse(n),$t.log("\u2713 Embedding metadata loaded:"),$t.log(` Model: ${this?.metadata?.model}`),$t.log(` Dimensions: ${this?.metadata?.dimensions}`),$t.log(` Total vectors: ${this?.metadata?.totalVectors}`),$t.log(` Created: ${this?.metadata?.createdAt}`),this.connection=await(0,JIt.connect)(this.dataPath);let i=JAe.default.join(this.dataPath,"table_index.json");try{let a=await XAe.default.readFile(i,"utf-8");this.tableIndex=JSON.parse(a),this.tables=[];for(let o of this.tableIndex?.tables||[]){let s=await this.connection.openTable(o);this.tables.push(s)}$t.log(`\u2713 Loaded ${this.tables.length} split tables`)}catch{$t.log("No table index found, trying single table...");try{let a=await this.connection.openTable("documents");this.tables=[a],this.tableIndex={tables:["documents"],totalTables:1,maxVectorsPerTable:-1,totalVectors:this.metadata?.totalVectors||0}}catch(a){throw new Error(`No tables found: ${a}`)}}$t.log("\u2713 Vector database loaded and ready")}catch(t){throw new Error(`Failed to load vector database: ${t}`)}}async semanticSearch(t,r=10,n){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let i=[];for(let o of this.tables){let s=o.vectorSearch(t).limit(r*2);n&&(s=s.where(`category = "${n}"`));let c=await s.toArray();i.push(...c)}return i.sort((o,s)=>(o._distance||0)-(s._distance||0)),i.slice(0,r).map(o=>({document:{id:o.document_id,vector:o.vector,content:o.content,title:o.title,category:o.category,path:o.path,chunk_index:o.chunk_index,metadata:{tags:this.parseJsonField(o.tags_json)||[],headers:this.parseJsonField(o.headers_json)||[],lastModified:new Date(o.lastModified),wordCount:o.wordCount,excerpt:o.excerpt}},score:1-(o._distance||0),distance:o._distance||0}))}catch(i){throw $t.error(`Semantic search failed: ${i}`),new Error(`Semantic search failed: ${i}`)}}async findSimilarToText(t,r=5){return $t.warn("findSimilarToText requires embedding generation - not available in simplified mode"),[]}async findSimilarToDocument(t,r=5){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let n=null;for(let s of this.tables){let c=await s.search("").where(`document_id = "${t}" AND chunk_index = 0`).limit(1).toArray();if(c.length>0){n=c[0].vector;break}}if(!n)return[];let i=[];for(let s of this.tables){let c=await s.vectorSearch(n).where(`document_id != "${t}"`).limit(r*2).toArray();i.push(...c)}let a=new Map;for(let s of i){let c=s.document_id,u=1-(s._distance||0);(!a.has(c)||a.get(c).score<u)&&a.set(c,{...s,score:u,distance:s._distance||0})}return Array.from(a.values()).sort((s,c)=>c.score-s.score).slice(0,r).map(s=>({document:{id:s.document_id,vector:s.vector,content:s.content,title:s.title,category:s.category,path:s.path,chunk_index:s.chunk_index,metadata:{tags:this.parseJsonField(s.tags_json)||[],headers:this.parseJsonField(s.headers_json)||[],lastModified:new Date(s.lastModified),wordCount:s.wordCount,excerpt:s.excerpt}},score:s.score,distance:s.distance}))}catch(n){return $t.error(`Find similar documents failed: ${n}`),[]}}async getDocumentsByCategory(t,r){if(this.tables.length===0)throw new Error("Vector database not initialized");try{let n=[];for(let a of this.tables){let o=a.search("").where(`category = "${t}" AND chunk_index = 0`);r&&(o=o.limit(Math.ceil(r/this.tables.length)+10));let s=await o.toArray();n.push(...s)}return(r?n.slice(0,r):n).map(a=>({document:{id:a.document_id,vector:a.vector,content:a.content,title:a.title,category:a.category,path:a.path,chunk_index:a.chunk_index,metadata:{tags:this.parseJsonField(a.tags_json)||[],headers:this.parseJsonField(a.headers_json)||[],lastModified:new Date(a.lastModified),wordCount:a.wordCount,excerpt:a.excerpt}},score:1,distance:0}))}catch(n){return $t.error(`Get documents by category failed: ${n}`),[]}}getMetadata(){return this.metadata}parseJsonField(t){try{return t?JSON.parse(t):[]}catch{return[]}}isInitialized(){return this.tables.length>0&&this.metadata!==null}async close(){this.connection&&(this.connection=null,this.tables=[],$t.log("Vector database connection closed"))}};var PW=class{pipeline=null;initialized=!1;async initialize(){if(!this.initialized)try{let{pipeline:t}=await import("@xenova/transformers");this.pipeline=await t("feature-extraction","Xenova/all-MiniLM-L6-v2",{quantized:!1}),this.initialized=!0}catch(t){throw new Error(`Failed to initialize text embedding service: ${t}. Make sure @xenova/transformers is available.`)}}async generateEmbedding(t){if(!this.initialized||!this.pipeline)throw new Error("Text embedding service not initialized. Call initialize() first.");try{let r=t.replace(/\n+/g," ").replace(/\s+/g," ").trim().substring(0,8192);if(!r)throw new Error("Empty text provided for embedding");let n=await this.pipeline(r,{pooling:"mean",normalize:!0});return Array.from(n.data)}catch(r){throw new Error(`Failed to generate embedding: ${r}`)}}isInitialized(){return this.initialized}};async function ZAe(e,t=!1){let{query:r,maxResults:n}=e;try{let i=new wW,a=new PW;await i.initialize(),await a.initialize();let o=await a.generateEmbedding(r),s=await i.semanticSearch(o,n??10);if(t){let c="";for(let[u,l]of s.entries())c+=`Result ${u+1}:
|
|
1654
1654
|
|
|
1655
1655
|
`,c+=`${l.document.content}
|
|
1656
1656
|
`,c+=`---
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sap-ux/fiori-mcp-server",
|
|
3
3
|
"description": "SAP Fiori - Model Context Protocol (MCP) server",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.0",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"SAP Fiori tools",
|
|
7
7
|
"SAP Fiori elements",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"esbuild": "0.25.6",
|
|
33
33
|
"@modelcontextprotocol/sdk": "1.24.1",
|
|
34
34
|
"@sap/ux-specification": "1.139.2",
|
|
35
|
-
"@sap-ux/annotation-converter": "0.10.
|
|
35
|
+
"@sap-ux/annotation-converter": "0.10.9",
|
|
36
36
|
"@sap-ux/edmx-parser": "0.9.6",
|
|
37
37
|
"@types/diff": "5.0.9",
|
|
38
38
|
"@types/json-schema": "7.0.5",
|
|
@@ -46,14 +46,14 @@
|
|
|
46
46
|
"promptfoo": "0.119.14",
|
|
47
47
|
"@langchain/mcp-adapters": "1.0.2",
|
|
48
48
|
"@langchain/core": "1.1.1",
|
|
49
|
-
"@sap-ux/axios-extension": "1.24.6",
|
|
50
49
|
"@sap-ux/project-access": "1.32.16",
|
|
51
|
-
"@sap-ux/fiori-annotation-api": "0.
|
|
50
|
+
"@sap-ux/fiori-annotation-api": "0.8.0",
|
|
51
|
+
"@sap-ux/axios-extension": "1.25.0",
|
|
52
52
|
"@sap-ux/fiori-docs-embeddings": "0.4.6",
|
|
53
53
|
"@sap-ux/i18n": "0.3.6",
|
|
54
54
|
"@sap-ux/logger": "0.7.2",
|
|
55
|
-
"@sap-ux/odata-annotation-core-types": "0.5.2",
|
|
56
55
|
"@sap-ux/odata-entity-model": "0.3.3",
|
|
56
|
+
"@sap-ux/odata-annotation-core-types": "0.5.2",
|
|
57
57
|
"@sap-ux/text-document-utils": "0.3.3",
|
|
58
58
|
"@sap-ux/btp-utils": "1.1.6",
|
|
59
59
|
"@sap-ux/feature-toggle": "0.3.5",
|