@sap-ux/fiori-mcp-server 0.6.4 → 0.6.5
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 PT(e,t){if(e instanceof $A){let n=new dk(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 dk(t);return r.process(e),r.emit(e,t)}function Wc(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 Wc(n.element,r);if(n.type==="set")return Wc(n.valueType,r);if(n.type==="lazy")return Wc(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 Wc(n.innerType,r);if(n.type==="intersection")return Wc(n.left,r)||Wc(n.right,r);if(n.type==="record"||n.type==="map")return Wc(n.keyType,r)||Wc(n.valueType,r);if(n.type==="pipe")return Wc(n.in,r)||Wc(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Wc(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Wc(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Wc(i,r))return!0;return!!(n.rest&&Wc(n.rest,r))}return!1}var gGe={};function JA(e){return!!e._zod}function n0(e,t){return JA(e)?xT(e,t):e.safeParse(t)}function z6(e){var t,r;if(!e)return;let n;if(JA(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 bGe(e){var t;if(JA(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 DT={};Ni(DT,{$brand:()=>wL,$input:()=>e6,$output:()=>Q8,NEVER:()=>x3,TimePrecision:()=>i6,ZodAny:()=>AGe,ZodArray:()=>DGe,ZodBase64:()=>kle,ZodBase64URL:()=>$le,ZodBigInt:()=>bk,ZodBigIntFormat:()=>jle,ZodBoolean:()=>vk,ZodCIDRv4:()=>Rle,ZodCIDRv6:()=>Lle,ZodCUID:()=>Ale,ZodCUID2:()=>Cle,ZodCatch:()=>KGe,ZodCodec:()=>Kle,ZodCustom:()=>i5,ZodCustomStringFormat:()=>gk,ZodDate:()=>t5,ZodDefault:()=>VGe,ZodDiscriminatedUnion:()=>NGe,ZodE164:()=>Mle,ZodEmail:()=>Tle,ZodEmoji:()=>Ole,ZodEnum:()=>hk,ZodError:()=>sle,ZodFile:()=>FGe,ZodFirstPartyTypeKind:()=>Wle,ZodFunction:()=>rKe,ZodGUID:()=>X6,ZodIPv4:()=>Nle,ZodIPv6:()=>Ile,ZodISODate:()=>G6,ZodISODateTime:()=>H6,ZodISODuration:()=>Y6,ZodISOTime:()=>K6,ZodIntersection:()=>IGe,ZodIssueCode:()=>DCr,ZodJWT:()=>Fle,ZodKSUID:()=>Dle,ZodLazy:()=>QGe,ZodLiteral:()=>MGe,ZodMAC:()=>TGe,ZodMap:()=>kGe,ZodNaN:()=>WGe,ZodNanoID:()=>Sle,ZodNever:()=>wGe,ZodNonOptional:()=>Hle,ZodNull:()=>SGe,ZodNullable:()=>qGe,ZodNumber:()=>yk,ZodNumberFormat:()=>ZA,ZodObject:()=>r5,ZodOptional:()=>zle,ZodPipe:()=>Gle,ZodPrefault:()=>BGe,ZodPromise:()=>tKe,ZodReadonly:()=>XGe,ZodRealError:()=>qu,ZodRecord:()=>Ule,ZodSet:()=>$Ge,ZodString:()=>mk,ZodStringFormat:()=>ui,ZodSuccess:()=>GGe,ZodSymbol:()=>xGe,ZodTemplateLiteral:()=>ZGe,ZodTransform:()=>jGe,ZodTuple:()=>RGe,ZodType:()=>Ar,ZodULID:()=>wle,ZodURL:()=>Q6,ZodUUID:()=>py,ZodUndefined:()=>OGe,ZodUnion:()=>Vle,ZodUnknown:()=>CGe,ZodVoid:()=>PGe,ZodXID:()=>Ple,_ZodString:()=>_le,_default:()=>UGe,_function:()=>xCr,any:()=>e5,array:()=>Bt,base64:()=>HAr,base64url:()=>GAr,bigint:()=>nCr,boolean:()=>Ji,catch:()=>YGe,check:()=>OCr,cidrv4:()=>BAr,cidrv6:()=>zAr,clone:()=>Ts,codec:()=>ECr,coerce:()=>Xle,config:()=>ga,core:()=>rp,cuid:()=>kAr,cuid2:()=>$Ar,custom:()=>Yle,date:()=>uCr,decode:()=>dle,decodeAsync:()=>mle,describe:()=>SCr,discriminatedUnion:()=>n5,e164:()=>KAr,email:()=>AAr,emoji:()=>RAr,encode:()=>fle,encodeAsync:()=>hle,endsWith:()=>HA,enum:()=>$n,file:()=>gCr,flattenError:()=>xA,float32:()=>QAr,float64:()=>eCr,formatError:()=>OA,function:()=>xCr,getErrorMap:()=>ICr,globalRegistry:()=>ec,gt:()=>Bh,gte:()=>tc,guid:()=>CAr,hash:()=>ZAr,hex:()=>JAr,hostname:()=>XAr,httpUrl:()=>IAr,includes:()=>BA,instanceof:()=>CCr,int:()=>Ele,int32:()=>tCr,int64:()=>iCr,intersection:()=>_k,ipv4:()=>qAr,ipv6:()=>UAr,iso:()=>W6,json:()=>PCr,jwt:()=>YAr,keyof:()=>lCr,ksuid:()=>jAr,lazy:()=>eKe,length:()=>CT,literal:()=>dt,locales:()=>kA,looseObject:()=>np,lowercase:()=>VA,lt:()=>Uh,lte:()=>ju,mac:()=>VAr,map:()=>dCr,maxLength:()=>AT,maxSize:()=>ST,meta:()=>ACr,mime:()=>GA,minLength:()=>ly,minSize:()=>r0,multipleOf:()=>t0,nan:()=>bCr,nanoid:()=>LAr,nativeEnum:()=>mCr,negative:()=>R6,never:()=>qle,nonnegative:()=>k6,nonoptional:()=>HGe,nonpositive:()=>L6,normalize:()=>KA,null:()=>Ek,nullable:()=>J6,nullish:()=>yCr,number:()=>kn,object:()=>Ae,optional:()=>pt,overwrite:()=>Cd,parse:()=>cle,parseAsync:()=>ule,partialRecord:()=>fCr,pipe:()=>Z6,positive:()=>I6,prefault:()=>zGe,preprocess:()=>a5,prettifyError:()=>C3,promise:()=>TCr,property:()=>$6,readonly:()=>JGe,record:()=>vi,refine:()=>nKe,regex:()=>qA,regexes:()=>Fu,registry:()=>HL,safeDecode:()=>yle,safeDecodeAsync:()=>ble,safeEncode:()=>gle,safeEncodeAsync:()=>vle,safeParse:()=>lle,safeParseAsync:()=>ple,set:()=>hCr,setErrorMap:()=>NCr,size:()=>jA,slugify:()=>fk,startsWith:()=>zA,strictObject:()=>pCr,string:()=>re,stringFormat:()=>WAr,stringbool:()=>wCr,success:()=>vCr,superRefine:()=>iKe,symbol:()=>oCr,templateLiteral:()=>_Cr,toJSONSchema:()=>PT,toLowerCase:()=>WA,toUpperCase:()=>XA,transform:()=>Ble,treeifyError:()=>A3,trim:()=>YA,tuple:()=>LGe,uint32:()=>rCr,uint64:()=>aCr,ulid:()=>MAr,undefined:()=>sCr,union:()=>dn,unknown:()=>li,uppercase:()=>UA,url:()=>xle,util:()=>Le,uuid:()=>wAr,uuidv4:()=>PAr,uuidv6:()=>DAr,uuidv7:()=>NAr,void:()=>cCr,xid:()=>FAr});var W6={};Ni(W6,{ZodISODate:()=>G6,ZodISODateTime:()=>H6,ZodISODuration:()=>Y6,ZodISOTime:()=>K6,date:()=>ile,datetime:()=>nle,duration:()=>ole,time:()=>ale});var H6=ne("ZodISODateTime",(e,t)=>{t8.init(e,t),ui.init(e,t)});function nle(e){return a6(H6,e)}var G6=ne("ZodISODate",(e,t)=>{r8.init(e,t),ui.init(e,t)});function ile(e){return o6(G6,e)}var K6=ne("ZodISOTime",(e,t)=>{n8.init(e,t),ui.init(e,t)});function ale(e){return s6(K6,e)}var Y6=ne("ZodISODuration",(e,t)=>{i8.init(e,t),ui.init(e,t)});function ole(e){return c6(Y6,e)}var _Ge=(e,t)=>{kL.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>OA(e,r)},flatten:{value:r=>xA(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,EA,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,EA,2)}},isEmpty:{get(){return e.issues.length===0}}})},sle=ne("ZodError",_Ge),qu=ne("ZodError",_Ge,{Parent:Error});var cle=SA(qu),ule=CA(qu),lle=PA(qu),ple=DA(qu),fle=w3(qu),dle=P3(qu),hle=D3(qu),mle=N3(qu),gle=I3(qu),yle=R3(qu),vle=L3(qu),ble=k3(qu);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)=>cle(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>lle(e,r,n),e.parseAsync=async(r,n)=>ule(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>ple(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>fle(e,r,n),e.decode=(r,n)=>dle(e,r,n),e.encodeAsync=async(r,n)=>hle(e,r,n),e.decodeAsync=async(r,n)=>mle(e,r,n),e.safeEncode=(r,n)=>gle(e,r,n),e.safeDecode=(r,n)=>yle(e,r,n),e.safeEncodeAsync=async(r,n)=>vle(e,r,n),e.safeDecodeAsync=async(r,n)=>ble(e,r,n),e.refine=(r,n)=>e.check(nKe(r,n)),e.superRefine=r=>e.check(iKe(r)),e.overwrite=r=>e.check(Cd(r)),e.optional=()=>pt(e),e.nullable=()=>J6(e),e.nullish=()=>pt(J6(e)),e.nonoptional=r=>HGe(e,r),e.array=()=>Bt(e),e.or=r=>dn([e,r]),e.and=r=>_k(e,r),e.transform=r=>Z6(e,Ble(r)),e.default=r=>UGe(e,r),e.prefault=r=>zGe(e,r),e.catch=r=>YGe(e,r),e.pipe=r=>Z6(e,r),e.readonly=()=>JGe(e),e.describe=r=>{let n=e.clone();return ec.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return ec.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return ec.get(e);let n=e.clone();return ec.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),_le=ne("_ZodString",(e,t)=>{e0.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(qA(...n)),e.includes=(...n)=>e.check(BA(...n)),e.startsWith=(...n)=>e.check(zA(...n)),e.endsWith=(...n)=>e.check(HA(...n)),e.min=(...n)=>e.check(ly(...n)),e.max=(...n)=>e.check(AT(...n)),e.length=(...n)=>e.check(CT(...n)),e.nonempty=(...n)=>e.check(ly(1,...n)),e.lowercase=n=>e.check(VA(n)),e.uppercase=n=>e.check(UA(n)),e.trim=()=>e.check(YA()),e.normalize=(...n)=>e.check(KA(...n)),e.toLowerCase=()=>e.check(WA()),e.toUpperCase=()=>e.check(XA()),e.slugify=()=>e.check(fk())}),mk=ne("ZodString",(e,t)=>{e0.init(e,t),_le.init(e,t),e.email=r=>e.check(GL(Tle,r)),e.url=r=>e.check(FA(Q6,r)),e.jwt=r=>e.check(pk(Fle,r)),e.emoji=r=>e.check(JL(Ole,r)),e.guid=r=>e.check(MA(X6,r)),e.uuid=r=>e.check(KL(py,r)),e.uuidv4=r=>e.check(YL(py,r)),e.uuidv6=r=>e.check(WL(py,r)),e.uuidv7=r=>e.check(XL(py,r)),e.nanoid=r=>e.check(ZL(Sle,r)),e.guid=r=>e.check(MA(X6,r)),e.cuid=r=>e.check(QL(Ale,r)),e.cuid2=r=>e.check(ek(Cle,r)),e.ulid=r=>e.check(tk(wle,r)),e.base64=r=>e.check(ck(kle,r)),e.base64url=r=>e.check(uk($le,r)),e.xid=r=>e.check(rk(Ple,r)),e.ksuid=r=>e.check(nk(Dle,r)),e.ipv4=r=>e.check(ik(Nle,r)),e.ipv6=r=>e.check(ak(Ile,r)),e.cidrv4=r=>e.check(ok(Rle,r)),e.cidrv6=r=>e.check(sk(Lle,r)),e.e164=r=>e.check(lk(Mle,r)),e.datetime=r=>e.check(nle(r)),e.date=r=>e.check(ile(r)),e.time=r=>e.check(ale(r)),e.duration=r=>e.check(ole(r))});function re(e){return t6(mk,e)}var ui=ne("ZodStringFormat",(e,t)=>{Kn.init(e,t),_le.init(e,t)}),Tle=ne("ZodEmail",(e,t)=>{G3.init(e,t),ui.init(e,t)});function AAr(e){return GL(Tle,e)}var X6=ne("ZodGUID",(e,t)=>{z3.init(e,t),ui.init(e,t)});function CAr(e){return MA(X6,e)}var py=ne("ZodUUID",(e,t)=>{H3.init(e,t),ui.init(e,t)});function wAr(e){return KL(py,e)}function PAr(e){return YL(py,e)}function DAr(e){return WL(py,e)}function NAr(e){return XL(py,e)}var Q6=ne("ZodURL",(e,t)=>{K3.init(e,t),ui.init(e,t)});function xle(e){return FA(Q6,e)}function IAr(e){return FA(Q6,{protocol:/^https?$/,hostname:Fu.domain,...Le.normalizeParams(e)})}var Ole=ne("ZodEmoji",(e,t)=>{Y3.init(e,t),ui.init(e,t)});function RAr(e){return JL(Ole,e)}var Sle=ne("ZodNanoID",(e,t)=>{W3.init(e,t),ui.init(e,t)});function LAr(e){return ZL(Sle,e)}var Ale=ne("ZodCUID",(e,t)=>{X3.init(e,t),ui.init(e,t)});function kAr(e){return QL(Ale,e)}var Cle=ne("ZodCUID2",(e,t)=>{J3.init(e,t),ui.init(e,t)});function $Ar(e){return ek(Cle,e)}var wle=ne("ZodULID",(e,t)=>{Z3.init(e,t),ui.init(e,t)});function MAr(e){return tk(wle,e)}var Ple=ne("ZodXID",(e,t)=>{Q3.init(e,t),ui.init(e,t)});function FAr(e){return rk(Ple,e)}var Dle=ne("ZodKSUID",(e,t)=>{e8.init(e,t),ui.init(e,t)});function jAr(e){return nk(Dle,e)}var Nle=ne("ZodIPv4",(e,t)=>{a8.init(e,t),ui.init(e,t)});function qAr(e){return ik(Nle,e)}var TGe=ne("ZodMAC",(e,t)=>{s8.init(e,t),ui.init(e,t)});function VAr(e){return n6(TGe,e)}var Ile=ne("ZodIPv6",(e,t)=>{o8.init(e,t),ui.init(e,t)});function UAr(e){return ak(Ile,e)}var Rle=ne("ZodCIDRv4",(e,t)=>{c8.init(e,t),ui.init(e,t)});function BAr(e){return ok(Rle,e)}var Lle=ne("ZodCIDRv6",(e,t)=>{u8.init(e,t),ui.init(e,t)});function zAr(e){return sk(Lle,e)}var kle=ne("ZodBase64",(e,t)=>{l8.init(e,t),ui.init(e,t)});function HAr(e){return ck(kle,e)}var $le=ne("ZodBase64URL",(e,t)=>{p8.init(e,t),ui.init(e,t)});function GAr(e){return uk($le,e)}var Mle=ne("ZodE164",(e,t)=>{f8.init(e,t),ui.init(e,t)});function KAr(e){return lk(Mle,e)}var Fle=ne("ZodJWT",(e,t)=>{d8.init(e,t),ui.init(e,t)});function YAr(e){return pk(Fle,e)}var gk=ne("ZodCustomStringFormat",(e,t)=>{h8.init(e,t),ui.init(e,t)});function WAr(e,t,r={}){return wT(gk,e,t,r)}function XAr(e){return wT(gk,"hostname",Fu.hostname,e)}function JAr(e){return wT(gk,"hex",Fu.hex,e)}function ZAr(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,i=Fu[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return wT(gk,n,i,t)}var yk=ne("ZodNumber",(e,t)=>{jL.init(e,t),Ar.init(e,t),e.gt=(n,i)=>e.check(Bh(n,i)),e.gte=(n,i)=>e.check(tc(n,i)),e.min=(n,i)=>e.check(tc(n,i)),e.lt=(n,i)=>e.check(Uh(n,i)),e.lte=(n,i)=>e.check(ju(n,i)),e.max=(n,i)=>e.check(ju(n,i)),e.int=n=>e.check(Ele(n)),e.safe=n=>e.check(Ele(n)),e.positive=n=>e.check(Bh(0,n)),e.nonnegative=n=>e.check(tc(0,n)),e.negative=n=>e.check(Uh(0,n)),e.nonpositive=n=>e.check(ju(0,n)),e.multipleOf=(n,i)=>e.check(t0(n,i)),e.step=(n,i)=>e.check(t0(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 u6(yk,e)}var ZA=ne("ZodNumberFormat",(e,t)=>{m8.init(e,t),yk.init(e,t)});function Ele(e){return p6(ZA,e)}function QAr(e){return f6(ZA,e)}function eCr(e){return d6(ZA,e)}function tCr(e){return h6(ZA,e)}function rCr(e){return m6(ZA,e)}var vk=ne("ZodBoolean",(e,t)=>{RA.init(e,t),Ar.init(e,t)});function Ji(e){return g6(vk,e)}var bk=ne("ZodBigInt",(e,t)=>{qL.init(e,t),Ar.init(e,t),e.gte=(n,i)=>e.check(tc(n,i)),e.min=(n,i)=>e.check(tc(n,i)),e.gt=(n,i)=>e.check(Bh(n,i)),e.gte=(n,i)=>e.check(tc(n,i)),e.min=(n,i)=>e.check(tc(n,i)),e.lt=(n,i)=>e.check(Uh(n,i)),e.lte=(n,i)=>e.check(ju(n,i)),e.max=(n,i)=>e.check(ju(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(ju(BigInt(0),n)),e.nonnegative=n=>e.check(tc(BigInt(0),n)),e.multipleOf=(n,i)=>e.check(t0(n,i));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function nCr(e){return v6(bk,e)}var jle=ne("ZodBigIntFormat",(e,t)=>{g8.init(e,t),bk.init(e,t)});function iCr(e){return E6(jle,e)}function aCr(e){return _6(jle,e)}var xGe=ne("ZodSymbol",(e,t)=>{y8.init(e,t),Ar.init(e,t)});function oCr(e){return T6(xGe,e)}var OGe=ne("ZodUndefined",(e,t)=>{v8.init(e,t),Ar.init(e,t)});function sCr(e){return x6(OGe,e)}var SGe=ne("ZodNull",(e,t)=>{b8.init(e,t),Ar.init(e,t)});function Ek(e){return O6(SGe,e)}var AGe=ne("ZodAny",(e,t)=>{E8.init(e,t),Ar.init(e,t)});function e5(){return S6(AGe)}var CGe=ne("ZodUnknown",(e,t)=>{_8.init(e,t),Ar.init(e,t)});function li(){return A6(CGe)}var wGe=ne("ZodNever",(e,t)=>{T8.init(e,t),Ar.init(e,t)});function qle(e){return C6(wGe,e)}var PGe=ne("ZodVoid",(e,t)=>{x8.init(e,t),Ar.init(e,t)});function cCr(e){return w6(PGe,e)}var t5=ne("ZodDate",(e,t)=>{O8.init(e,t),Ar.init(e,t),e.min=(n,i)=>e.check(tc(n,i)),e.max=(n,i)=>e.check(ju(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 uCr(e){return P6(t5,e)}var DGe=ne("ZodArray",(e,t)=>{S8.init(e,t),Ar.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(ly(r,n)),e.nonempty=r=>e.check(ly(1,r)),e.max=(r,n)=>e.check(AT(r,n)),e.length=(r,n)=>e.check(CT(r,n)),e.unwrap=()=>e.element});function Bt(e,t){return rle(DGe,e,t)}function lCr(e){let t=e._zod.def.shape;return $n(Object.keys(t))}var r5=ne("ZodObject",(e,t)=>{tle.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:qle()}),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(zle,e,r[0]),e.required=(...r)=>Le.required(Hle,e,r[0])});function Ae(e,t){let r={type:"object",shape:e??{},...Le.normalizeParams(t)};return new r5(r)}function pCr(e,t){return new r5({type:"object",shape:e,catchall:qle(),...Le.normalizeParams(t)})}function np(e,t){return new r5({type:"object",shape:e,catchall:li(),...Le.normalizeParams(t)})}var Vle=ne("ZodUnion",(e,t)=>{VL.init(e,t),Ar.init(e,t),e.options=t.options});function dn(e,t){return new Vle({type:"union",options:e,...Le.normalizeParams(t)})}var NGe=ne("ZodDiscriminatedUnion",(e,t)=>{Vle.init(e,t),A8.init(e,t)});function n5(e,t,r){return new NGe({type:"union",options:t,discriminator:e,...Le.normalizeParams(r)})}var IGe=ne("ZodIntersection",(e,t)=>{C8.init(e,t),Ar.init(e,t)});function _k(e,t){return new IGe({type:"intersection",left:e,right:t})}var RGe=ne("ZodTuple",(e,t)=>{UL.init(e,t),Ar.init(e,t),e.rest=r=>e.clone({...e._zod.def,rest:r})});function LGe(e,t,r){let n=t instanceof Wt,i=n?r:t,a=n?t:null;return new RGe({type:"tuple",items:e,rest:a,...Le.normalizeParams(i)})}var Ule=ne("ZodRecord",(e,t)=>{w8.init(e,t),Ar.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function vi(e,t,r){return new Ule({type:"record",keyType:e,valueType:t,...Le.normalizeParams(r)})}function fCr(e,t,r){let n=Ts(e);return n._zod.values=void 0,new Ule({type:"record",keyType:n,valueType:t,...Le.normalizeParams(r)})}var kGe=ne("ZodMap",(e,t)=>{P8.init(e,t),Ar.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function dCr(e,t,r){return new kGe({type:"map",keyType:e,valueType:t,...Le.normalizeParams(r)})}var $Ge=ne("ZodSet",(e,t)=>{D8.init(e,t),Ar.init(e,t),e.min=(...r)=>e.check(r0(...r)),e.nonempty=r=>e.check(r0(1,r)),e.max=(...r)=>e.check(ST(...r)),e.size=(...r)=>e.check(jA(...r))});function hCr(e,t){return new $Ge({type:"set",valueType:e,...Le.normalizeParams(t)})}var hk=ne("ZodEnum",(e,t)=>{N8.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 hk({...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 hk({...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 hk({type:"enum",entries:r,...Le.normalizeParams(t)})}function mCr(e,t){return new hk({type:"enum",entries:e,...Le.normalizeParams(t)})}var MGe=ne("ZodLiteral",(e,t)=>{I8.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 MGe({type:"literal",values:Array.isArray(e)?e:[e],...Le.normalizeParams(t)})}var FGe=ne("ZodFile",(e,t)=>{R8.init(e,t),Ar.init(e,t),e.min=(r,n)=>e.check(r0(r,n)),e.max=(r,n)=>e.check(ST(r,n)),e.mime=(r,n)=>e.check(GA(Array.isArray(r)?r:[r],n))});function gCr(e){return M6(FGe,e)}var jGe=ne("ZodTransform",(e,t)=>{L8.init(e,t),Ar.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Yb(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 Ble(e){return new jGe({type:"transform",transform:e})}var zle=ne("ZodOptional",(e,t)=>{k8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function pt(e){return new zle({type:"optional",innerType:e})}var qGe=ne("ZodNullable",(e,t)=>{$8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function J6(e){return new qGe({type:"nullable",innerType:e})}function yCr(e){return pt(J6(e))}var VGe=ne("ZodDefault",(e,t)=>{M8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function UGe(e,t){return new VGe({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Le.shallowClone(t)}})}var BGe=ne("ZodPrefault",(e,t)=>{F8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function zGe(e,t){return new BGe({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Le.shallowClone(t)}})}var Hle=ne("ZodNonOptional",(e,t)=>{j8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function HGe(e,t){return new Hle({type:"nonoptional",innerType:e,...Le.normalizeParams(t)})}var GGe=ne("ZodSuccess",(e,t)=>{q8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function vCr(e){return new GGe({type:"success",innerType:e})}var KGe=ne("ZodCatch",(e,t)=>{V8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function YGe(e,t){return new KGe({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var WGe=ne("ZodNaN",(e,t)=>{U8.init(e,t),Ar.init(e,t)});function bCr(e){return N6(WGe,e)}var Gle=ne("ZodPipe",(e,t)=>{B8.init(e,t),Ar.init(e,t),e.in=t.in,e.out=t.out});function Z6(e,t){return new Gle({type:"pipe",in:e,out:t})}var Kle=ne("ZodCodec",(e,t)=>{Gle.init(e,t),LA.init(e,t)});function ECr(e,t,r){return new Kle({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}var XGe=ne("ZodReadonly",(e,t)=>{z8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function JGe(e){return new XGe({type:"readonly",innerType:e})}var ZGe=ne("ZodTemplateLiteral",(e,t)=>{H8.init(e,t),Ar.init(e,t)});function _Cr(e,t){return new ZGe({type:"template_literal",parts:e,...Le.normalizeParams(t)})}var QGe=ne("ZodLazy",(e,t)=>{Y8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.getter()});function eKe(e){return new QGe({type:"lazy",getter:e})}var tKe=ne("ZodPromise",(e,t)=>{K8.init(e,t),Ar.init(e,t),e.unwrap=()=>e._zod.def.innerType});function TCr(e){return new tKe({type:"promise",innerType:e})}var rKe=ne("ZodFunction",(e,t)=>{G8.init(e,t),Ar.init(e,t)});function xCr(e){return new rKe({type:"function",input:Array.isArray(e?.input)?LGe(e?.input):e?.input??Bt(li()),output:e?.output??li()})}var i5=ne("ZodCustom",(e,t)=>{W8.init(e,t),Ar.init(e,t)});function OCr(e){let t=new ri({check:"custom"});return t._zod.check=e,t}function Yle(e,t){return F6(i5,e??(()=>!0),t)}function nKe(e,t={}){return j6(i5,e,t)}function iKe(e){return q6(e)}var SCr=V6,ACr=U6;function CCr(e,t={error:`Input not instance of ${e.name}`}){let r=new i5({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...Le.normalizeParams(t)});return r._zod.bag.Class=e,r}var wCr=(...e)=>B6({Codec:Kle,Boolean:vk,String:mk},...e);function PCr(e){let t=eKe(()=>dn([re(e),kn(),Ji(),Ek(),Bt(t),vi(re(),t)]));return t}function a5(e,t){return Z6(Ble(e),t)}var DCr={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 NCr(e){ga({customError:e})}function ICr(){return ga().customError}var Wle;Wle||(Wle={});var Xle={};Ni(Xle,{bigint:()=>$Cr,boolean:()=>kCr,date:()=>MCr,number:()=>LCr,string:()=>RCr});function RCr(e){return r6(mk,e)}function LCr(e){return l6(yk,e)}function kCr(e){return y6(vk,e)}function $Cr(e){return b6(bk,e)}function MCr(e){return D6(t5,e)}ga(X8());var Zle="2025-11-25";var aKe=[Zle,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Hh="io.modelcontextprotocol/related-task",s5="2.0",zh=Yle(e=>e!==null&&(typeof e=="object"||typeof e=="function")),oKe=dn([re(),kn().int()]),sKe=re(),jCr=np({ttl:dn([kn(),Ek()]).optional(),pollInterval:kn().optional()}),Qle=np({taskId:re()}),qCr=np({progressToken:oKe.optional(),[Hh]:Qle.optional()}),Vu=np({task:jCr.optional(),_meta:qCr.optional()}),xs=Ae({method:re(),params:Vu.optional()}),NT=np({_meta:Ae({[Hh]:pt(Qle)}).passthrough().optional()}),nf=Ae({method:re(),params:NT.optional()}),rc=np({_meta:np({[Hh]:Qle.optional()}).optional()}),c5=dn([re(),kn().int()]),cKe=Ae({jsonrpc:dt(s5),id:c5,...xs.shape}).strict(),epe=e=>cKe.safeParse(e).success,uKe=Ae({jsonrpc:dt(s5),...nf.shape}).strict(),lKe=e=>uKe.safeParse(e).success,pKe=Ae({jsonrpc:dt(s5),id:c5,result:rc}).strict(),Tk=e=>pKe.safeParse(e).success,on;(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"})(on||(on={}));var fKe=Ae({jsonrpc:dt(s5),id:c5,error:Ae({code:kn().int(),message:re(),data:pt(li())})}).strict(),dKe=e=>fKe.safeParse(e).success,hKe=dn([cKe,uKe,pKe,fKe]),u5=rc.strict(),VCr=NT.extend({requestId:c5,reason:re().optional()}),l5=nf.extend({method:dt("notifications/cancelled"),params:VCr}),UCr=Ae({src:re(),mimeType:re().optional(),sizes:Bt(re()).optional()}),xk=Ae({icons:Bt(UCr).optional()}),QA=Ae({name:re(),title:re().optional()}),mKe=QA.extend({...QA.shape,...xk.shape,version:re(),websiteUrl:re().optional()}),BCr=_k(Ae({applyDefaults:Ji().optional()}),vi(re(),li())),zCr=a5(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,_k(Ae({form:BCr.optional(),url:zh.optional()}),vi(re(),li()).optional())),HCr=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(),GCr=Ae({list:pt(Ae({}).passthrough()),cancel:pt(Ae({}).passthrough()),requests:pt(Ae({tools:pt(Ae({call:pt(Ae({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),KCr=Ae({experimental:vi(re(),zh).optional(),sampling:Ae({context:zh.optional(),tools:zh.optional()}).optional(),elicitation:zCr.optional(),roots:Ae({listChanged:Ji().optional()}).optional(),tasks:pt(HCr)}),YCr=Vu.extend({protocolVersion:re(),capabilities:KCr,clientInfo:mKe}),tpe=xs.extend({method:dt("initialize"),params:YCr});var WCr=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(GCr)}).passthrough(),XCr=rc.extend({protocolVersion:re(),capabilities:WCr,serverInfo:mKe,instructions:re().optional()}),rpe=nf.extend({method:dt("notifications/initialized")});var p5=xs.extend({method:dt("ping")}),JCr=Ae({progress:kn(),total:pt(kn()),message:pt(re())}),ZCr=Ae({...NT.shape,...JCr.shape,progressToken:oKe}),f5=nf.extend({method:dt("notifications/progress"),params:ZCr}),QCr=Vu.extend({cursor:sKe.optional()}),Ok=xs.extend({params:QCr.optional()}),Sk=rc.extend({nextCursor:pt(sKe)}),Ak=Ae({taskId:re(),status:$n(["working","input_required","completed","failed","cancelled"]),ttl:dn([kn(),Ek()]),createdAt:re(),lastUpdatedAt:re(),pollInterval:pt(kn()),statusMessage:pt(re())}),eC=rc.extend({task:Ak}),ewr=NT.merge(Ak),Ck=nf.extend({method:dt("notifications/tasks/status"),params:ewr}),d5=xs.extend({method:dt("tasks/get"),params:Vu.extend({taskId:re()})}),h5=rc.merge(Ak),m5=xs.extend({method:dt("tasks/result"),params:Vu.extend({taskId:re()})}),g5=Ok.extend({method:dt("tasks/list")}),y5=Sk.extend({tasks:Bt(Ak)}),gKe=xs.extend({method:dt("tasks/cancel"),params:Vu.extend({taskId:re()})}),yKe=rc.merge(Ak),vKe=Ae({uri:re(),mimeType:pt(re()),_meta:vi(re(),li()).optional()}),bKe=vKe.extend({text:re()}),npe=re().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),EKe=vKe.extend({blob:npe}),_Ke=Ae({...QA.shape,...xk.shape,uri:re(),description:pt(re()),mimeType:pt(re()),_meta:pt(np({}))}),twr=Ae({...QA.shape,...xk.shape,uriTemplate:re(),description:pt(re()),mimeType:pt(re()),_meta:pt(np({}))}),rwr=Ok.extend({method:dt("resources/list")}),nwr=Sk.extend({resources:Bt(_Ke)}),iwr=Ok.extend({method:dt("resources/templates/list")}),awr=Sk.extend({resourceTemplates:Bt(twr)}),ipe=Vu.extend({uri:re()}),owr=ipe,swr=xs.extend({method:dt("resources/read"),params:owr}),cwr=rc.extend({contents:Bt(dn([bKe,EKe]))}),uwr=nf.extend({method:dt("notifications/resources/list_changed")}),lwr=ipe,pwr=xs.extend({method:dt("resources/subscribe"),params:lwr}),fwr=ipe,dwr=xs.extend({method:dt("resources/unsubscribe"),params:fwr}),hwr=NT.extend({uri:re()}),mwr=nf.extend({method:dt("notifications/resources/updated"),params:hwr}),gwr=Ae({name:re(),description:pt(re()),required:pt(Ji())}),ywr=Ae({...QA.shape,...xk.shape,description:pt(re()),arguments:pt(Bt(gwr)),_meta:pt(np({}))}),vwr=Ok.extend({method:dt("prompts/list")}),bwr=Sk.extend({prompts:Bt(ywr)}),Ewr=Vu.extend({name:re(),arguments:vi(re(),re()).optional()}),_wr=xs.extend({method:dt("prompts/get"),params:Ewr}),ape=Ae({type:dt("text"),text:re(),_meta:vi(re(),li()).optional()}),ope=Ae({type:dt("image"),data:npe,mimeType:re(),_meta:vi(re(),li()).optional()}),spe=Ae({type:dt("audio"),data:npe,mimeType:re(),_meta:vi(re(),li()).optional()}),Twr=Ae({type:dt("tool_use"),name:re(),id:re(),input:Ae({}).passthrough(),_meta:pt(Ae({}).passthrough())}).passthrough(),xwr=Ae({type:dt("resource"),resource:dn([bKe,EKe]),_meta:vi(re(),li()).optional()}),Owr=_Ke.extend({type:dt("resource_link")}),cpe=dn([ape,ope,spe,Owr,xwr]),Swr=Ae({role:$n(["user","assistant"]),content:cpe}),Awr=rc.extend({description:pt(re()),messages:Bt(Swr)}),Cwr=nf.extend({method:dt("notifications/prompts/list_changed")}),wwr=Ae({title:re().optional(),readOnlyHint:Ji().optional(),destructiveHint:Ji().optional(),idempotentHint:Ji().optional(),openWorldHint:Ji().optional()}),Pwr=Ae({taskSupport:$n(["required","optional","forbidden"]).optional()}),TKe=Ae({...QA.shape,...xk.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(wwr),execution:pt(Pwr),_meta:vi(re(),li()).optional()}),upe=Ok.extend({method:dt("tools/list")}),Dwr=Sk.extend({tools:Bt(TKe)}),v5=rc.extend({content:Bt(cpe).default([]),structuredContent:vi(re(),li()).optional(),isError:pt(Ji())}),gOi=v5.or(rc.extend({toolResult:li()})),Nwr=Vu.extend({name:re(),arguments:pt(vi(re(),li()))}),wk=xs.extend({method:dt("tools/call"),params:Nwr}),Iwr=nf.extend({method:dt("notifications/tools/list_changed")}),Pk=$n(["debug","info","notice","warning","error","critical","alert","emergency"]),Rwr=Vu.extend({level:Pk}),lpe=xs.extend({method:dt("logging/setLevel"),params:Rwr}),Lwr=NT.extend({level:Pk,logger:re().optional(),data:li()}),kwr=nf.extend({method:dt("notifications/message"),params:Lwr}),$wr=Ae({name:re().optional()}),Mwr=Ae({hints:pt(Bt($wr)),costPriority:pt(kn().min(0).max(1)),speedPriority:pt(kn().min(0).max(1)),intelligencePriority:pt(kn().min(0).max(1))}),Fwr=Ae({mode:pt($n(["auto","required","none"]))}),jwr=Ae({type:dt("tool_result"),toolUseId:re().describe("The unique identifier for the corresponding tool call."),content:Bt(cpe).default([]),structuredContent:Ae({}).passthrough().optional(),isError:pt(Ji()),_meta:pt(Ae({}).passthrough())}).passthrough(),qwr=n5("type",[ape,ope,spe]),o5=n5("type",[ape,ope,spe,Twr,jwr]),Vwr=Ae({role:$n(["user","assistant"]),content:dn([o5,Bt(o5)]),_meta:pt(Ae({}).passthrough())}).passthrough(),Uwr=Vu.extend({messages:Bt(Vwr),modelPreferences:Mwr.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(TKe)),toolChoice:pt(Fwr)}),Bwr=xs.extend({method:dt("sampling/createMessage"),params:Uwr}),ppe=rc.extend({model:re(),stopReason:pt($n(["endTurn","stopSequence","maxTokens"]).or(re())),role:$n(["user","assistant"]),content:qwr}),fpe=rc.extend({model:re(),stopReason:pt($n(["endTurn","stopSequence","maxTokens","toolUse"]).or(re())),role:$n(["user","assistant"]),content:dn([o5,Bt(o5)])}),zwr=Ae({type:dt("boolean"),title:re().optional(),description:re().optional(),default:Ji().optional()}),Hwr=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()}),Gwr=Ae({type:$n(["number","integer"]),title:re().optional(),description:re().optional(),minimum:kn().optional(),maximum:kn().optional(),default:kn().optional()}),Kwr=Ae({type:dt("string"),title:re().optional(),description:re().optional(),enum:Bt(re()),default:re().optional()}),Ywr=Ae({type:dt("string"),title:re().optional(),description:re().optional(),oneOf:Bt(Ae({const:re(),title:re()})),default:re().optional()}),Wwr=Ae({type:dt("string"),title:re().optional(),description:re().optional(),enum:Bt(re()),enumNames:Bt(re()).optional(),default:re().optional()}),Xwr=dn([Kwr,Ywr]),Jwr=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()}),Zwr=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()}),Qwr=dn([Jwr,Zwr]),ePr=dn([Wwr,Xwr,Qwr]),tPr=dn([ePr,zwr,Hwr,Gwr]),rPr=Vu.extend({mode:dt("form").optional(),message:re(),requestedSchema:Ae({type:dt("object"),properties:vi(re(),tPr),required:Bt(re()).optional()})}),nPr=Vu.extend({mode:dt("url"),message:re(),elicitationId:re(),url:re().url()}),iPr=dn([rPr,nPr]),aPr=xs.extend({method:dt("elicitation/create"),params:iPr}),oPr=NT.extend({elicitationId:re()}),sPr=nf.extend({method:dt("notifications/elicitation/complete"),params:oPr}),b5=rc.extend({action:$n(["accept","decline","cancel"]),content:a5(e=>e===null?void 0:e,vi(re(),dn([re(),kn(),Ji(),Bt(re())])).optional())}),cPr=Ae({type:dt("ref/resource"),uri:re()});var uPr=Ae({type:dt("ref/prompt"),name:re()}),lPr=Vu.extend({ref:dn([uPr,cPr]),argument:Ae({name:re(),value:re()}),context:Ae({arguments:vi(re(),re()).optional()}).optional()}),pPr=xs.extend({method:dt("completion/complete"),params:lPr});var fPr=rc.extend({completion:np({values:Bt(re()).max(100),total:pt(kn().int()),hasMore:pt(Ji())})}),dPr=Ae({uri:re().startsWith("file://"),name:re().optional(),_meta:vi(re(),li()).optional()}),hPr=xs.extend({method:dt("roots/list")}),dpe=rc.extend({roots:Bt(dPr)}),mPr=nf.extend({method:dt("notifications/roots/list_changed")}),yOi=dn([p5,tpe,pPr,lpe,_wr,vwr,rwr,iwr,swr,pwr,dwr,wk,upe,d5,m5,g5]),vOi=dn([l5,f5,rpe,mPr,Ck]),bOi=dn([u5,ppe,fpe,b5,dpe,h5,y5,eC]),EOi=dn([p5,Bwr,aPr,hPr,d5,m5,g5]),_Oi=dn([l5,f5,kwr,mwr,uwr,Iwr,Cwr,Ck,sPr]),TOi=dn([u5,XCr,fPr,Awr,bwr,nwr,awr,cwr,v5,Dwr,h5,y5,eC]),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===on.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Jle(i.elicitations,r)}return new e(t,r,n)}},Jle=class extends Cr{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(on.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 i0(e){return e==="completed"||e==="failed"||e==="cancelled"}var gPr=Symbol("Let zodToJsonSchema decide on which parser to use");var r1i=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hpe(e){let t=z6(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");let n=bGe(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function mpe(e,t){let r=n0(e,t);if(!r.success)throw r.error;return r.data}var TPr=6e4,E5=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(l5,r=>{this._oncancel(r)}),this.setNotificationHandler(f5,r=>{this._onprogress(r)}),this.setRequestHandler(p5,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(d5,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Cr(on.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(m5,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(on.InvalidParams,`Task not found: ${o}`);if(!i0(s.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(i0(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(g5,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(on.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(gKe,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Cr(on.InvalidParams,`Task not found: ${r.params.taskId}`);if(i0(i.status))throw new Cr(on.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(on.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof Cr?i:new Cr(on.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(on.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),Tk(c)||dKe(c)?this._onresponse(c):epe(c)?this._onrequest(c,u):lKe(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(on.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:on.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 x,S;let A={...O,relatedRequestId:t.id};p&&!A.relatedTask&&(A.relatedTask={taskId:p});let P=(S=(x=A.relatedTask)===null||x===void 0?void 0:x.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:on.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),Tk(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(Tk(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),Tk(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(on.InternalError,String(l))}}return}let u;try{let l=await this.request(t,eC,n);if(l.task)u=l.task.taskId,yield{type:"taskCreated",task:l.task};else throw new Cr(on.InternalError,"Task creation did not return a task");for(;;){let p=await this.getTask({taskId:u},n);if(yield{type:"taskStatus",task:p},i0(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(on.InternalError,`Task ${u} failed`)}:p.status==="cancelled"&&(yield{type:"error",error:new Cr(on.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(on.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 x=this._requestMessageId++,S={...t,jsonrpc:"2.0",id:x};n?.onprogress&&(this._progressHandlers.set(x,n.onprogress),S.params={...t.params,_meta:{...((d=t.params)===null||d===void 0?void 0:d._meta)||{},progressToken:x}}),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(x),this._progressHandlers.delete(x),this._cleanupTimeout(x),(K=this._transport)===null||K===void 0||K.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:x,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(on.RequestTimeout,String(F));l($)};this._responseHandlers.set(x,F=>{var K;if(!(!((K=n?.signal)===null||K===void 0)&&K.aborted)){if(F instanceof Error)return l(F);try{let $=n0(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:TPr,k=()=>A(Cr.fromError(on.RequestTimeout,"Request timed out",{timeout:P}));this._setupTimeout(x,P,n?.maxTotalTimeout,k,(_=n?.resetTimeoutOnProgress)!==null&&_!==void 0?_:!1);let N=c?.taskId;if(N){let F=K=>{let $=this._responseHandlers.get(x);$?$(K):this._onerror(new Error(`Response handler missing for side-channeled request ${x}`))};this._requestResolvers.set(x,F),this._enqueueTaskMessage(N,{type:"request",message:S,timestamp:Date.now()}).catch(K=>{this._cleanupTimeout(x),l(K)})}else this._transport.send(S,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(F=>{this._cleanupTimeout(x),l(F)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},h5,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},y5,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},yKe,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=hpe(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=mpe(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=hpe(t);this._notificationHandlers.set(n,i=>{let a=mpe(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"&&epe(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new Cr(on.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(on.InvalidRequest,"Request cancelled"));return}let u=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(u),c(new Cr(on.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(on.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=Ck.parse({method:"notifications/tasks/status",params:s});await this.notification(c),i0(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(on.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(i0(s.status))throw new Cr(on.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=Ck.parse({method:"notifications/tasks/status",params:c});await this.notification(u),i0(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function xKe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function OKe(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];xKe(o)&&xKe(a)?r[i]={...o,...a}:r[i]=a}return r}var gWe=wt(tz(),1),yWe=wt(mWe(),1);function lkr(){let e=new gWe.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,yWe.default)(e),e}var nz=class{constructor(t){this._ajv=t??lkr()}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 iz=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 vWe(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 bWe(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 az=class extends E5{constructor(t,r){var n,i;super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Pk.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 nz,this.setRequestHandler(tpe,a=>this._oninitialize(a)),this.setNotificationHandler(rpe,()=>{var a;return(a=this.oninitialized)===null||a===void 0?void 0:a.call(this)}),this._capabilities.logging&&this.setRequestHandler(lpe,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=Pk.safeParse(u);return l.success&&this._loggingLevels.set(c,l.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new iz(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=OKe(this._capabilities,t)}setRequestHandler(t,r){var n,i,a;let o=z6(t),s=o?.method;if(!s)throw new Error("Schema is missing a method literal");let c;if(JA(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=n0(wk,p);if(!d.success){let _=d.error instanceof Error?d.error.message:String(d.error);throw new Cr(on.InvalidParams,`Invalid tools/call request: ${_}`)}let{params:h}=d.data,m=await Promise.resolve(r(p,f));if(h.task){let _=n0(eC,m);if(!_.success){let O=_.error instanceof Error?_.error.message:String(_.error);throw new Cr(on.InvalidParams,`Invalid task creation result: ${O}`)}return _.data}let v=n0(v5,m);if(!v.success){let _=v.error instanceof Error?v.error.message:String(v.error);throw new Cr(on.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;bWe((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&&vWe((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:aKe.includes(r)?r:Zle,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"},u5)}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},fpe,r):this.request({method:"sampling/createMessage",params:t},ppe,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},b5,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},b5,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(on.InvalidParams,`Elicitation response content does not match requested schema: ${f.errorMessage}`)}catch(p){throw p instanceof Cr?p:new Cr(on.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},dpe,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 ode=wt(require("node:process"),1);var oz=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),fkr(r)}clear(){this._buffer=void 0}};function fkr(e){return hKe.parse(JSON.parse(e))}function EWe(e){return JSON.stringify(e)+`
|
|
1653
|
-
`}var sz=class{constructor(t=ode.default.stdin,r=ode.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new oz,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=EWe(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var TWe="0.6.4";var yC={name:"@sap-ux/fiori-mcp-server",description:"SAP Fiori - Model Context Protocol (MCP) server",version:TWe,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","inspector-ts":"npx @modelcontextprotocol/inspector ts-node -T src/index.ts --log-level=debug",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.19","@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 SWe=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.")}),BT=dn([re(),Bt(dn([re(),kn()]))]),AWe=Ae({functionalityId:BT.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),description:re()}),xWe=$n(["object","array","string","number","boolean","null","integer","any"]),OWe=Ae({type:dn([xWe,Bt(xWe)]).optional(),description:re().optional(),properties:e5().optional()}).catchall(e5()),CWe=OWe.extend({properties:vi(re(),dn([OWe,Ji()])).optional()});var wWe=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`)")}),PWe=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.")}),DWe=Ae({appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path."),functionalityId:BT.describe("The ID of the functionality to get details for")}),NWe=Ae({functionalityId:BT.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.'),qwi=Ae({query:re().min(2).describe("The search query for fiori elements, annotations, sapui5, fiori tools documentation")});var Uwi=re().describe("Search results as formatted text"),IWe=Ae({applications:Bt(SWe)}),RWe=Ae({applicationPath:re(),functionalities:Bt(AWe)}),LWe=Ae({functionalityId:BT.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),name:re(),description:re(),technicalDescription:re().optional(),parameters:CWe,prerequisites:Bt(re()).optional(),impact:re().optional(),examples:Bt(re()).optional(),pageName:re().optional()}),kWe=Ae({functionalityId:BT,status:re(),message:re(),parameters:li(),appPath:re(),changes:Bt(re()),timestamp:re()});var Oxe=wt(require("node:fs/promises")),Af=wt(require("node:path"));var su=wt(w0()),nTt=wt(zd()),iTt=require("node:path");function cmn(){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"OFF":return;case"ERROR":return su.LogLevel.Error;case"WARN":return su.LogLevel.Warn;case"INFO":return su.LogLevel.Info;case"DEBUG":return su.LogLevel.Debug;case"VERBOSE":return su.LogLevel.Verbose;case"SILLY":return su.LogLevel.Silly;default:break}return su.LogLevel.Error}var rTt=cmn(),yt=new su.ToolsLogger({logLevel:rTt??su.LogLevel.Error,transports:rTt===void 0?[new su.NullTransport]:[new su.FileTransport({filename:(0,iTt.join)(nTt.fioriToolsDirectory,"fiori-mcp-server.log"),maxsize:10*1024*1024,maxFiles:5})],logPrefix:"fiori-mcp"}),WM={info:(e,...t)=>{yt.info(`@sap/ux-specification: ${e}`);for(let r of t)yt.info(typeof r=="number"?r.toString():r)},warning:(e,...t)=>{yt.warn(`@sap/ux-specification: ${e}`);for(let r of t)yt.warn(typeof r=="number"?r.toString():r)},error:(e,...t)=>{yt.error(`@sap/ux-specification: ${e}`);for(let r of t)yt.error(typeof r=="number"?r.toString():r)},reset:()=>{}};async function aTt(){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 Oxe.default.access(n),yt.log("\u2713 Using @sap-ux/fiori-docs-embeddings package"),{dataPath:n,embeddingsPath:Af.default.join(n,"embeddings"),searchPath:Af.default.join(n,"search"),docsPath:Af.default.join(n,"docs"),isExternalPackage:!0,isAvailable:!0}}catch{yt.warn("Could not load @sap-ux/fiori-docs-embeddings package, trying local data...")}let e=Af.default.join(__dirname,"../../data");try{return await Oxe.default.access(e),yt.log("\u2713 Using local data directory"),{dataPath:e,embeddingsPath:Af.default.join(e,"embeddings"),searchPath:Af.default.join(e,"search"),docsPath:Af.default.join(e,"docs"),isExternalPackage:!1,isAvailable:!0}}catch{yt.warn("Local data directory not available either")}let t=Af.default.join(__dirname,"../../data");return yt.warn("\u26A0\uFE0F No embeddings data available - running in limited mode"),{dataPath:t,embeddingsPath:Af.default.join(t,"embeddings"),searchPath:Af.default.join(t,"search"),docsPath:Af.default.join(t,"docs"),isExternalPackage:!1,isAvailable:!1}}var gc=wt(zd()),XM=require("node:path");async function cu(e){try{e=(0,XM.join)(e);try{let t=await(0,gc.createApplicationAccess)(e);return{root:t.project.root,appId:t.getAppId(),applicationAccess:t}}catch(t){yt.warn(`Application was not found by given path. Error: ${t}`);let r=await(0,gc.findProjectRoot)(e),n=await(0,gc.getProject)(r);if(n)return{root:n.root,appId:""}}}catch(t){yt.warn(`Project was not found by given path. Error: ${t}`);return}}var h7=e=>{let t;switch(e){case gc.DirName.View:{t=(0,XM.join)(gc.DirName.Ext,gc.DirName.View);break}case gc.DirName.Fragment:{t=(0,XM.join)(gc.DirName.Ext,gc.DirName.Fragment);break}case gc.DirName.Controller:{t=(0,XM.join)(gc.DirName.Ext,gc.DirName.Controller);break}default:t=e}return t},bm=(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,bm({...o,...s},t,r)}}let n={...e};return n.properties&&(n.properties=Object.fromEntries(Object.entries(n.properties).map(([i,a])=>[i,bm(a,t,r)]))),n.items&&(Array.isArray(n.items)?n.items=n.items.map(i=>bm(i,t,r)):n.items=bm(n.items,t,r)),n.allOf&&(n.allOf=n.allOf.map(i=>bm(i,t,r))),n.anyOf&&(n.anyOf=n.anyOf.map(i=>bm(i,t,r))),n.oneOf&&(n.oneOf=n.oneOf.map(i=>bm(i,t,r))),typeof n.additionalProperties=="object"&&(n.additionalProperties=bm(n.additionalProperties,t,r)),n},oTt=(e,t)=>({type:"object",properties:{[e]:t}}),Ta=e=>{let t=PT(e);return delete t.$schema,t},Em=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof sle?new Error(`Missing required fields in parameters. ${JSON.stringify(r.issues,null,4)}`):new Error("Unknown error. Recheck input parameters.")}};var IIt=require("node:util"),RIt=require("node:child_process"),LIt=wt(jAe());async function _W(e="1.18.5"){let t="@sap/generator-fiori";if((await(0,LIt.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 TW=(0,IIt.promisify)(RIt.exec);var kIt=require("@lancedb/lancedb");var qAe=wt(require("node:fs/promises")),VAe=wt(require("node:path")),xW=class{connection=null;tables=[];tableIndex=null;metadata=null;dataPath;constructor(t){this.dataPath=t||""}async initialize(){try{yt.log("Loading vector database from pre-built embeddings...");let t=await aTt();if(!t.isAvailable)throw new Error("No embeddings data available");this.dataPath=t.embeddingsPath,yt.log(`Using embeddings path: ${this.dataPath} (external: ${t.isExternalPackage})`);let r=VAe.default.join(this.dataPath,"metadata.json"),n=await qAe.default.readFile(r,"utf-8");this.metadata=JSON.parse(n),yt.log("\u2713 Embedding metadata loaded:"),yt.log(` Model: ${this?.metadata?.model}`),yt.log(` Dimensions: ${this?.metadata?.dimensions}`),yt.log(` Total vectors: ${this?.metadata?.totalVectors}`),yt.log(` Created: ${this?.metadata?.createdAt}`),this.connection=await(0,kIt.connect)(this.dataPath);let i=VAe.default.join(this.dataPath,"table_index.json");try{let a=await qAe.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)}yt.log(`\u2713 Loaded ${this.tables.length} split tables`)}catch{yt.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}`)}}yt.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 yt.error(`Semantic search failed: ${i}`),new Error(`Semantic search failed: ${i}`)}}async findSimilarToText(t,r=5){return yt.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 yt.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 yt.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=[],yt.log("Vector database connection closed"))}};var OW=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 UAe(e,t=!1){let{query:r,maxResults:n}=e;try{let i=new xW,a=new OW;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 sz=class{constructor(t=ode.default.stdin,r=ode.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new oz,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=EWe(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var TWe="0.6.5";var yC={name:"@sap-ux/fiori-mcp-server",description:"SAP Fiori - Model Context Protocol (MCP) server",version:TWe,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","inspector-ts":"npx @modelcontextprotocol/inspector ts-node -T src/index.ts --log-level=debug",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.19","@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 SWe=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.")}),BT=dn([re(),Bt(dn([re(),kn()]))]),AWe=Ae({functionalityId:BT.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),description:re()}),xWe=$n(["object","array","string","number","boolean","null","integer","any"]),OWe=Ae({type:dn([xWe,Bt(xWe)]).optional(),description:re().optional(),properties:e5().optional()}).catchall(e5()),CWe=OWe.extend({properties:vi(re(),dn([OWe,Ji()])).optional()});var wWe=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`)")}),PWe=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.")}),DWe=Ae({appPath:re().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path."),functionalityId:BT.describe("The ID of the functionality to get details for")}),NWe=Ae({functionalityId:BT.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.'),qwi=Ae({query:re().min(2).describe("The search query for fiori elements, annotations, sapui5, fiori tools documentation")});var Uwi=re().describe("Search results as formatted text"),IWe=Ae({applications:Bt(SWe)}),RWe=Ae({applicationPath:re(),functionalities:Bt(AWe)}),LWe=Ae({functionalityId:BT.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),name:re(),description:re(),technicalDescription:re().optional(),parameters:CWe,prerequisites:Bt(re()).optional(),impact:re().optional(),examples:Bt(re()).optional(),pageName:re().optional()}),kWe=Ae({functionalityId:BT,status:re(),message:re(),parameters:li(),appPath:re(),changes:Bt(re()),timestamp:re()});var Oxe=wt(require("node:fs/promises")),Af=wt(require("node:path"));var su=wt(w0()),nTt=wt(zd()),iTt=require("node:path");function cmn(){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"OFF":return;case"ERROR":return su.LogLevel.Error;case"WARN":return su.LogLevel.Warn;case"INFO":return su.LogLevel.Info;case"DEBUG":return su.LogLevel.Debug;case"VERBOSE":return su.LogLevel.Verbose;case"SILLY":return su.LogLevel.Silly;default:break}return su.LogLevel.Error}var rTt=cmn(),yt=new su.ToolsLogger({logLevel:rTt??su.LogLevel.Error,transports:rTt===void 0?[new su.NullTransport]:[new su.FileTransport({filename:(0,iTt.join)(nTt.fioriToolsDirectory,"fiori-mcp-server.log"),maxsize:10*1024*1024,maxFiles:5})],logPrefix:"fiori-mcp"}),WM={info:(e,...t)=>{yt.info(`@sap/ux-specification: ${e}`);for(let r of t)yt.info(typeof r=="number"?r.toString():r)},warning:(e,...t)=>{yt.warn(`@sap/ux-specification: ${e}`);for(let r of t)yt.warn(typeof r=="number"?r.toString():r)},error:(e,...t)=>{yt.error(`@sap/ux-specification: ${e}`);for(let r of t)yt.error(typeof r=="number"?r.toString():r)},reset:()=>{}};async function aTt(){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 Oxe.default.access(n),yt.log("\u2713 Using @sap-ux/fiori-docs-embeddings package"),{dataPath:n,embeddingsPath:Af.default.join(n,"embeddings"),searchPath:Af.default.join(n,"search"),docsPath:Af.default.join(n,"docs"),isExternalPackage:!0,isAvailable:!0}}catch{yt.warn("Could not load @sap-ux/fiori-docs-embeddings package, trying local data...")}let e=Af.default.join(__dirname,"../../data");try{return await Oxe.default.access(e),yt.log("\u2713 Using local data directory"),{dataPath:e,embeddingsPath:Af.default.join(e,"embeddings"),searchPath:Af.default.join(e,"search"),docsPath:Af.default.join(e,"docs"),isExternalPackage:!1,isAvailable:!0}}catch{yt.warn("Local data directory not available either")}let t=Af.default.join(__dirname,"../../data");return yt.warn("\u26A0\uFE0F No embeddings data available - running in limited mode"),{dataPath:t,embeddingsPath:Af.default.join(t,"embeddings"),searchPath:Af.default.join(t,"search"),docsPath:Af.default.join(t,"docs"),isExternalPackage:!1,isAvailable:!1}}var gc=wt(zd()),XM=require("node:path");async function cu(e){try{e=(0,XM.join)(e);try{let t=await(0,gc.createApplicationAccess)(e);return{root:t.project.root,appId:t.getAppId(),applicationAccess:t}}catch(t){yt.warn(`Application was not found by given path. Error: ${t}`);let r=await(0,gc.findProjectRoot)(e),n=await(0,gc.getProject)(r);if(n)return{root:n.root,appId:""}}}catch(t){yt.warn(`Project was not found by given path. Error: ${t}`);return}}var h7=e=>{let t;switch(e){case gc.DirName.View:{t=(0,XM.join)(gc.DirName.Ext,gc.DirName.View);break}case gc.DirName.Fragment:{t=(0,XM.join)(gc.DirName.Ext,gc.DirName.Fragment);break}case gc.DirName.Controller:{t=(0,XM.join)(gc.DirName.Ext,gc.DirName.Controller);break}default:t=e}return t},bm=(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,bm({...o,...s},t,r)}}let n={...e};return n.properties&&(n.properties=Object.fromEntries(Object.entries(n.properties).map(([i,a])=>[i,bm(a,t,r)]))),n.items&&(Array.isArray(n.items)?n.items=n.items.map(i=>bm(i,t,r)):n.items=bm(n.items,t,r)),n.allOf&&(n.allOf=n.allOf.map(i=>bm(i,t,r))),n.anyOf&&(n.anyOf=n.anyOf.map(i=>bm(i,t,r))),n.oneOf&&(n.oneOf=n.oneOf.map(i=>bm(i,t,r))),typeof n.additionalProperties=="object"&&(n.additionalProperties=bm(n.additionalProperties,t,r)),n},oTt=(e,t)=>({type:"object",properties:{[e]:t}}),Ta=e=>{let t=PT(e);return delete t.$schema,t},Em=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof sle?new Error(`Missing required fields in parameters. ${JSON.stringify(r.issues,null,4)}`):new Error("Unknown error. Recheck input parameters.")}};var IIt=require("node:util"),RIt=require("node:child_process"),LIt=wt(jAe());async function _W(e="1.18.5"){let t="@sap/generator-fiori";if((await(0,LIt.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 TW=(0,IIt.promisify)(RIt.exec);var kIt=require("@lancedb/lancedb");var qAe=wt(require("node:fs/promises")),VAe=wt(require("node:path")),xW=class{connection=null;tables=[];tableIndex=null;metadata=null;dataPath;constructor(t){this.dataPath=t||""}async initialize(){try{yt.log("Loading vector database from pre-built embeddings...");let t=await aTt();if(!t.isAvailable)throw new Error("No embeddings data available");this.dataPath=t.embeddingsPath,yt.log(`Using embeddings path: ${this.dataPath} (external: ${t.isExternalPackage})`);let r=VAe.default.join(this.dataPath,"metadata.json"),n=await qAe.default.readFile(r,"utf-8");this.metadata=JSON.parse(n),yt.log("\u2713 Embedding metadata loaded:"),yt.log(` Model: ${this?.metadata?.model}`),yt.log(` Dimensions: ${this?.metadata?.dimensions}`),yt.log(` Total vectors: ${this?.metadata?.totalVectors}`),yt.log(` Created: ${this?.metadata?.createdAt}`),this.connection=await(0,kIt.connect)(this.dataPath);let i=VAe.default.join(this.dataPath,"table_index.json");try{let a=await qAe.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)}yt.log(`\u2713 Loaded ${this.tables.length} split tables`)}catch{yt.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}`)}}yt.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 yt.error(`Semantic search failed: ${i}`),new Error(`Semantic search failed: ${i}`)}}async findSimilarToText(t,r=5){return yt.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 yt.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 yt.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=[],yt.log("Vector database connection closed"))}};var OW=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 UAe(e,t=!1){let{query:r,maxResults:n}=e;try{let i=new xW,a=new OW;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.6.
|
|
4
|
+
"version": "0.6.5",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"SAP Fiori tools",
|
|
7
7
|
"SAP Fiori elements",
|
|
@@ -48,12 +48,12 @@
|
|
|
48
48
|
"@langchain/core": "1.1.1",
|
|
49
49
|
"@sap-ux/axios-extension": "1.25.6",
|
|
50
50
|
"@sap-ux/project-access": "1.33.1",
|
|
51
|
-
"@sap-ux/fiori-annotation-api": "0.8.
|
|
52
|
-
"@sap-ux/fiori-docs-embeddings": "0.4.
|
|
51
|
+
"@sap-ux/fiori-annotation-api": "0.8.5",
|
|
52
|
+
"@sap-ux/fiori-docs-embeddings": "0.4.9",
|
|
53
53
|
"@sap-ux/i18n": "0.3.7",
|
|
54
54
|
"@sap-ux/logger": "0.8.0",
|
|
55
55
|
"@sap-ux/odata-annotation-core-types": "0.5.2",
|
|
56
|
-
"@sap-ux/odata-entity-model": "0.3.
|
|
56
|
+
"@sap-ux/odata-entity-model": "0.3.4",
|
|
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",
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"@lancedb/lancedb": "0.22.0",
|
|
66
66
|
"mem-fs": "2.1.0",
|
|
67
67
|
"mem-fs-editor": "9.4.0",
|
|
68
|
-
"@sap-ux/fiori-docs-embeddings": "0.4.
|
|
68
|
+
"@sap-ux/fiori-docs-embeddings": "0.4.9",
|
|
69
69
|
"@sap-ux/store": "1.4.2"
|
|
70
70
|
},
|
|
71
71
|
"engines": {
|