@sap-ux/fiori-mcp-server 0.6.9 → 0.6.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,6 +8,9 @@ The server helps AI models create or modify SAP Fiori applications based on prom
8
8
 
9
9
  - _Please add a SAP Fiori elements list report app to my CAP project_
10
10
  - _Generate a new CAP project and SAP Fiori app based on my_picture.png_
11
+ - _Generate a new SAP Fiori elements list report app for odata service `https://hostname:port/sap/opu/odata4/sap/my_v4_service?sap-client=000`_.
12
+
13
+ ℹ️This prompt requires a saved SAP system connection by using the [Connection Manager for SAP Systems](https://marketplace.visualstudio.com/items?itemName=SAPOSS.sap-ux-sap-systems-ext) extension.
11
14
  - _Add the FCL to the SAP Fiori elements app_
12
15
  - _Enable initial load for the fiori app_
13
16
 
@@ -91,10 +94,11 @@ Gets the list of supported functionalities to create a new or modify an existing
91
94
 
92
95
  The main functionalities are:
93
96
 
94
- - Generating a Fiori elements app within an [SAP Cloud Application Programming Model (CAP)](https://cap.cloud.sap/) project
97
+ - Generating an SAP Fiori elements app within an [SAP Cloud Application Programming Model (CAP)](https://cap.cloud.sap/) project
98
+ - Generating an SAP Fiori elements app for an existing OData service, for example, an [ABAP RESTful Application Programming Model](https://pages.community.sap.com/topics/abap/rap)-based OData service
95
99
  - Adding and deleting pages from an app
96
100
  - Adding and modifying controller extensions
97
- - Modifying `manifest.json` properties depending on the app (e.g. adding Flexible Column Layout, enabling initial load)
101
+ - Modifying `manifest.json` properties depending on the app, for example, adding a layout based on the flexibility of the programming model or enabling initial load
98
102
 
99
103
  #### `get_functionality_details` (Step 2 of 3)
100
104
  Gets the required parameters and detailed information for a specific functionality to create a new or modify an existing SAP Fiori application.
@@ -102,6 +106,28 @@ Gets the required parameters and detailed information for a specific functionali
102
106
  #### `execute_functionality` (Step 3 of 3)
103
107
  Executes a specific functionality to create a new or modify an existing SAP Fiori application with provided parameters.
104
108
 
109
+ ## [Logging](#logging)
110
+
111
+ By default, logging is enabled at the `error` level. To adjust the log level or disable logging completely, you can use the `env` property in your configuration.
112
+
113
+ ```json
114
+ {
115
+ "mcpServers": {
116
+ "fiori-mcp": {
117
+ "type": "stdio",
118
+ "timeout": 600,
119
+ "command": "npx",
120
+ "args": ["--yes","@sap-ux/fiori-mcp-server@latest", "fiori-mcp"],
121
+ "env": {
122
+ "LOG_LEVEL": "debug"
123
+ }
124
+ }
125
+ }
126
+ }
127
+ ```
128
+ The following log levels are supported: `off`, `error`, `warn`, `info`, `debug`, and `verbose`.
129
+
130
+ The logs are stored in the file system at `~/.fioritools/fiori-mcp-server.log`
105
131
 
106
132
  ## [Telemetry](#telemetry)
107
133
 
package/dist/index.js CHANGED
@@ -1607,7 +1607,7 @@ ${n.message}`:h,E=[v,t,e].filter(Boolean).join(`
1607
1607
 
1608
1608
  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 f=n.external.registry.get(l[0])?.id;if(t!==l[0]&&f){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 d=this.seen.get(l),f=d.def??d.schema,h={...f};if(d.ref===null)return;let g=d.ref;if(d.ref=null,g){s(g,p);let v=this.seen.get(g).schema;v.$ref&&(p.target==="draft-7"||p.target==="draft-4"||p.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(v)):(Object.assign(f,v),Object.assign(f,h))}d.isParent||this.override({zodSchema:l,jsonSchema:f,path:d.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 q0(e,t){if(e instanceof Ix){let n=new GR(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 GR(t);return r.process(e),r.emit(e,t)}function Uc(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 Uc(n.element,r);if(n.type==="set")return Uc(n.valueType,r);if(n.type==="lazy")return Uc(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 Uc(n.innerType,r);if(n.type==="intersection")return Uc(n.left,r)||Uc(n.right,r);if(n.type==="record"||n.type==="map")return Uc(n.keyType,r)||Uc(n.valueType,r);if(n.type==="pipe")return Uc(n.in,r)||Uc(n.out,r);if(n.type==="object"){for(let i in n.shape)if(Uc(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(Uc(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(Uc(i,r))return!0;return!!(n.rest&&Uc(n.rest,r))}return!1}var PUe={};function Kx(e){return!!e._zod}function _b(e,t){return Kx(e)?k0(e,t):e.safeParse(t)}function L4(e){if(!e)return;let t;if(Kx(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function IUe(e){if(Kx(e)){let a=e._zod?.def;if(a){if(a.value!==void 0)return a.value;if(Array.isArray(a.values)&&a.values.length>0)return a.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}var U0={};Pi(U0,{$brand:()=>sR,$input:()=>z3,$output:()=>B3,NEVER:()=>dB,TimePrecision:()=>Y3,ZodAny:()=>jUe,ZodArray:()=>BUe,ZodBase64:()=>Loe,ZodBase64URL:()=>koe,ZodBigInt:()=>ZR,ZodBigIntFormat:()=>Foe,ZodBoolean:()=>JR,ZodCIDRv4:()=>Ioe,ZodCIDRv6:()=>Roe,ZodCUID:()=>Aoe,ZodCUID2:()=>xoe,ZodCatch:()=>oBe,ZodCodec:()=>Goe,ZodCustom:()=>K4,ZodCustomStringFormat:()=>WR,ZodDate:()=>z4,ZodDefault:()=>eBe,ZodDiscriminatedUnion:()=>zUe,ZodE164:()=>$oe,ZodEmail:()=>Eoe,ZodEmoji:()=>Ooe,ZodEnum:()=>KR,ZodError:()=>ooe,ZodFile:()=>JUe,ZodFirstPartyTypeKind:()=>Yoe,ZodFunction:()=>mBe,ZodGUID:()=>j4,ZodIPv4:()=>woe,ZodIPv6:()=>Noe,ZodISODate:()=>$4,ZodISODateTime:()=>k4,ZodISODuration:()=>F4,ZodISOTime:()=>M4,ZodIntersection:()=>HUe,ZodIssueCode:()=>zfr,ZodJWT:()=>Moe,ZodKSUID:()=>Poe,ZodLazy:()=>fBe,ZodLiteral:()=>XUe,ZodMAC:()=>kUe,ZodMap:()=>YUe,ZodNaN:()=>cBe,ZodNanoID:()=>Soe,ZodNever:()=>qUe,ZodNonOptional:()=>zoe,ZodNull:()=>FUe,ZodNullable:()=>QUe,ZodNumber:()=>XR,ZodNumberFormat:()=>Wx,ZodObject:()=>H4,ZodOptional:()=>Boe,ZodPipe:()=>Hoe,ZodPrefault:()=>rBe,ZodPromise:()=>hBe,ZodReadonly:()=>uBe,ZodRealError:()=>Nu,ZodRecord:()=>qoe,ZodSet:()=>WUe,ZodString:()=>YR,ZodStringFormat:()=>li,ZodSuccess:()=>aBe,ZodSymbol:()=>$Ue,ZodTemplateLiteral:()=>pBe,ZodTransform:()=>ZUe,ZodTuple:()=>GUe,ZodType:()=>Sr,ZodULID:()=>Coe,ZodURL:()=>U4,ZodUUID:()=>jg,ZodUndefined:()=>MUe,ZodUnion:()=>Voe,ZodUnknown:()=>VUe,ZodVoid:()=>UUe,ZodXID:()=>Doe,_ZodString:()=>_oe,_default:()=>tBe,_function:()=>Mfr,any:()=>B4,array:()=>Ut,base64:()=>afr,base64url:()=>ofr,bigint:()=>yfr,boolean:()=>wi,catch:()=>sBe,check:()=>Ffr,cidrv4:()=>nfr,cidrv6:()=>ifr,clone:()=>hs,codec:()=>Lfr,coerce:()=>Woe,config:()=>fa,core:()=>Bl,cuid:()=>Wpr,cuid2:()=>Xpr,custom:()=>Koe,date:()=>Ofr,decode:()=>foe,decodeAsync:()=>hoe,describe:()=>jfr,discriminatedUnion:()=>G4,e164:()=>sfr,email:()=>Vpr,emoji:()=>Kpr,encode:()=>poe,encodeAsync:()=>doe,endsWith:()=>qx,enum:()=>ri,file:()=>wfr,flattenError:()=>bx,float32:()=>dfr,float64:()=>hfr,formatError:()=>_x,function:()=>Mfr,getErrorMap:()=>Gfr,globalRegistry:()=>Ys,gt:()=>Eh,gte:()=>Ws,guid:()=>qpr,hash:()=>ffr,hex:()=>pfr,hostname:()=>lfr,httpUrl:()=>Gpr,includes:()=>jx,instanceof:()=>qfr,int:()=>boe,int32:()=>mfr,int64:()=>vfr,intersection:()=>eL,ipv4:()=>efr,ipv6:()=>rfr,iso:()=>Yx,json:()=>Bfr,jwt:()=>cfr,keyof:()=>Sfr,ksuid:()=>Qpr,lazy:()=>dBe,length:()=>j0,literal:()=>ft,locales:()=>Nx,looseObject:()=>Xs,lowercase:()=>Mx,lt:()=>_h,lte:()=>wu,mac:()=>tfr,map:()=>Cfr,maxLength:()=>F0,maxSize:()=>M0,meta:()=>Vfr,mime:()=>Ux,minLength:()=>Fg,minSize:()=>bb,multipleOf:()=>vb,nan:()=>Rfr,nanoid:()=>Ypr,nativeEnum:()=>Pfr,negative:()=>O4,never:()=>joe,nonnegative:()=>A4,nonoptional:()=>iBe,nonpositive:()=>S4,normalize:()=>Bx,null:()=>QR,nullable:()=>V4,nullish:()=>Nfr,number:()=>gn,object:()=>we,optional:()=>kn,overwrite:()=>ld,parse:()=>soe,parseAsync:()=>coe,partialRecord:()=>xfr,pipe:()=>q4,positive:()=>T4,prefault:()=>nBe,preprocess:()=>Y4,prettifyError:()=>yB,promise:()=>$fr,property:()=>x4,readonly:()=>lBe,record:()=>$n,refine:()=>gBe,regex:()=>$x,regexes:()=>Pu,registry:()=>SR,safeDecode:()=>goe,safeDecodeAsync:()=>voe,safeEncode:()=>moe,safeEncodeAsync:()=>yoe,safeParse:()=>uoe,safeParseAsync:()=>loe,set:()=>Dfr,setErrorMap:()=>Hfr,size:()=>kx,slugify:()=>HR,startsWith:()=>Vx,strictObject:()=>Afr,string:()=>ee,stringFormat:()=>ufr,stringbool:()=>Ufr,success:()=>Ifr,superRefine:()=>yBe,symbol:()=>_fr,templateLiteral:()=>kfr,toJSONSchema:()=>q0,toLowerCase:()=>Hx,toUpperCase:()=>Gx,transform:()=>Uoe,treeifyError:()=>gB,trim:()=>zx,tuple:()=>KUe,uint32:()=>gfr,uint64:()=>bfr,ulid:()=>Jpr,undefined:()=>Efr,union:()=>nn,unknown:()=>xn,uppercase:()=>Fx,url:()=>Toe,util:()=>Le,uuid:()=>Upr,uuidv4:()=>Bpr,uuidv6:()=>zpr,uuidv7:()=>Hpr,void:()=>Tfr,xid:()=>Zpr});var Yx={};Pi(Yx,{ZodISODate:()=>$4,ZodISODateTime:()=>k4,ZodISODuration:()=>F4,ZodISOTime:()=>M4,date:()=>noe,datetime:()=>roe,duration:()=>aoe,time:()=>ioe});var k4=ne("ZodISODateTime",(e,t)=>{HB.init(e,t),li.init(e,t)});function roe(e){return W3(k4,e)}var $4=ne("ZodISODate",(e,t)=>{GB.init(e,t),li.init(e,t)});function noe(e){return X3($4,e)}var M4=ne("ZodISOTime",(e,t)=>{KB.init(e,t),li.init(e,t)});function ioe(e){return J3(M4,e)}var F4=ne("ZodISODuration",(e,t)=>{YB.init(e,t),li.init(e,t)});function aoe(e){return Z3(F4,e)}var LUe=(e,t)=>{hR.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>_x(e,r)},flatten:{value:r=>bx(e,r)},addIssue:{value:r=>{e.issues.push(r),e.message=JSON.stringify(e.issues,gx,2)}},addIssues:{value:r=>{e.issues.push(...r),e.message=JSON.stringify(e.issues,gx,2)}},isEmpty:{get(){return e.issues.length===0}}})},ooe=ne("ZodError",LUe),Nu=ne("ZodError",LUe,{Parent:Error});var soe=Ex(Nu),coe=Ox(Nu),uoe=Ax(Nu),loe=xx(Nu),poe=vB(Nu),foe=bB(Nu),doe=_B(Nu),hoe=EB(Nu),moe=TB(Nu),goe=OB(Nu),yoe=SB(Nu),voe=AB(Nu);var Sr=ne("ZodType",(e,t)=>(Yt.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)=>hs(e,r,n),e.brand=()=>e,e.register=(r,n)=>(r.add(e,n),e),e.parse=(r,n)=>soe(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>uoe(e,r,n),e.parseAsync=async(r,n)=>coe(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>loe(e,r,n),e.spa=e.safeParseAsync,e.encode=(r,n)=>poe(e,r,n),e.decode=(r,n)=>foe(e,r,n),e.encodeAsync=async(r,n)=>doe(e,r,n),e.decodeAsync=async(r,n)=>hoe(e,r,n),e.safeEncode=(r,n)=>moe(e,r,n),e.safeDecode=(r,n)=>goe(e,r,n),e.safeEncodeAsync=async(r,n)=>yoe(e,r,n),e.safeDecodeAsync=async(r,n)=>voe(e,r,n),e.refine=(r,n)=>e.check(gBe(r,n)),e.superRefine=r=>e.check(yBe(r)),e.overwrite=r=>e.check(ld(r)),e.optional=()=>kn(e),e.nullable=()=>V4(e),e.nullish=()=>kn(V4(e)),e.nonoptional=r=>iBe(e,r),e.array=()=>Ut(e),e.or=r=>nn([e,r]),e.and=r=>eL(e,r),e.transform=r=>q4(e,Uoe(r)),e.default=r=>tBe(e,r),e.prefault=r=>nBe(e,r),e.catch=r=>sBe(e,r),e.pipe=r=>q4(e,r),e.readonly=()=>lBe(e),e.describe=r=>{let n=e.clone();return Ys.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Ys.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Ys.get(e);let n=e.clone();return Ys.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),_oe=ne("_ZodString",(e,t)=>{yb.init(e,t),Sr.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($x(...n)),e.includes=(...n)=>e.check(jx(...n)),e.startsWith=(...n)=>e.check(Vx(...n)),e.endsWith=(...n)=>e.check(qx(...n)),e.min=(...n)=>e.check(Fg(...n)),e.max=(...n)=>e.check(F0(...n)),e.length=(...n)=>e.check(j0(...n)),e.nonempty=(...n)=>e.check(Fg(1,...n)),e.lowercase=n=>e.check(Mx(n)),e.uppercase=n=>e.check(Fx(n)),e.trim=()=>e.check(zx()),e.normalize=(...n)=>e.check(Bx(...n)),e.toLowerCase=()=>e.check(Hx()),e.toUpperCase=()=>e.check(Gx()),e.slugify=()=>e.check(HR())}),YR=ne("ZodString",(e,t)=>{yb.init(e,t),_oe.init(e,t),e.email=r=>e.check(AR(Eoe,r)),e.url=r=>e.check(Lx(U4,r)),e.jwt=r=>e.check(zR(Moe,r)),e.emoji=r=>e.check(wR(Ooe,r)),e.guid=r=>e.check(Rx(j4,r)),e.uuid=r=>e.check(xR(jg,r)),e.uuidv4=r=>e.check(CR(jg,r)),e.uuidv6=r=>e.check(DR(jg,r)),e.uuidv7=r=>e.check(PR(jg,r)),e.nanoid=r=>e.check(NR(Soe,r)),e.guid=r=>e.check(Rx(j4,r)),e.cuid=r=>e.check(IR(Aoe,r)),e.cuid2=r=>e.check(RR(xoe,r)),e.ulid=r=>e.check(LR(Coe,r)),e.base64=r=>e.check(qR(Loe,r)),e.base64url=r=>e.check(UR(koe,r)),e.xid=r=>e.check(kR(Doe,r)),e.ksuid=r=>e.check($R(Poe,r)),e.ipv4=r=>e.check(MR(woe,r)),e.ipv6=r=>e.check(FR(Noe,r)),e.cidrv4=r=>e.check(jR(Ioe,r)),e.cidrv6=r=>e.check(VR(Roe,r)),e.e164=r=>e.check(BR($oe,r)),e.datetime=r=>e.check(roe(r)),e.date=r=>e.check(noe(r)),e.time=r=>e.check(ioe(r)),e.duration=r=>e.check(aoe(r))});function ee(e){return H3(YR,e)}var li=ne("ZodStringFormat",(e,t)=>{Kn.init(e,t),_oe.init(e,t)}),Eoe=ne("ZodEmail",(e,t)=>{$B.init(e,t),li.init(e,t)});function Vpr(e){return AR(Eoe,e)}var j4=ne("ZodGUID",(e,t)=>{LB.init(e,t),li.init(e,t)});function qpr(e){return Rx(j4,e)}var jg=ne("ZodUUID",(e,t)=>{kB.init(e,t),li.init(e,t)});function Upr(e){return xR(jg,e)}function Bpr(e){return CR(jg,e)}function zpr(e){return DR(jg,e)}function Hpr(e){return PR(jg,e)}var U4=ne("ZodURL",(e,t)=>{MB.init(e,t),li.init(e,t)});function Toe(e){return Lx(U4,e)}function Gpr(e){return Lx(U4,{protocol:/^https?$/,hostname:Pu.domain,...Le.normalizeParams(e)})}var Ooe=ne("ZodEmoji",(e,t)=>{FB.init(e,t),li.init(e,t)});function Kpr(e){return wR(Ooe,e)}var Soe=ne("ZodNanoID",(e,t)=>{jB.init(e,t),li.init(e,t)});function Ypr(e){return NR(Soe,e)}var Aoe=ne("ZodCUID",(e,t)=>{VB.init(e,t),li.init(e,t)});function Wpr(e){return IR(Aoe,e)}var xoe=ne("ZodCUID2",(e,t)=>{qB.init(e,t),li.init(e,t)});function Xpr(e){return RR(xoe,e)}var Coe=ne("ZodULID",(e,t)=>{UB.init(e,t),li.init(e,t)});function Jpr(e){return LR(Coe,e)}var Doe=ne("ZodXID",(e,t)=>{BB.init(e,t),li.init(e,t)});function Zpr(e){return kR(Doe,e)}var Poe=ne("ZodKSUID",(e,t)=>{zB.init(e,t),li.init(e,t)});function Qpr(e){return $R(Poe,e)}var woe=ne("ZodIPv4",(e,t)=>{WB.init(e,t),li.init(e,t)});function efr(e){return MR(woe,e)}var kUe=ne("ZodMAC",(e,t)=>{JB.init(e,t),li.init(e,t)});function tfr(e){return K3(kUe,e)}var Noe=ne("ZodIPv6",(e,t)=>{XB.init(e,t),li.init(e,t)});function rfr(e){return FR(Noe,e)}var Ioe=ne("ZodCIDRv4",(e,t)=>{ZB.init(e,t),li.init(e,t)});function nfr(e){return jR(Ioe,e)}var Roe=ne("ZodCIDRv6",(e,t)=>{QB.init(e,t),li.init(e,t)});function ifr(e){return VR(Roe,e)}var Loe=ne("ZodBase64",(e,t)=>{e3.init(e,t),li.init(e,t)});function afr(e){return qR(Loe,e)}var koe=ne("ZodBase64URL",(e,t)=>{t3.init(e,t),li.init(e,t)});function ofr(e){return UR(koe,e)}var $oe=ne("ZodE164",(e,t)=>{r3.init(e,t),li.init(e,t)});function sfr(e){return BR($oe,e)}var Moe=ne("ZodJWT",(e,t)=>{n3.init(e,t),li.init(e,t)});function cfr(e){return zR(Moe,e)}var WR=ne("ZodCustomStringFormat",(e,t)=>{i3.init(e,t),li.init(e,t)});function ufr(e,t,r={}){return V0(WR,e,t,r)}function lfr(e){return V0(WR,"hostname",Pu.hostname,e)}function pfr(e){return V0(WR,"hex",Pu.hex,e)}function ffr(e,t){let r=t?.enc??"hex",n=`${e}_${r}`,i=Pu[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return V0(WR,n,i,t)}var XR=ne("ZodNumber",(e,t)=>{vR.init(e,t),Sr.init(e,t),e.gt=(n,i)=>e.check(Eh(n,i)),e.gte=(n,i)=>e.check(Ws(n,i)),e.min=(n,i)=>e.check(Ws(n,i)),e.lt=(n,i)=>e.check(_h(n,i)),e.lte=(n,i)=>e.check(wu(n,i)),e.max=(n,i)=>e.check(wu(n,i)),e.int=n=>e.check(boe(n)),e.safe=n=>e.check(boe(n)),e.positive=n=>e.check(Eh(0,n)),e.nonnegative=n=>e.check(Ws(0,n)),e.negative=n=>e.check(_h(0,n)),e.nonpositive=n=>e.check(wu(0,n)),e.multipleOf=(n,i)=>e.check(vb(n,i)),e.step=(n,i)=>e.check(vb(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 gn(e){return Q3(XR,e)}var Wx=ne("ZodNumberFormat",(e,t)=>{a3.init(e,t),XR.init(e,t)});function boe(e){return t4(Wx,e)}function dfr(e){return r4(Wx,e)}function hfr(e){return n4(Wx,e)}function mfr(e){return i4(Wx,e)}function gfr(e){return a4(Wx,e)}var JR=ne("ZodBoolean",(e,t)=>{Px.init(e,t),Sr.init(e,t)});function wi(e){return o4(JR,e)}var ZR=ne("ZodBigInt",(e,t)=>{bR.init(e,t),Sr.init(e,t),e.gte=(n,i)=>e.check(Ws(n,i)),e.min=(n,i)=>e.check(Ws(n,i)),e.gt=(n,i)=>e.check(Eh(n,i)),e.gte=(n,i)=>e.check(Ws(n,i)),e.min=(n,i)=>e.check(Ws(n,i)),e.lt=(n,i)=>e.check(_h(n,i)),e.lte=(n,i)=>e.check(wu(n,i)),e.max=(n,i)=>e.check(wu(n,i)),e.positive=n=>e.check(Eh(BigInt(0),n)),e.negative=n=>e.check(_h(BigInt(0),n)),e.nonpositive=n=>e.check(wu(BigInt(0),n)),e.nonnegative=n=>e.check(Ws(BigInt(0),n)),e.multipleOf=(n,i)=>e.check(vb(n,i));let r=e._zod.bag;e.minValue=r.minimum??null,e.maxValue=r.maximum??null,e.format=r.format??null});function yfr(e){return c4(ZR,e)}var Foe=ne("ZodBigIntFormat",(e,t)=>{o3.init(e,t),ZR.init(e,t)});function vfr(e){return l4(Foe,e)}function bfr(e){return p4(Foe,e)}var $Ue=ne("ZodSymbol",(e,t)=>{s3.init(e,t),Sr.init(e,t)});function _fr(e){return f4($Ue,e)}var MUe=ne("ZodUndefined",(e,t)=>{c3.init(e,t),Sr.init(e,t)});function Efr(e){return d4(MUe,e)}var FUe=ne("ZodNull",(e,t)=>{u3.init(e,t),Sr.init(e,t)});function QR(e){return h4(FUe,e)}var jUe=ne("ZodAny",(e,t)=>{l3.init(e,t),Sr.init(e,t)});function B4(){return m4(jUe)}var VUe=ne("ZodUnknown",(e,t)=>{p3.init(e,t),Sr.init(e,t)});function xn(){return g4(VUe)}var qUe=ne("ZodNever",(e,t)=>{f3.init(e,t),Sr.init(e,t)});function joe(e){return y4(qUe,e)}var UUe=ne("ZodVoid",(e,t)=>{d3.init(e,t),Sr.init(e,t)});function Tfr(e){return v4(UUe,e)}var z4=ne("ZodDate",(e,t)=>{h3.init(e,t),Sr.init(e,t),e.min=(n,i)=>e.check(Ws(n,i)),e.max=(n,i)=>e.check(wu(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 Ofr(e){return b4(z4,e)}var BUe=ne("ZodArray",(e,t)=>{m3.init(e,t),Sr.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Fg(r,n)),e.nonempty=r=>e.check(Fg(1,r)),e.max=(r,n)=>e.check(F0(r,n)),e.length=(r,n)=>e.check(j0(r,n)),e.unwrap=()=>e.element});function Ut(e,t){return toe(BUe,e,t)}function Sfr(e){let t=e._zod.def.shape;return ri(Object.keys(t))}var H4=ne("ZodObject",(e,t)=>{eoe.init(e,t),Sr.init(e,t),Le.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>ri(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:xn()}),e.loose=()=>e.clone({...e._zod.def,catchall:xn()}),e.strict=()=>e.clone({...e._zod.def,catchall:joe()}),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(Boe,e,r[0]),e.required=(...r)=>Le.required(zoe,e,r[0])});function we(e,t){let r={type:"object",shape:e??{},...Le.normalizeParams(t)};return new H4(r)}function Afr(e,t){return new H4({type:"object",shape:e,catchall:joe(),...Le.normalizeParams(t)})}function Xs(e,t){return new H4({type:"object",shape:e,catchall:xn(),...Le.normalizeParams(t)})}var Voe=ne("ZodUnion",(e,t)=>{_R.init(e,t),Sr.init(e,t),e.options=t.options});function nn(e,t){return new Voe({type:"union",options:e,...Le.normalizeParams(t)})}var zUe=ne("ZodDiscriminatedUnion",(e,t)=>{Voe.init(e,t),g3.init(e,t)});function G4(e,t,r){return new zUe({type:"union",options:t,discriminator:e,...Le.normalizeParams(r)})}var HUe=ne("ZodIntersection",(e,t)=>{y3.init(e,t),Sr.init(e,t)});function eL(e,t){return new HUe({type:"intersection",left:e,right:t})}var GUe=ne("ZodTuple",(e,t)=>{ER.init(e,t),Sr.init(e,t),e.rest=r=>e.clone({...e._zod.def,rest:r})});function KUe(e,t,r){let n=t instanceof Yt,i=n?r:t,a=n?t:null;return new GUe({type:"tuple",items:e,rest:a,...Le.normalizeParams(i)})}var qoe=ne("ZodRecord",(e,t)=>{v3.init(e,t),Sr.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function $n(e,t,r){return new qoe({type:"record",keyType:e,valueType:t,...Le.normalizeParams(r)})}function xfr(e,t,r){let n=hs(e);return n._zod.values=void 0,new qoe({type:"record",keyType:n,valueType:t,...Le.normalizeParams(r)})}var YUe=ne("ZodMap",(e,t)=>{b3.init(e,t),Sr.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Cfr(e,t,r){return new YUe({type:"map",keyType:e,valueType:t,...Le.normalizeParams(r)})}var WUe=ne("ZodSet",(e,t)=>{_3.init(e,t),Sr.init(e,t),e.min=(...r)=>e.check(bb(...r)),e.nonempty=r=>e.check(bb(1,r)),e.max=(...r)=>e.check(M0(...r)),e.size=(...r)=>e.check(kx(...r))});function Dfr(e,t){return new WUe({type:"set",valueType:e,...Le.normalizeParams(t)})}var KR=ne("ZodEnum",(e,t)=>{E3.init(e,t),Sr.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 KR({...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 KR({...t,checks:[],...Le.normalizeParams(i),entries:a})}});function ri(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new KR({type:"enum",entries:r,...Le.normalizeParams(t)})}function Pfr(e,t){return new KR({type:"enum",entries:e,...Le.normalizeParams(t)})}var XUe=ne("ZodLiteral",(e,t)=>{T3.init(e,t),Sr.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 ft(e,t){return new XUe({type:"literal",values:Array.isArray(e)?e:[e],...Le.normalizeParams(t)})}var JUe=ne("ZodFile",(e,t)=>{O3.init(e,t),Sr.init(e,t),e.min=(r,n)=>e.check(bb(r,n)),e.max=(r,n)=>e.check(M0(r,n)),e.mime=(r,n)=>e.check(Ux(Array.isArray(r)?r:[r],n))});function wfr(e){return C4(JUe,e)}var ZUe=ne("ZodTransform",(e,t)=>{S3.init(e,t),Sr.init(e,t),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new pb(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 Uoe(e){return new ZUe({type:"transform",transform:e})}var Boe=ne("ZodOptional",(e,t)=>{A3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function kn(e){return new Boe({type:"optional",innerType:e})}var QUe=ne("ZodNullable",(e,t)=>{x3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function V4(e){return new QUe({type:"nullable",innerType:e})}function Nfr(e){return kn(V4(e))}var eBe=ne("ZodDefault",(e,t)=>{C3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function tBe(e,t){return new eBe({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Le.shallowClone(t)}})}var rBe=ne("ZodPrefault",(e,t)=>{D3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nBe(e,t){return new rBe({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Le.shallowClone(t)}})}var zoe=ne("ZodNonOptional",(e,t)=>{P3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function iBe(e,t){return new zoe({type:"nonoptional",innerType:e,...Le.normalizeParams(t)})}var aBe=ne("ZodSuccess",(e,t)=>{w3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ifr(e){return new aBe({type:"success",innerType:e})}var oBe=ne("ZodCatch",(e,t)=>{N3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sBe(e,t){return new oBe({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var cBe=ne("ZodNaN",(e,t)=>{I3.init(e,t),Sr.init(e,t)});function Rfr(e){return E4(cBe,e)}var Hoe=ne("ZodPipe",(e,t)=>{R3.init(e,t),Sr.init(e,t),e.in=t.in,e.out=t.out});function q4(e,t){return new Hoe({type:"pipe",in:e,out:t})}var Goe=ne("ZodCodec",(e,t)=>{Hoe.init(e,t),wx.init(e,t)});function Lfr(e,t,r){return new Goe({type:"pipe",in:e,out:t,transform:r.decode,reverseTransform:r.encode})}var uBe=ne("ZodReadonly",(e,t)=>{L3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function lBe(e){return new uBe({type:"readonly",innerType:e})}var pBe=ne("ZodTemplateLiteral",(e,t)=>{k3.init(e,t),Sr.init(e,t)});function kfr(e,t){return new pBe({type:"template_literal",parts:e,...Le.normalizeParams(t)})}var fBe=ne("ZodLazy",(e,t)=>{F3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.getter()});function dBe(e){return new fBe({type:"lazy",getter:e})}var hBe=ne("ZodPromise",(e,t)=>{M3.init(e,t),Sr.init(e,t),e.unwrap=()=>e._zod.def.innerType});function $fr(e){return new hBe({type:"promise",innerType:e})}var mBe=ne("ZodFunction",(e,t)=>{$3.init(e,t),Sr.init(e,t)});function Mfr(e){return new mBe({type:"function",input:Array.isArray(e?.input)?KUe(e?.input):e?.input??Ut(xn()),output:e?.output??xn()})}var K4=ne("ZodCustom",(e,t)=>{j3.init(e,t),Sr.init(e,t)});function Ffr(e){let t=new ti({check:"custom"});return t._zod.check=e,t}function Koe(e,t){return D4(K4,e??(()=>!0),t)}function gBe(e,t={}){return P4(K4,e,t)}function yBe(e){return w4(e)}var jfr=N4,Vfr=I4;function qfr(e,t={error:`Input not instance of ${e.name}`}){let r=new K4({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...Le.normalizeParams(t)});return r._zod.bag.Class=e,r}var Ufr=(...e)=>R4({Codec:Goe,Boolean:JR,String:YR},...e);function Bfr(e){let t=dBe(()=>nn([ee(e),gn(),wi(),QR(),Ut(t),$n(ee(),t)]));return t}function Y4(e,t){return q4(Uoe(e),t)}var zfr={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 Hfr(e){fa({customError:e})}function Gfr(){return fa().customError}var Yoe;Yoe||(Yoe={});var Woe={};Pi(Woe,{bigint:()=>Xfr,boolean:()=>Wfr,date:()=>Jfr,number:()=>Yfr,string:()=>Kfr});function Kfr(e){return G3(YR,e)}function Yfr(e){return e4(XR,e)}function Wfr(e){return s4(JR,e)}function Xfr(e){return u4(ZR,e)}function Jfr(e){return _4(z4,e)}fa(V3());var Joe="2025-11-25";var vBe=[Joe,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Eb="io.modelcontextprotocol/related-task",X4="2.0",ms=Koe(e=>e!==null&&(typeof e=="object"||typeof e=="function")),bBe=nn([ee(),gn().int()]),_Be=ee(),oui=Xs({ttl:nn([gn(),QR()]).optional(),pollInterval:gn().optional()}),Qfr=we({ttl:gn().optional()}),edr=we({taskId:ee()}),Zoe=Xs({progressToken:bBe.optional(),[Eb]:edr.optional()}),zl=we({_meta:Zoe.optional()}),tL=zl.extend({task:Qfr.optional()}),EBe=e=>tL.safeParse(e).success,gs=we({method:ee(),params:zl.loose().optional()}),Fp=we({_meta:Zoe.optional()}),jp=we({method:ee(),params:Fp.loose().optional()}),ys=Xs({_meta:Zoe.optional()}),J4=nn([ee(),gn().int()]),TBe=we({jsonrpc:ft(X4),id:J4,...gs.shape}).strict(),Qoe=e=>TBe.safeParse(e).success,OBe=we({jsonrpc:ft(X4),...jp.shape}).strict(),SBe=e=>OBe.safeParse(e).success,ese=we({jsonrpc:ft(X4),id:J4,result:ys}).strict(),rL=e=>ese.safeParse(e).success;var an;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(an||(an={}));var tse=we({jsonrpc:ft(X4),id:J4.optional(),error:we({code:gn().int(),message:ee(),data:xn().optional()})}).strict();var ABe=e=>tse.safeParse(e).success;var xBe=nn([TBe,OBe,ese,tse]),sui=nn([ese,tse]),Z4=ys.strict(),tdr=Fp.extend({requestId:J4.optional(),reason:ee().optional()}),Q4=jp.extend({method:ft("notifications/cancelled"),params:tdr}),rdr=we({src:ee(),mimeType:ee().optional(),sizes:Ut(ee()).optional(),theme:ri(["light","dark"]).optional()}),nL=we({icons:Ut(rdr).optional()}),Xx=we({name:ee(),title:ee().optional()}),CBe=Xx.extend({...Xx.shape,...nL.shape,version:ee(),websiteUrl:ee().optional(),description:ee().optional()}),ndr=eL(we({applyDefaults:wi().optional()}),$n(ee(),xn())),idr=Y4(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,eL(we({form:ndr.optional(),url:ms.optional()}),$n(ee(),xn()).optional())),adr=Xs({list:ms.optional(),cancel:ms.optional(),requests:Xs({sampling:Xs({createMessage:ms.optional()}).optional(),elicitation:Xs({create:ms.optional()}).optional()}).optional()}),odr=Xs({list:ms.optional(),cancel:ms.optional(),requests:Xs({tools:Xs({call:ms.optional()}).optional()}).optional()}),sdr=we({experimental:$n(ee(),ms).optional(),sampling:we({context:ms.optional(),tools:ms.optional()}).optional(),elicitation:idr.optional(),roots:we({listChanged:wi().optional()}).optional(),tasks:adr.optional()}),cdr=zl.extend({protocolVersion:ee(),capabilities:sdr,clientInfo:CBe}),iL=gs.extend({method:ft("initialize"),params:cdr});var udr=we({experimental:$n(ee(),ms).optional(),logging:ms.optional(),completions:ms.optional(),prompts:we({listChanged:wi().optional()}).optional(),resources:we({subscribe:wi().optional(),listChanged:wi().optional()}).optional(),tools:we({listChanged:wi().optional()}).optional(),tasks:odr.optional()}),ldr=ys.extend({protocolVersion:ee(),capabilities:udr,serverInfo:CBe,instructions:ee().optional()}),rse=jp.extend({method:ft("notifications/initialized"),params:Fp.optional()});var ez=gs.extend({method:ft("ping"),params:zl.optional()}),pdr=we({progress:gn(),total:kn(gn()),message:kn(ee())}),fdr=we({...Fp.shape,...pdr.shape,progressToken:bBe}),tz=jp.extend({method:ft("notifications/progress"),params:fdr}),ddr=zl.extend({cursor:_Be.optional()}),aL=gs.extend({params:ddr.optional()}),oL=ys.extend({nextCursor:_Be.optional()}),hdr=ri(["working","input_required","completed","failed","cancelled"]),sL=we({taskId:ee(),status:hdr,ttl:nn([gn(),QR()]),createdAt:ee(),lastUpdatedAt:ee(),pollInterval:kn(gn()),statusMessage:kn(ee())}),Jx=ys.extend({task:sL}),mdr=Fp.merge(sL),cL=jp.extend({method:ft("notifications/tasks/status"),params:mdr}),rz=gs.extend({method:ft("tasks/get"),params:zl.extend({taskId:ee()})}),nz=ys.merge(sL),iz=gs.extend({method:ft("tasks/result"),params:zl.extend({taskId:ee()})}),cui=ys.loose(),az=aL.extend({method:ft("tasks/list")}),oz=oL.extend({tasks:Ut(sL)}),sz=gs.extend({method:ft("tasks/cancel"),params:zl.extend({taskId:ee()})}),DBe=ys.merge(sL),PBe=we({uri:ee(),mimeType:kn(ee()),_meta:$n(ee(),xn()).optional()}),wBe=PBe.extend({text:ee()}),nse=ee().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),NBe=PBe.extend({blob:nse}),uL=ri(["user","assistant"]),Zx=we({audience:Ut(uL).optional(),priority:gn().min(0).max(1).optional(),lastModified:Yx.datetime({offset:!0}).optional()}),IBe=we({...Xx.shape,...nL.shape,uri:ee(),description:kn(ee()),mimeType:kn(ee()),annotations:Zx.optional(),_meta:kn(Xs({}))}),gdr=we({...Xx.shape,...nL.shape,uriTemplate:ee(),description:kn(ee()),mimeType:kn(ee()),annotations:Zx.optional(),_meta:kn(Xs({}))}),ydr=aL.extend({method:ft("resources/list")}),vdr=oL.extend({resources:Ut(IBe)}),bdr=aL.extend({method:ft("resources/templates/list")}),_dr=oL.extend({resourceTemplates:Ut(gdr)}),ise=zl.extend({uri:ee()}),Edr=ise,Tdr=gs.extend({method:ft("resources/read"),params:Edr}),Odr=ys.extend({contents:Ut(nn([wBe,NBe]))}),Sdr=jp.extend({method:ft("notifications/resources/list_changed"),params:Fp.optional()}),Adr=ise,xdr=gs.extend({method:ft("resources/subscribe"),params:Adr}),Cdr=ise,Ddr=gs.extend({method:ft("resources/unsubscribe"),params:Cdr}),Pdr=Fp.extend({uri:ee()}),wdr=jp.extend({method:ft("notifications/resources/updated"),params:Pdr}),Ndr=we({name:ee(),description:kn(ee()),required:kn(wi())}),Idr=we({...Xx.shape,...nL.shape,description:kn(ee()),arguments:kn(Ut(Ndr)),_meta:kn(Xs({}))}),Rdr=aL.extend({method:ft("prompts/list")}),Ldr=oL.extend({prompts:Ut(Idr)}),kdr=zl.extend({name:ee(),arguments:$n(ee(),ee()).optional()}),$dr=gs.extend({method:ft("prompts/get"),params:kdr}),ase=we({type:ft("text"),text:ee(),annotations:Zx.optional(),_meta:$n(ee(),xn()).optional()}),ose=we({type:ft("image"),data:nse,mimeType:ee(),annotations:Zx.optional(),_meta:$n(ee(),xn()).optional()}),sse=we({type:ft("audio"),data:nse,mimeType:ee(),annotations:Zx.optional(),_meta:$n(ee(),xn()).optional()}),Mdr=we({type:ft("tool_use"),name:ee(),id:ee(),input:$n(ee(),xn()),_meta:$n(ee(),xn()).optional()}),Fdr=we({type:ft("resource"),resource:nn([wBe,NBe]),annotations:Zx.optional(),_meta:$n(ee(),xn()).optional()}),jdr=IBe.extend({type:ft("resource_link")}),cse=nn([ase,ose,sse,jdr,Fdr]),Vdr=we({role:uL,content:cse}),qdr=ys.extend({description:ee().optional(),messages:Ut(Vdr)}),Udr=jp.extend({method:ft("notifications/prompts/list_changed"),params:Fp.optional()}),Bdr=we({title:ee().optional(),readOnlyHint:wi().optional(),destructiveHint:wi().optional(),idempotentHint:wi().optional(),openWorldHint:wi().optional()}),zdr=we({taskSupport:ri(["required","optional","forbidden"]).optional()}),RBe=we({...Xx.shape,...nL.shape,description:ee().optional(),inputSchema:we({type:ft("object"),properties:$n(ee(),ms).optional(),required:Ut(ee()).optional()}).catchall(xn()),outputSchema:we({type:ft("object"),properties:$n(ee(),ms).optional(),required:Ut(ee()).optional()}).catchall(xn()).optional(),annotations:Bdr.optional(),execution:zdr.optional(),_meta:$n(ee(),xn()).optional()}),use=aL.extend({method:ft("tools/list")}),Hdr=oL.extend({tools:Ut(RBe)}),cz=ys.extend({content:Ut(cse).default([]),structuredContent:$n(ee(),xn()).optional(),isError:wi().optional()}),uui=cz.or(ys.extend({toolResult:xn()})),Gdr=tL.extend({name:ee(),arguments:$n(ee(),xn()).optional()}),lL=gs.extend({method:ft("tools/call"),params:Gdr}),Kdr=jp.extend({method:ft("notifications/tools/list_changed"),params:Fp.optional()}),lui=we({autoRefresh:wi().default(!0),debounceMs:gn().int().nonnegative().default(300)}),pL=ri(["debug","info","notice","warning","error","critical","alert","emergency"]),Ydr=zl.extend({level:pL}),lse=gs.extend({method:ft("logging/setLevel"),params:Ydr}),Wdr=Fp.extend({level:pL,logger:ee().optional(),data:xn()}),Xdr=jp.extend({method:ft("notifications/message"),params:Wdr}),Jdr=we({name:ee().optional()}),Zdr=we({hints:Ut(Jdr).optional(),costPriority:gn().min(0).max(1).optional(),speedPriority:gn().min(0).max(1).optional(),intelligencePriority:gn().min(0).max(1).optional()}),Qdr=we({mode:ri(["auto","required","none"]).optional()}),ehr=we({type:ft("tool_result"),toolUseId:ee().describe("The unique identifier for the corresponding tool call."),content:Ut(cse).default([]),structuredContent:we({}).loose().optional(),isError:wi().optional(),_meta:$n(ee(),xn()).optional()}),thr=G4("type",[ase,ose,sse]),W4=G4("type",[ase,ose,sse,Mdr,ehr]),rhr=we({role:uL,content:nn([W4,Ut(W4)]),_meta:$n(ee(),xn()).optional()}),nhr=tL.extend({messages:Ut(rhr),modelPreferences:Zdr.optional(),systemPrompt:ee().optional(),includeContext:ri(["none","thisServer","allServers"]).optional(),temperature:gn().optional(),maxTokens:gn().int(),stopSequences:Ut(ee()).optional(),metadata:ms.optional(),tools:Ut(RBe).optional(),toolChoice:Qdr.optional()}),ihr=gs.extend({method:ft("sampling/createMessage"),params:nhr}),pse=ys.extend({model:ee(),stopReason:kn(ri(["endTurn","stopSequence","maxTokens"]).or(ee())),role:uL,content:thr}),fse=ys.extend({model:ee(),stopReason:kn(ri(["endTurn","stopSequence","maxTokens","toolUse"]).or(ee())),role:uL,content:nn([W4,Ut(W4)])}),ahr=we({type:ft("boolean"),title:ee().optional(),description:ee().optional(),default:wi().optional()}),ohr=we({type:ft("string"),title:ee().optional(),description:ee().optional(),minLength:gn().optional(),maxLength:gn().optional(),format:ri(["email","uri","date","date-time"]).optional(),default:ee().optional()}),shr=we({type:ri(["number","integer"]),title:ee().optional(),description:ee().optional(),minimum:gn().optional(),maximum:gn().optional(),default:gn().optional()}),chr=we({type:ft("string"),title:ee().optional(),description:ee().optional(),enum:Ut(ee()),default:ee().optional()}),uhr=we({type:ft("string"),title:ee().optional(),description:ee().optional(),oneOf:Ut(we({const:ee(),title:ee()})),default:ee().optional()}),lhr=we({type:ft("string"),title:ee().optional(),description:ee().optional(),enum:Ut(ee()),enumNames:Ut(ee()).optional(),default:ee().optional()}),phr=nn([chr,uhr]),fhr=we({type:ft("array"),title:ee().optional(),description:ee().optional(),minItems:gn().optional(),maxItems:gn().optional(),items:we({type:ft("string"),enum:Ut(ee())}),default:Ut(ee()).optional()}),dhr=we({type:ft("array"),title:ee().optional(),description:ee().optional(),minItems:gn().optional(),maxItems:gn().optional(),items:we({anyOf:Ut(we({const:ee(),title:ee()}))}),default:Ut(ee()).optional()}),hhr=nn([fhr,dhr]),mhr=nn([lhr,phr,hhr]),ghr=nn([mhr,ahr,ohr,shr]),yhr=tL.extend({mode:ft("form").optional(),message:ee(),requestedSchema:we({type:ft("object"),properties:$n(ee(),ghr),required:Ut(ee()).optional()})}),vhr=tL.extend({mode:ft("url"),message:ee(),elicitationId:ee(),url:ee().url()}),bhr=nn([yhr,vhr]),_hr=gs.extend({method:ft("elicitation/create"),params:bhr}),Ehr=Fp.extend({elicitationId:ee()}),Thr=jp.extend({method:ft("notifications/elicitation/complete"),params:Ehr}),uz=ys.extend({action:ri(["accept","decline","cancel"]),content:Y4(e=>e===null?void 0:e,$n(ee(),nn([ee(),gn(),wi(),Ut(ee())])).optional())}),Ohr=we({type:ft("ref/resource"),uri:ee()});var Shr=we({type:ft("ref/prompt"),name:ee()}),Ahr=zl.extend({ref:nn([Shr,Ohr]),argument:we({name:ee(),value:ee()}),context:we({arguments:$n(ee(),ee()).optional()}).optional()}),xhr=gs.extend({method:ft("completion/complete"),params:Ahr});var Chr=ys.extend({completion:Xs({values:Ut(ee()).max(100),total:kn(gn().int()),hasMore:kn(wi())})}),Dhr=we({uri:ee().startsWith("file://"),name:ee().optional(),_meta:$n(ee(),xn()).optional()}),Phr=gs.extend({method:ft("roots/list"),params:zl.optional()}),dse=ys.extend({roots:Ut(Dhr)}),whr=jp.extend({method:ft("notifications/roots/list_changed"),params:Fp.optional()}),pui=nn([ez,iL,xhr,lse,$dr,Rdr,ydr,bdr,Tdr,xdr,Ddr,lL,use,rz,iz,az,sz]),fui=nn([Q4,tz,rse,whr,cL]),dui=nn([Z4,pse,fse,uz,dse,nz,oz,Jx]),hui=nn([ez,ihr,_hr,Phr,rz,iz,az,sz]),mui=nn([Q4,tz,Xdr,wdr,Sdr,Kdr,Udr,cL,Thr]),gui=nn([Z4,ldr,Chr,qdr,Ldr,vdr,_dr,Odr,cz,Hdr,nz,oz,Jx]),Ar=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===an.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new Xoe(i.elicitations,r)}return new e(t,r,n)}},Xoe=class extends Ar{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(an.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function Tb(e){return e==="completed"||e==="failed"||e==="cancelled"}var Nhr=Symbol("Let zodToJsonSchema decide on which parser to use");var Xui=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function hse(e){let r=L4(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=IUe(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function mse(e,t){let r=_b(e,t);if(!r.success)throw r.error;return r.data}var Mhr=6e4,lz=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(Q4,r=>{this._oncancel(r)}),this.setNotificationHandler(tz,r=>{this._onprogress(r)}),this.setRequestHandler(ez,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(rz,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Ar(an.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(iz,async(r,n)=>{let i=async()=>{let a=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let p=c,d=new Ar(p.error.code,p.error.message,p.error.data);l(d)}else{let p=s.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let o=await this._taskStore.getTask(a,n.sessionId);if(!o)throw new Ar(an.InvalidParams,`Task not found: ${a}`);if(!Tb(o.status))return await this._waitForTaskUpdate(a,n.signal),await i();if(Tb(o.status)){let s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[Eb]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(az,async(r,n)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new Ar(an.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(sz,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Ar(an.InvalidParams,`Task not found: ${r.params.taskId}`);if(Tb(i.status))throw new Ar(an.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new Ar(an.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof Ar?i:new Ar(an.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.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),Ar.fromError(an.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=a=>{n?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),rL(a)||ABe(a)?this._onresponse(a):Qoe(a)?this._onrequest(a,o):SBe(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=Ar.fromError(an.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,i=this._transport,a=t.params?._meta?.[Eb]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:an.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{type:"error",message:l,timestamp:Date.now()},i?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):i?.send(l).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(t.id,o);let s=EBe(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,i?.sessionId):void 0,u={signal:o.signal,sessionId:i?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{let p={relatedRequestId:t.id};a&&(p.relatedTask={taskId:a}),await this.notification(l,p)},sendRequest:async(l,p,d)=>{let f={...d,relatedRequestId:t.id};a&&!f.relatedTask&&(f.relatedTask={taskId:a});let h=f.relatedTask?.taskId??a;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(l,p,f)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:a,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(o.signal.aborted)return;let p={result:l,jsonrpc:"2.0",id:t.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async l=>{if(o.signal.aborted)return;let p={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:an.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"error",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).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),rL(t))n(t);else{let o=new Ar(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(rL(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),rL(t))i(t);else{let o=Ar.fromError(t.error.code,t.error.message,t.error.data);i(o)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(t,r,n)}}catch(o){yield{type:"error",error:o instanceof Ar?o:new Ar(an.InternalError,String(o))}}return}let a;try{let o=await this.request(t,Jx,n);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new Ar(an.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},Tb(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new Ar(an.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new Ar(an.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof Ar?o:new Ar(an.InternalError,String(o))}}}request(t,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{let p=O=>{l(O)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),s&&this.assertTaskCapability(t.method)}catch(O){p(O);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...t,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...t.params,_meta:{...t.params?._meta||{},progressToken:d}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Eb]:c}});let h=O=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(O)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(A=>this._onerror(new Error(`Failed to send cancellation: ${A}`)));let S=O instanceof Ar?O:new Ar(an.RequestTimeout,String(O));l(S)};this._responseHandlers.set(d,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return l(O);try{let S=_b(r,O.result);S.success?u(S.data):l(S.error)}catch(S){l(S)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??Mhr,v=()=>h(Ar.fromError(an.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(d,g,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let E=c?.taskId;if(E){let O=S=>{let A=this._responseHandlers.get(d);A?A(S):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,O),this._enqueueTaskMessage(E,{type:"request",message:f,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(d),l(S)})}else this._transport.send(f,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(O=>{this._cleanupTimeout(d),l(O)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},nz,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},oz,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},DBe,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let s={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Eb]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Eb]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let o={...t,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[Eb]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(t,r){let n=hse(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=mse(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=hse(t);this._notificationHandlers.set(n,i=>{let a=mse(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){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,i)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let i of n)if(i.type==="request"&&Qoe(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new Ar(an.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(t);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,a)=>{if(r.aborted){a(new Ar(an.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),a(new Ar(an.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!t)throw new Error("No request provided");return await n.createTask(i,t.id,{method:t.method,params:t.params},r)},getTask:async i=>{let a=await n.getTask(i,r);if(!a)throw new Ar(an.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await n.storeTaskResult(i,a,o,r);let s=await n.getTask(i,r);if(s){let c=cL.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Tb(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 Ar(an.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Tb(s.status))throw new Ar(an.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,o,r);let c=await n.getTask(i,r);if(c){let u=cL.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Tb(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function LBe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kBe(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];LBe(o)&&LBe(a)?r[i]={...o,...a}:r[i]=a}return r}var Cze=Dt(Hz(),1),Dze=Dt(xze(),1);function A_r(){let e=new Cze.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Dze.default)(e),e}var Kz=class{constructor(t){this._ajv=t??A_r()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Yz=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 Pze(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function wze(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Wz=class extends lz{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(pL.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Kz,this.setRequestHandler(iL,n=>this._oninitialize(n)),this.setNotificationHandler(rse,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(lse,async(n,i)=>{let a=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=n.params,s=pL.safeParse(o);return s.success&&this._loggingLevels.set(a,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Yz(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=kBe(this._capabilities,t)}setRequestHandler(t,r){let i=L4(t)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(Kx(i)){let s=i;a=s._zod?.def?.value??s.value}else{let s=i;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let s=async(c,u)=>{let l=_b(lL,c);if(!l.success){let h=l.error instanceof Error?l.error.message:String(l.error);throw new Ar(an.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=l.data,d=await Promise.resolve(r(c,u));if(p.task){let h=_b(Jx,d);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new Ar(an.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let f=_b(cz,d);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new Ar(an.InvalidParams,`Invalid tools/call result: ${h}`)}return f.data};return super.setRequestHandler(t,s)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){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(!this._clientCapabilities?.elicitation?.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){wze(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Pze(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:vBe.includes(r)?r:Joe,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"},Z4)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],a=i.some(u=>u.type==="tool_result"),o=t.messages.length>1?t.messages[t.messages.length-2]:void 0,s=o?Array.isArray(o.content)?o.content:[o.content]:[],c=s.some(u=>u.type==="tool_use");if(a){if(i.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(p=>p.type==="tool_use").map(p=>p.id)),l=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(u.size!==l.size||![...u].every(p=>l.has(p)))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},fse,r):this.request({method:"sampling/createMessage",params:t},pse,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=t;return this.request({method:"elicitation/create",params:i},uz,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=t.mode==="form"?t:{...t,mode:"form"},a=await this.request({method:"elicitation/create",params:i},uz,r);if(a.action==="accept"&&a.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!s.valid)throw new Ar(an.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(o){throw o instanceof Ar?o:new Ar(an.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return a}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},dse,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 oue=Dt(require("node:process"),1);var Xz=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
1609
1609
  `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),x_r(r)}clear(){this._buffer=void 0}};function x_r(e){return xBe.parse(JSON.parse(e))}function Nze(e){return JSON.stringify(e)+`
1610
- `}var Jz=class{constructor(t=oue.default.stdin,r=oue.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Xz,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(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(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Nze(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Rze="0.6.9";var Q0={name:"@sap-ux/fiori-mcp-server",description:"SAP Fiori - Model Context Protocol (MCP) server",version:Rze,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.25.2","@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.8"},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 $ze=we({name:ee().describe("Name of the Fiori application. Usually derived from the `sap.app/id` field in the application's manifest.json."),appPath:ee().describe("Absolute path to the Fiori application's root directory."),projectPath:ee().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:ri(["EDMXBackend","CAPJava","CAPNodejs"]).describe("Type of project the application belongs to."),odataVersion:ee().describe("OData protocol version used by the application's main service.")}),tT=nn([ee(),Ut(nn([ee(),gn()]))]),Mze=we({functionalityId:tT.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),description:ee()}),Lze=ri(["object","array","string","number","boolean","null","integer","any"]),kze=we({type:nn([Lze,Ut(Lze)]).optional(),description:ee().optional(),properties:B4().optional()}).catchall(B4()),Fze=kze.extend({properties:$n(ee(),nn([kze,wi()])).optional()});var jze=we({searchPath:Ut(ee()).describe("Path to search for Fiori applications (defaults to current directory). If VSCode - list of VS Code workspace folder paths(`workspace.workspaceFolders`)")}),Vze=we({appPath:ee().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.")}),qze=we({appPath:ee().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path."),functionalityId:tT.describe("The ID of the functionality to get details for")}),Uze=we({functionalityId:tT.describe("The ID of the functionality to execute"),parameters:$n(ee(),xn()).describe("Parameters for the functionality execution"),appPath:ee().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.'),whi=we({query:ee().min(2).describe("The search query for fiori elements, annotations, sapui5, fiori tools documentation")});var Ihi=ee().describe("Search results as formatted text"),Bze=we({applications:Ut($ze)}),zze=we({applicationPath:ee(),functionalities:Ut(Mze)}),Hze=we({functionalityId:tT.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),name:ee(),description:ee(),technicalDescription:ee().optional(),parameters:Fze,prerequisites:Ut(ee()).optional(),impact:ee().optional(),examples:Ut(ee()).optional(),pageName:ee().optional()}),Gze=we({functionalityId:tT,status:ee(),message:ee(),parameters:xn(),appPath:ee(),changes:Ut(ee()),timestamp:ee()});var N_e=Dt(require("node:fs/promises")),lf=Dt(require("node:path"));var eu=Dt(Kb()),Adt=Dt(Cd()),xdt=require("node:path");function DZr(){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 eu.LogLevel.Error;case"WARN":return eu.LogLevel.Warn;case"INFO":return eu.LogLevel.Info;case"DEBUG":return eu.LogLevel.Debug;case"VERBOSE":return eu.LogLevel.Verbose;case"SILLY":return eu.LogLevel.Silly;default:break}return eu.LogLevel.Error}var Sdt=DZr(),dt=new eu.ToolsLogger({logLevel:Sdt??eu.LogLevel.Error,transports:Sdt===void 0?[new eu.NullTransport]:[new eu.FileTransport({filename:(0,xdt.join)(Adt.fioriToolsDirectory,"fiori-mcp-server.log"),maxsize:10*1024*1024,maxFiles:5})],logPrefix:"fiori-mcp"}),IM={info:(e,...t)=>{dt.info(`@sap/ux-specification: ${e}`);for(let r of t)dt.info(typeof r=="number"?r.toString():r)},warning:(e,...t)=>{dt.warn(`@sap/ux-specification: ${e}`);for(let r of t)dt.warn(typeof r=="number"?r.toString():r)},error:(e,...t)=>{dt.error(`@sap/ux-specification: ${e}`);for(let r of t)dt.error(typeof r=="number"?r.toString():r)},reset:()=>{}};async function Cdt(){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 N_e.default.access(n),dt.log("\u2713 Using @sap-ux/fiori-docs-embeddings package"),{dataPath:n,embeddingsPath:lf.default.join(n,"embeddings"),searchPath:lf.default.join(n,"search"),docsPath:lf.default.join(n,"docs"),isExternalPackage:!0,isAvailable:!0}}catch{dt.warn("Could not load @sap-ux/fiori-docs-embeddings package, trying local data...")}let e=lf.default.join(__dirname,"../../data");try{return await N_e.default.access(e),dt.log("\u2713 Using local data directory"),{dataPath:e,embeddingsPath:lf.default.join(e,"embeddings"),searchPath:lf.default.join(e,"search"),docsPath:lf.default.join(e,"docs"),isExternalPackage:!1,isAvailable:!0}}catch{dt.warn("Local data directory not available either")}let t=lf.default.join(__dirname,"../../data");return dt.warn("\u26A0\uFE0F No embeddings data available - running in limited mode"),{dataPath:t,embeddingsPath:lf.default.join(t,"embeddings"),searchPath:lf.default.join(t,"search"),docsPath:lf.default.join(t,"docs"),isExternalPackage:!1,isAvailable:!1}}var lc=Dt(Cd()),RM=require("node:path");async function tu(e){try{e=(0,RM.join)(e);try{let t=await(0,lc.createApplicationAccess)(e);return{root:t.project.root,appId:t.getAppId(),applicationAccess:t}}catch(t){dt.warn(`Application was not found by given path. Error: ${t}`);let r=await(0,lc.findProjectRoot)(e),n=await(0,lc.getProject)(r);if(n)return{root:n.root,appId:""}}}catch(t){dt.warn(`Project was not found by given path. Error: ${t}`);return}}var s9=e=>{let t;switch(e){case lc.DirName.View:{t=(0,RM.join)(lc.DirName.Ext,lc.DirName.View);break}case lc.DirName.Fragment:{t=(0,RM.join)(lc.DirName.Ext,lc.DirName.Fragment);break}case lc.DirName.Controller:{t=(0,RM.join)(lc.DirName.Ext,lc.DirName.Controller);break}default:t=e}return t},Xh=(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,Xh({...o,...s},t,r)}}let n={...e};return n.properties&&(n.properties=Object.fromEntries(Object.entries(n.properties).map(([i,a])=>[i,Xh(a,t,r)]))),n.items&&(Array.isArray(n.items)?n.items=n.items.map(i=>Xh(i,t,r)):n.items=Xh(n.items,t,r)),n.allOf&&(n.allOf=n.allOf.map(i=>Xh(i,t,r))),n.anyOf&&(n.anyOf=n.anyOf.map(i=>Xh(i,t,r))),n.oneOf&&(n.oneOf=n.oneOf.map(i=>Xh(i,t,r))),typeof n.additionalProperties=="object"&&(n.additionalProperties=Xh(n.additionalProperties,t,r)),n},Ddt=(e,t)=>({type:"object",properties:{[e]:t}}),va=e=>{let t=q0(e);return delete t.$schema,t},Jh=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof ooe?new Error(`Missing required fields in parameters. ${JSON.stringify(r.issues,null,4)}`):new Error("Unknown error. Recheck input parameters.")}};var _At=require("node:util"),EAt=require("node:child_process"),TAt=Dt(aSe());async function TY(e="1.18.5"){let t="@sap/generator-fiori";if((await(0,TAt.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 OY=(0,_At.promisify)(EAt.exec);var OAt=require("@lancedb/lancedb");var oSe=Dt(require("node:fs/promises")),sSe=Dt(require("node:path")),SY=class{connection=null;tables=[];tableIndex=null;metadata=null;dataPath;constructor(t){this.dataPath=t||""}async initialize(){try{dt.log("Loading vector database from pre-built embeddings...");let t=await Cdt();if(!t.isAvailable)throw new Error("No embeddings data available");this.dataPath=t.embeddingsPath,dt.log(`Using embeddings path: ${this.dataPath} (external: ${t.isExternalPackage})`);let r=sSe.default.join(this.dataPath,"metadata.json"),n=await oSe.default.readFile(r,"utf-8");this.metadata=JSON.parse(n),dt.log("\u2713 Embedding metadata loaded:"),dt.log(` Model: ${this?.metadata?.model}`),dt.log(` Dimensions: ${this?.metadata?.dimensions}`),dt.log(` Total vectors: ${this?.metadata?.totalVectors}`),dt.log(` Created: ${this?.metadata?.createdAt}`),this.connection=await(0,OAt.connect)(this.dataPath);let i=sSe.default.join(this.dataPath,"table_index.json");try{let a=await oSe.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)}dt.log(`\u2713 Loaded ${this.tables.length} split tables`)}catch{dt.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}`)}}dt.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 dt.error(`Semantic search failed: ${i}`),new Error(`Semantic search failed: ${i}`)}}async findSimilarToText(t,r=5){return dt.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 dt.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 dt.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=[],dt.log("Vector database connection closed"))}};var AY=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 cSe(e,t=!1){let{query:r,maxResults:n}=e;try{let i=new SY,a=new AY;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}:
1610
+ `}var Jz=class{constructor(t=oue.default.stdin,r=oue.default.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new Xz,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(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(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Nze(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Rze="0.6.10";var Q0={name:"@sap-ux/fiori-mcp-server",description:"SAP Fiori - Model Context Protocol (MCP) server",version:Rze,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.25.2","@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.8"},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 $ze=we({name:ee().describe("Name of the Fiori application. Usually derived from the `sap.app/id` field in the application's manifest.json."),appPath:ee().describe("Absolute path to the Fiori application's root directory."),projectPath:ee().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:ri(["EDMXBackend","CAPJava","CAPNodejs"]).describe("Type of project the application belongs to."),odataVersion:ee().describe("OData protocol version used by the application's main service.")}),tT=nn([ee(),Ut(nn([ee(),gn()]))]),Mze=we({functionalityId:tT.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),description:ee()}),Lze=ri(["object","array","string","number","boolean","null","integer","any"]),kze=we({type:nn([Lze,Ut(Lze)]).optional(),description:ee().optional(),properties:B4().optional()}).catchall(B4()),Fze=kze.extend({properties:$n(ee(),nn([kze,wi()])).optional()});var jze=we({searchPath:Ut(ee()).describe("Path to search for Fiori applications (defaults to current directory). If VSCode - list of VS Code workspace folder paths(`workspace.workspaceFolders`)")}),Vze=we({appPath:ee().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.")}),qze=we({appPath:ee().describe("Path to the Fiori application if one exists or to the current directory. Path should be an absolute path."),functionalityId:tT.describe("The ID of the functionality to get details for")}),Uze=we({functionalityId:tT.describe("The ID of the functionality to execute"),parameters:$n(ee(),xn()).describe("Parameters for the functionality execution"),appPath:ee().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.'),whi=we({query:ee().min(2).describe("The search query for fiori elements, annotations, sapui5, fiori tools documentation")});var Ihi=ee().describe("Search results as formatted text"),Bze=we({applications:Ut($ze)}),zze=we({applicationPath:ee(),functionalities:Ut(Mze)}),Hze=we({functionalityId:tT.describe("Identifier to pass as the `functionalityId` parameter when calling `get_functionality_details` or `execute_functionality`"),name:ee(),description:ee(),technicalDescription:ee().optional(),parameters:Fze,prerequisites:Ut(ee()).optional(),impact:ee().optional(),examples:Ut(ee()).optional(),pageName:ee().optional()}),Gze=we({functionalityId:tT,status:ee(),message:ee(),parameters:xn(),appPath:ee(),changes:Ut(ee()),timestamp:ee()});var N_e=Dt(require("node:fs/promises")),lf=Dt(require("node:path"));var eu=Dt(Kb()),Adt=Dt(Cd()),xdt=require("node:path");function DZr(){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 eu.LogLevel.Error;case"WARN":return eu.LogLevel.Warn;case"INFO":return eu.LogLevel.Info;case"DEBUG":return eu.LogLevel.Debug;case"VERBOSE":return eu.LogLevel.Verbose;case"SILLY":return eu.LogLevel.Silly;default:break}return eu.LogLevel.Error}var Sdt=DZr(),dt=new eu.ToolsLogger({logLevel:Sdt??eu.LogLevel.Error,transports:Sdt===void 0?[new eu.NullTransport]:[new eu.FileTransport({filename:(0,xdt.join)(Adt.fioriToolsDirectory,"fiori-mcp-server.log"),maxsize:10*1024*1024,maxFiles:5})],logPrefix:"fiori-mcp"}),IM={info:(e,...t)=>{dt.info(`@sap/ux-specification: ${e}`);for(let r of t)dt.info(typeof r=="number"?r.toString():r)},warning:(e,...t)=>{dt.warn(`@sap/ux-specification: ${e}`);for(let r of t)dt.warn(typeof r=="number"?r.toString():r)},error:(e,...t)=>{dt.error(`@sap/ux-specification: ${e}`);for(let r of t)dt.error(typeof r=="number"?r.toString():r)},reset:()=>{}};async function Cdt(){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 N_e.default.access(n),dt.log("\u2713 Using @sap-ux/fiori-docs-embeddings package"),{dataPath:n,embeddingsPath:lf.default.join(n,"embeddings"),searchPath:lf.default.join(n,"search"),docsPath:lf.default.join(n,"docs"),isExternalPackage:!0,isAvailable:!0}}catch{dt.warn("Could not load @sap-ux/fiori-docs-embeddings package, trying local data...")}let e=lf.default.join(__dirname,"../../data");try{return await N_e.default.access(e),dt.log("\u2713 Using local data directory"),{dataPath:e,embeddingsPath:lf.default.join(e,"embeddings"),searchPath:lf.default.join(e,"search"),docsPath:lf.default.join(e,"docs"),isExternalPackage:!1,isAvailable:!0}}catch{dt.warn("Local data directory not available either")}let t=lf.default.join(__dirname,"../../data");return dt.warn("\u26A0\uFE0F No embeddings data available - running in limited mode"),{dataPath:t,embeddingsPath:lf.default.join(t,"embeddings"),searchPath:lf.default.join(t,"search"),docsPath:lf.default.join(t,"docs"),isExternalPackage:!1,isAvailable:!1}}var lc=Dt(Cd()),RM=require("node:path");async function tu(e){try{e=(0,RM.join)(e);try{let t=await(0,lc.createApplicationAccess)(e);return{root:t.project.root,appId:t.getAppId(),applicationAccess:t}}catch(t){dt.warn(`Application was not found by given path. Error: ${t}`);let r=await(0,lc.findProjectRoot)(e),n=await(0,lc.getProject)(r);if(n)return{root:n.root,appId:""}}}catch(t){dt.warn(`Project was not found by given path. Error: ${t}`);return}}var s9=e=>{let t;switch(e){case lc.DirName.View:{t=(0,RM.join)(lc.DirName.Ext,lc.DirName.View);break}case lc.DirName.Fragment:{t=(0,RM.join)(lc.DirName.Ext,lc.DirName.Fragment);break}case lc.DirName.Controller:{t=(0,RM.join)(lc.DirName.Ext,lc.DirName.Controller);break}default:t=e}return t},Xh=(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,Xh({...o,...s},t,r)}}let n={...e};return n.properties&&(n.properties=Object.fromEntries(Object.entries(n.properties).map(([i,a])=>[i,Xh(a,t,r)]))),n.items&&(Array.isArray(n.items)?n.items=n.items.map(i=>Xh(i,t,r)):n.items=Xh(n.items,t,r)),n.allOf&&(n.allOf=n.allOf.map(i=>Xh(i,t,r))),n.anyOf&&(n.anyOf=n.anyOf.map(i=>Xh(i,t,r))),n.oneOf&&(n.oneOf=n.oneOf.map(i=>Xh(i,t,r))),typeof n.additionalProperties=="object"&&(n.additionalProperties=Xh(n.additionalProperties,t,r)),n},Ddt=(e,t)=>({type:"object",properties:{[e]:t}}),va=e=>{let t=q0(e);return delete t.$schema,t},Jh=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof ooe?new Error(`Missing required fields in parameters. ${JSON.stringify(r.issues,null,4)}`):new Error("Unknown error. Recheck input parameters.")}};var _At=require("node:util"),EAt=require("node:child_process"),TAt=Dt(aSe());async function TY(e="1.18.5"){let t="@sap/generator-fiori";if((await(0,TAt.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 OY=(0,_At.promisify)(EAt.exec);var OAt=require("@lancedb/lancedb");var oSe=Dt(require("node:fs/promises")),sSe=Dt(require("node:path")),SY=class{connection=null;tables=[];tableIndex=null;metadata=null;dataPath;constructor(t){this.dataPath=t||""}async initialize(){try{dt.log("Loading vector database from pre-built embeddings...");let t=await Cdt();if(!t.isAvailable)throw new Error("No embeddings data available");this.dataPath=t.embeddingsPath,dt.log(`Using embeddings path: ${this.dataPath} (external: ${t.isExternalPackage})`);let r=sSe.default.join(this.dataPath,"metadata.json"),n=await oSe.default.readFile(r,"utf-8");this.metadata=JSON.parse(n),dt.log("\u2713 Embedding metadata loaded:"),dt.log(` Model: ${this?.metadata?.model}`),dt.log(` Dimensions: ${this?.metadata?.dimensions}`),dt.log(` Total vectors: ${this?.metadata?.totalVectors}`),dt.log(` Created: ${this?.metadata?.createdAt}`),this.connection=await(0,OAt.connect)(this.dataPath);let i=sSe.default.join(this.dataPath,"table_index.json");try{let a=await oSe.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)}dt.log(`\u2713 Loaded ${this.tables.length} split tables`)}catch{dt.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}`)}}dt.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 dt.error(`Semantic search failed: ${i}`),new Error(`Semantic search failed: ${i}`)}}async findSimilarToText(t,r=5){return dt.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 dt.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 dt.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=[],dt.log("Vector database connection closed"))}};var AY=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 cSe(e,t=!1){let{query:r,maxResults:n}=e;try{let i=new SY,a=new AY;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}:
1611
1611
 
1612
1612
  `,c+=`${l.document.content}
1613
1613
  `,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.9",
4
+ "version": "0.6.10",
5
5
  "keywords": [
6
6
  "SAP Fiori tools",
7
7
  "SAP Fiori elements",
@@ -54,11 +54,11 @@
54
54
  "@sap-ux/logger": "0.8.0",
55
55
  "@sap-ux/odata-annotation-core-types": "0.5.2",
56
56
  "@sap-ux/text-document-utils": "0.3.3",
57
+ "@sap-ux/nodejs-utils": "0.2.11",
57
58
  "@sap-ux/odata-entity-model": "0.3.4",
59
+ "@sap-ux/telemetry": "0.6.56",
58
60
  "@sap-ux/btp-utils": "1.1.6",
59
- "@sap-ux/feature-toggle": "0.3.5",
60
- "@sap-ux/nodejs-utils": "0.2.11",
61
- "@sap-ux/telemetry": "0.6.56"
61
+ "@sap-ux/feature-toggle": "0.3.5"
62
62
  },
63
63
  "dependencies": {
64
64
  "@xenova/transformers": "2.17.2",