@mcp-use/inspector 0.12.0-canary.9 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ const e={},t=Object.freeze(Object.defineProperty({__proto__:null,default:e},Symbol.toStringTag,{value:"Module"}));export{t as _};
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-D-XhkzNF.js","assets/index-mfl-FSxP.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
2
- import{v as ei,w as Cl,x as kl,_ as j,y as _e,Z as Tl,$ as El,p as zi,z as xl,T as ti,A as Ml,B as y,a as an,C as Ye,D as _s,E as _r,F as Sr,G as Al,H as Pl,I as Ol,J as Nl}from"./index-mfl-FSxP.js";import{K as tg,L as ng,M as rg,N as sg,O as ig,P as og,V as ag,W as lg,Q as cg}from"./index-mfl-FSxP.js";import{L as Wi,S as fr,t as Il,o as $l,l as Rl,a as Hi,T as jl,D as Ll,b as Gi}from"./index-DRgvhQ7a.js";import{h as bn,s as Dl,g as Ki,B as Ul,k as Fl,l as Vl,I as Bl,C as zl,m as Wl,t as Hl,n as Gl,o as Kl,p as Jl,q as ql,r as Yl,u as Xl,v as Zl,w as Ql,x as ec,y as tc,R as nc,z as rc,a as sc}from"./index-DY4fhMWt.js";import{aP as ic,aQ as Ss,aR as oc,at as Ee,e as Zt,aS as ac,aT as ln,a0 as de,x as nt,aU as Ji,g as lc,aV as Hr,_ as q,ag as Kt,ae as fe,z as O,ad as ee,d as cc,C as uc,aW as hc,p as ni,aA as qi,aX as be,ai as cn,aY as nn,E as Yi,y as Oe,aZ as Cs,B as Gr,D as Lt,am as Dt,a_ as dc,a$ as fc,b0 as pc,b1 as mc,b2 as gc,b3 as yc,b4 as wc,b5 as bc,b6 as vc,b7 as _c,b8 as Sc,b9 as Cc,ba as kc,bb as Tc,bc as Ec,bd as xc,be as Mc,K as Ac,bf as Pc,bg as Oc,bh as Nc,t as je,r as rn,m as $e,L as Xe,aq as Ut,bi as Ic,F as $c,aB as ri,ar as Rc,bj as si,bk as ii,ab as ks,aa as oi,a9 as Kr,ac as jc,S as Lc,a5 as Ts,a8 as Ge,bl as Jn,o as z,bm as ae,bn as Dc,bo as Me,bp as vt,bq as Uc,br as Es,l as U,a6 as Fc,i as Vc,T as Bc,bs as qn,bt as Ue,bu as F,bv as Xi,s as ne,a7 as zc,bw as An,bx as Zi,by as Ft,bz as un,bA as Yn,bB as Xn,bC as Wc,aL as Hc,aJ as Gc,aI as Kc,bD as Jc,aH as Pn}from"./index-BvWxscWX.js";import{E as Qi,c as qc,e as Yc}from"./embeddings-DQVbIFjc.js";import"./index-DRz5BQNA.js";const Xc=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Zc=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${Xc(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Cl(r.values[0])}`:`Invalid option: expected one of ${ei(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",i=e(r.origin);return i?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",i=e(r.origin);return i?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${i.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${ei(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Qc(){return{localeError:Zc()}}kl(Qc());var Cr,Cn,kr=0,Tr=0;function eu(t,e,n){var r=0,s=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Cr),o==null&&(o=Cn)),i==null||o==null){var a=t.random||(t.rng||ic)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Cr&&!t._v6&&(i[0]|=1,Cr=i)),o==null&&(o=(a[6]<<8|a[7])&16383,Cn===void 0&&!t._v6&&(Cn=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Tr+1,u=l-kr+(c-Tr)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>kr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");kr=l,Tr=c,Cn=o,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=o>>>8|128,s[r++]=o&255;for(var f=0;f<6;++f)s[r+f]=i[f];return e||Ss(s)}function tu(t){var e=typeof t=="string"?oc(t):t,n=nu(e);return typeof t=="string"?Ss(n):n}function nu(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function ai(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function li(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?ai(Object(n),!0).forEach(function(r){ru(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ai(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function ru(t,e,n){return(e=su(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function su(t){var e=iu(t,"string");return typeof e=="symbol"?e:e+""}function iu(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ou(t={},e,n=0){var r=eu(li(li({},t),{},{_v6:!0}),new Uint8Array(16));return r=tu(r),Ss(r)}async function*au(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}j(au,"streamEventsToAISDK");function lu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}j(lu,"createReadableStreamFromGenerator");async function*cu(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-C_3SaotY.js","assets/index-IsrJH759.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
2
+ import{t as ei,u as Cl,v as kl,_ as j,w as _e,Z as Tl,$ as El,p as zi,x as xl,T as ti,y as Ml,z as y,a as an,A as Ye,B as _s,C as _r,D as Sr,E as Al,F as Pl,G as Ol,H as Nl}from"./index-IsrJH759.js";import{I as tg,J as ng,K as rg,L as sg,M as ig,N as og,O as ag,K as lg,V as cg,W as ug,P as hg,Q as dg,Q as fg}from"./index-IsrJH759.js";import{L as Wi,S as fr,t as Il,o as $l,l as Rl,a as Hi,T as jl,D as Ll,b as Gi}from"./index-C1PULc-j.js";import{h as bn,s as Dl,g as Ki,B as Ul,k as Fl,l as Vl,I as Bl,C as zl,m as Wl,t as Hl,n as Gl,o as Kl,p as Jl,q as ql,r as Yl,u as Xl,v as Zl,w as Ql,x as ec,y as tc,R as nc,z as rc,a as sc}from"./index-CNOfsJmB.js";import{aP as ic,aQ as Ss,aR as oc,at as Ee,e as Zt,aS as ac,aT as ln,a0 as de,x as nt,aU as Ji,g as lc,aV as Hr,_ as q,ag as Kt,ae as fe,z as O,ad as ee,d as cc,C as uc,aW as hc,p as ni,aA as qi,aX as be,ai as cn,aY as nn,E as Yi,y as Oe,aZ as Cs,B as Gr,D as Lt,am as Dt,a_ as dc,a$ as fc,b0 as pc,b1 as mc,b2 as gc,b3 as yc,b4 as wc,b5 as bc,b6 as vc,b7 as _c,b8 as Sc,b9 as Cc,ba as kc,bb as Tc,bc as Ec,bd as xc,be as Mc,K as Ac,bf as Pc,bg as Oc,bh as Nc,t as je,r as rn,m as $e,L as Xe,aq as Ut,bi as Ic,F as $c,aB as ri,ar as Rc,bj as si,bk as ii,ab as ks,aa as oi,a9 as Kr,ac as jc,S as Lc,a5 as Ts,a8 as Ge,bl as Jn,o as z,bm as ae,bn as Dc,bo as Me,bp as vt,bq as Uc,br as Es,l as U,a6 as Fc,i as Vc,T as Bc,bs as qn,bt as Ue,bu as F,bv as Xi,s as ne,a7 as zc,bw as An,bx as Zi,by as Ft,bz as un,bA as Yn,bB as Xn,bC as Wc,aL as Hc,aJ as Gc,aI as Kc,bD as Jc,aH as Pn}from"./index-D4BJ-4dv.js";import{E as Qi,c as qc,e as Yc}from"./embeddings-DN38A_vZ.js";import"./index-DRz5BQNA.js";const Xc=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Zc=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${Xc(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Cl(r.values[0])}`:`Invalid option: expected one of ${ei(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",i=e(r.origin);return i?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",i=e(r.origin);return i?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${i.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${ei(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function Qc(){return{localeError:Zc()}}kl(Qc());var Cr,Cn,kr=0,Tr=0;function eu(t,e,n){var r=0,s=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Cr),o==null&&(o=Cn)),i==null||o==null){var a=t.random||(t.rng||ic)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Cr&&!t._v6&&(i[0]|=1,Cr=i)),o==null&&(o=(a[6]<<8|a[7])&16383,Cn===void 0&&!t._v6&&(Cn=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Tr+1,u=l-kr+(c-Tr)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>kr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");kr=l,Tr=c,Cn=o,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=o>>>8|128,s[r++]=o&255;for(var f=0;f<6;++f)s[r+f]=i[f];return e||Ss(s)}function tu(t){var e=typeof t=="string"?oc(t):t,n=nu(e);return typeof t=="string"?Ss(n):n}function nu(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function ai(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function li(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?ai(Object(n),!0).forEach(function(r){ru(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ai(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function ru(t,e,n){return(e=su(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function su(t){var e=iu(t,"string");return typeof e=="symbol"?e:e+""}function iu(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ou(t={},e,n=0){var r=eu(li(li({},t),{},{_v6:!0}),new Uint8Array(16));return r=tu(r),Ss(r)}async function*au(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}j(au,"streamEventsToAISDK");function lu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}j(lu,"createReadableStreamFromGenerator");async function*cu(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
3
  🔧 Using tool: ${e.name}
4
4
  `;break;case"on_tool_end":yield`
5
5
  ✅ Tool completed: ${e.name}
@@ -372,7 +372,7 @@ You can then use these server-specific tools in subsequent steps.
372
372
  Here are the tools *currently* available to you (this list includes server management tools and will
373
373
  change when you connect to a server):
374
374
  {tool_descriptions}
375
- `,jt,Zm=(jt=class{static getPackageVersion(){return xl()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Dm({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new mt,this.telemetry=ti.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Vi({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new mt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Rm(this.client,this.adapter)}else this.adapter=e.adapter??new mt(this.disallowedTools);if(this.telemetry=ti.getInstance(),this.llm){const[n,r]=Ml(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Vi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:j(()=>this.getMetadata(),"metadataProvider"),tagsProvider:j(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:j(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:j(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:j(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}y.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await mt.createTools(this.client),y.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Um;this.systemMessage=vl(e,n,Fm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof be))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[gl({runLimit:this.maxSteps})],s=il({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new be(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof be)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new mt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const i=r.replace(/[^\w-]/g,"_");if(s==null)n[i]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[i]=s;else if(Array.isArray(s)){const o=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof s=="object")try{const o=JSON.stringify(s);o.length>1e3?(y.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=s}catch(o){y.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${i}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const i=this.client.getServerConfig(s);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),r[s]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){y.warn(`Failed to get config for server '${s}': ${i}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const i=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof fe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,r,s,i);const o=this.stream(e,n,r,s,i);return this._consumeAndReturn(o)}async*stream(e,n,r=!0,s,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,r,s,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const S=this.serverManager.tools,m=new Set(S.map(v=>v.name)),w=new Set(this._tools.map(v=>v.name));(m.size!==w.size||[...m].some(v=>!w.has(v)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const S of h)(this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S))&&d.push(S);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");y.info(`💬 Received query: '${f}'`),y.info("🏁 Starting agent execution");const g=3;let p=0;const C=[...d,new fe(e)];for(;p<=g;){const S={messages:C};let m=!1;const w=await this._agentExecutor.stream(S,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const v of w){for(const[k,x]of Object.entries(v))if(y.debug(`📦 Node '${k}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let b=x.messages;Array.isArray(b)||(b=[b]);for(const _ of b)C.includes(_)||C.push(_);for(const _ of b){if("tool_calls"in _&&Array.isArray(_.tool_calls)&&_.tool_calls.length>0)for(const M of _.tool_calls){const E=M.name||"unknown",P=M.args||{};this.toolsUsedNames.push(E),u++;let I=JSON.stringify(P);I.length>100&&(I=`${I.slice(0,97)}...`),y.info(`🔧 Tool call: ${E} with input: ${I}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(_)){const M=_.content;let E=String(M);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),y.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,I=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(I.size!==V.size||[...I].some(X=>!V.has(X))){y.info(`🔄 Tools changed during execution. New tools: ${[...I].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,y.info(`🔃 Restarting execution with updated tools (restart ${p}/${g})`);break}}}this._isAIMessageLike(_)&&!this._messageHasToolCalls(_)&&(c=this._normalizeOutput(this._getMessageContent(_)),y.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>g){y.warn(`⚠️ Max restarts (${g}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const S=C.slice(d.length);for(const m of S)this.addToHistory(m)}if(i&&c)try{y.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(S)}`)),y.info("✅ Structured output successful"),l=!0,S}catch(S){throw y.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw y.error(`❌ Error running query: ${h}`),o&&r&&(y.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,g=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:g.length,toolsAvailableNames:g.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),r&&!this.client&&o&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new mt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,i){const{prettyStreamEvents:o}=await an(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-D-XhkzNF.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,r,s,i)))yield;return a}async*streamEvents(e,n,r=!0,s,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);y.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new fe({content:e})));const g=s??this.conversationHistory,p=[];for(const m of g)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):y.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const C=[...p,new fe(e)];y.info("callbacks",this.callbacks);const S=d.streamEvents({messages:C},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const m of S)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const v=this._normalizeOutput(w.content);h+=v,y.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){y.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,v=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,v=x,x});let k=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(k++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${k*2}s)`,elapsed:k*2}});if(v)throw v;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(w)}`)),y.info("✅ Structured output successful"))}catch(m){y.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new O(h));console.log(`
375
+ `,jt,Zm=(jt=class{static getPackageVersion(){return xl()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Dm({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new mt,this.telemetry=ti.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Vi({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new mt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Rm(this.client,this.adapter)}else this.adapter=e.adapter??new mt(this.disallowedTools);if(this.telemetry=ti.getInstance(),this.llm){const[n,r]=Ml(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Vi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:j(()=>this.getMetadata(),"metadataProvider"),tagsProvider:j(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:j(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:j(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:j(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}y.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await mt.createTools(this.client),y.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Um;this.systemMessage=vl(e,n,Fm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof be))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[gl({runLimit:this.maxSteps})],s=il({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new be(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof be)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new mt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const i=r.replace(/[^\w-]/g,"_");if(s==null)n[i]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[i]=s;else if(Array.isArray(s)){const o=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof s=="object")try{const o=JSON.stringify(s);o.length>1e3?(y.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=s}catch(o){y.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${i}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const i=this.client.getServerConfig(s);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),r[s]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){y.warn(`Failed to get config for server '${s}': ${i}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const i=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof fe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,r,s,i);const o=this.stream(e,n,r,s,i);return this._consumeAndReturn(o)}async*stream(e,n,r=!0,s,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,r,s,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const S=this.serverManager.tools,m=new Set(S.map(v=>v.name)),w=new Set(this._tools.map(v=>v.name));(m.size!==w.size||[...m].some(v=>!w.has(v)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const S of h)(this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S))&&d.push(S);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");y.info(`💬 Received query: '${f}'`),y.info("🏁 Starting agent execution");const g=3;let p=0;const C=[...d,new fe(e)];for(;p<=g;){const S={messages:C};let m=!1;const w=await this._agentExecutor.stream(S,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const v of w){for(const[k,x]of Object.entries(v))if(y.debug(`📦 Node '${k}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let b=x.messages;Array.isArray(b)||(b=[b]);for(const _ of b)C.includes(_)||C.push(_);for(const _ of b){if("tool_calls"in _&&Array.isArray(_.tool_calls)&&_.tool_calls.length>0)for(const M of _.tool_calls){const E=M.name||"unknown",P=M.args||{};this.toolsUsedNames.push(E),u++;let I=JSON.stringify(P);I.length>100&&(I=`${I.slice(0,97)}...`),y.info(`🔧 Tool call: ${E} with input: ${I}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(_)){const M=_.content;let E=String(M);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),y.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,I=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(I.size!==V.size||[...I].some(X=>!V.has(X))){y.info(`🔄 Tools changed during execution. New tools: ${[...I].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,y.info(`🔃 Restarting execution with updated tools (restart ${p}/${g})`);break}}}this._isAIMessageLike(_)&&!this._messageHasToolCalls(_)&&(c=this._normalizeOutput(this._getMessageContent(_)),y.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>g){y.warn(`⚠️ Max restarts (${g}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const S=C.slice(d.length);for(const m of S)this.addToHistory(m)}if(i&&c)try{y.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(S)}`)),y.info("✅ Structured output successful"),l=!0,S}catch(S){throw y.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw y.error(`❌ Error running query: ${h}`),o&&r&&(y.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,g=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:g.length,toolsAvailableNames:g.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),r&&!this.client&&o&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new mt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,i){const{prettyStreamEvents:o}=await an(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-C_3SaotY.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,r,s,i)))yield;return a}async*streamEvents(e,n,r=!0,s,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);y.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new fe({content:e})));const g=s??this.conversationHistory,p=[];for(const m of g)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):y.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const C=[...p,new fe(e)];y.info("callbacks",this.callbacks);const S=d.streamEvents({messages:C},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const m of S)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const v=this._normalizeOutput(w.content);h+=v,y.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){y.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,v=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,v=x,x});let k=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(k++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${k*2}s)`,elapsed:k*2}});if(v)throw v;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(w)}`)),y.info("✅ Structured output successful"))}catch(m){y.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new O(h));console.log(`
376
376
 
377
377
  `),y.info(`🎉 StreamEvents complete - ${c} events emitted`),l=!0}catch(d){throw y.error(`❌ Error during streamEvents: ${d}`),o&&r&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),d}finally{const d=Date.now()-a;let f=0;this.client?f=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(f=this.connectors.length);const g=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:f,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:d,errorType:l?null:"streaming_error",conversationHistoryLength:g}),r&&!this.client&&o&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,i="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Pn(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const o=Pn(r),{$schema:a,additionalProperties:l,...c}=o;i=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${i}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){y.info(`🔄 Structured output attempt ${f}/${h}`);let g=`
378
378
  Please format the following information according to the EXACT schema specified below.
@@ -405,4 +405,4 @@ ${g}`);const C=await s.stream(g);let S=null,m=0;for await(const v of C){if(m++,y
405
405
 
406
406
  Make sure you gather ALL the required information during your task execution.
407
407
  If any required information is missing, continue working to find it.
408
- `}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},j(jt,"MCPAgent"),jt),Z={},Vm=Z.MCP_USE_LANGFUSE?.toLowerCase()==="false",wn={handler:null,client:null,initPromise:null};async function Qs(t,e,n,r){try{const s=await an(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){y.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:i}=s,u=class u extends i{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,g,p,C){super(d),this.agentId=f,this.metadata=g,this.metadataProvider=p,this.tagsProvider=C,this.verbose=d?.verbose??!1}async handleChainStart(d,f,g,p,C,S,m,w){y.debug("Langfuse: Chain start intercepted");const v=this.getCustomTags(),k=this.getMetadata(),x=[...C||[],...v],b={...S||{},...k};return this.verbose&&(y.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(x)}`),y.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(b)}`)),super.handleChainStart(d,f,g,p,x,b,m,w)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const g=this.tagsProvider();g&&g.length>0&&d.push(...g)}return d}getMetadata(){const d={},f=this.getEnvironmentTag();if(f&&(d.env=f),this.agentId&&(d.agent_id=this.agentId),this.metadata&&Object.assign(d,this.metadata),this.metadataProvider){const g=this.metadataProvider();g&&Object.assign(d,g)}return d}getEnvironmentTag(){const d=Z.MCP_USE_AGENT_ENV;if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return y.debug("Langfuse: LLM start intercepted"),this.verbose&&y.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return y.debug("Langfuse: Tool start intercepted"),this.verbose&&y.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return y.debug("Langfuse: Retriever start intercepted"),this.verbose&&y.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return y.debug("Langfuse: Agent action intercepted"),this.verbose&&y.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return y.debug("Langfuse: Agent end intercepted"),this.verbose&&y.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};j(u,"LoggingCallbackHandler");let o=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||Z.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Z.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Z.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Z.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Z.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Z.LANGFUSE_ENABLED!=="false",traceName:a.trace_name||Z.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:l.length>0?l:void 0,metadata:a||void 0};y.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),wn.handler=new o(c,t,e,n,r),y.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await an(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;wn.client=new d({publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||"https://cloud.langfuse.com"}),y.debug("Langfuse client initialized")}}catch(h){y.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){y.debug(`Langfuse initialization error: ${s}`)}}j(Qs,"initializeLangfuse");Vm?y.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Z.LANGFUSE_PUBLIC_KEY||!Z.LANGFUSE_SECRET_KEY?y.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):wn.initPromise=Qs();var Bm=j(()=>wn.handler,"langfuseHandler"),zm=j(()=>wn.initPromise,"langfuseInitPromise");const Bi=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Qs,langfuseHandler:Bm,langfuseInitPromise:zm},Symbol.toStringTag,{value:"Module"}));export{km as BaseAdapter,tg as BaseConnector,ng as BrowserOAuthClientProvider,rg as HttpConnector,mt as LangChainAdapter,sg as Logger,Zm as MCPAgent,ig as MCPClient,og as MCPSession,Vi as ObservabilityManager,Dm as RemoteAgent,ag as VERSION,lg as WebSocketConnector,lu as createReadableStreamFromGenerator,xl as getPackageVersion,y as logger,cg as onMcpAuthorization,au as streamEventsToAISDK,cu as streamEventsToAISDKWithTools};
408
+ `}catch(r){return y.warn(`Could not extract schema details: ${r}`),e}}},j(jt,"MCPAgent"),jt),Z={},Vm=Z.MCP_USE_LANGFUSE?.toLowerCase()==="false",wn={handler:null,client:null,initPromise:null};async function Qs(t,e,n,r){try{const s=await an(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){y.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:i}=s,u=class u extends i{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,g,p,C){super(d),this.agentId=f,this.metadata=g,this.metadataProvider=p,this.tagsProvider=C,this.verbose=d?.verbose??!1}async handleChainStart(d,f,g,p,C,S,m,w){y.debug("Langfuse: Chain start intercepted");const v=this.getCustomTags(),k=this.getMetadata(),x=[...C||[],...v],b={...S||{},...k};return this.verbose&&(y.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(x)}`),y.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(b)}`)),super.handleChainStart(d,f,g,p,x,b,m,w)}getCustomTags(){const d=[],f=this.getEnvironmentTag();if(f&&d.push(`env:${f}`),this.agentId&&d.push(`agent_id:${this.agentId}`),this.tagsProvider){const g=this.tagsProvider();g&&g.length>0&&d.push(...g)}return d}getMetadata(){const d={},f=this.getEnvironmentTag();if(f&&(d.env=f),this.agentId&&(d.agent_id=this.agentId),this.metadata&&Object.assign(d,this.metadata),this.metadataProvider){const g=this.metadataProvider();g&&Object.assign(d,g)}return d}getEnvironmentTag(){const d=Z.MCP_USE_AGENT_ENV;if(!d)return"unknown";const f=d.toLowerCase();return f==="local"||f==="development"?"local":f==="production"||f==="prod"?"production":f==="staging"||f==="stage"?"staging":f==="hosted"||f==="cloud"?"hosted":f.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...d){return y.debug("Langfuse: LLM start intercepted"),this.verbose&&y.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return y.debug("Langfuse: Tool start intercepted"),this.verbose&&y.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return y.debug("Langfuse: Retriever start intercepted"),this.verbose&&y.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return y.debug("Langfuse: Agent action intercepted"),this.verbose&&y.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return y.debug("Langfuse: Agent end intercepted"),this.verbose&&y.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};j(u,"LoggingCallbackHandler");let o=u;const a=e||(n?n():{}),l=r?r():[],c={publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||Z.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Z.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Z.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Z.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Z.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Z.LANGFUSE_ENABLED!=="false",traceName:a.trace_name||Z.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:l.length>0?l:void 0,metadata:a||void 0};y.debug("Langfuse handler config:",JSON.stringify({traceName:c.traceName,sessionId:c.sessionId,userId:c.userId,tags:c.tags},null,2)),wn.handler=new o(c,t,e,n,r),y.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await an(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;wn.client=new d({publicKey:Z.LANGFUSE_PUBLIC_KEY,secretKey:Z.LANGFUSE_SECRET_KEY,baseUrl:Z.LANGFUSE_HOST||"https://cloud.langfuse.com"}),y.debug("Langfuse client initialized")}}catch(h){y.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){y.debug(`Langfuse initialization error: ${s}`)}}j(Qs,"initializeLangfuse");Vm?y.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Z.LANGFUSE_PUBLIC_KEY||!Z.LANGFUSE_SECRET_KEY?y.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):wn.initPromise=Qs();var Bm=j(()=>wn.handler,"langfuseHandler"),zm=j(()=>wn.initPromise,"langfuseInitPromise");const Bi=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:Qs,langfuseHandler:Bm,langfuseInitPromise:zm},Symbol.toStringTag,{value:"Module"}));export{km as BaseAdapter,tg as BaseConnector,ng as BrowserOAuthClientProvider,rg as BrowserTelemetry,sg as HttpConnector,mt as LangChainAdapter,ig as Logger,Zm as MCPAgent,og as MCPClient,ag as MCPSession,Vi as ObservabilityManager,Dm as RemoteAgent,lg as Tel,ti as Telemetry,cg as VERSION,ug as WebSocketConnector,lu as createReadableStreamFromGenerator,xl as getPackageVersion,y as logger,hg as onMcpAuthorization,dg as setBrowserTelemetrySource,fg as setTelemetrySource,au as streamEventsToAISDK,cu as streamEventsToAISDKWithTools};
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-bfSXqRHx.js","assets/index-mfl-FSxP.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
2
- import{_ as a,a as k}from"./index-mfl-FSxP.js";var y=null,L=null,O=null,J=!1,V=typeof process<"u"&&process.versions?.node;(async()=>{if(V)try{O=(await k(()=>import("./util-t-trnxQI.js").then(e=>e.u),[])).stripVTControlCharacters}catch{}try{y=(await k(()=>import("./index-JiKw9JSs.js"),[])).default}catch{}try{L=(await k(()=>import("./index-bfSXqRHx.js").then(e=>e.i),__vite__mapDeps([0,1,2]))).highlight}catch{}V&&(!y||!L)&&(J||(J=!0,console.warn(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BRR1ewVe.js","assets/index-IsrJH759.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
2
+ import{_ as a,a as k}from"./index-IsrJH759.js";var y=null,L=null,O=null,J=!1,V=typeof process<"u"&&process.versions?.node;(async()=>{if(V)try{O=(await k(()=>import("./util-t-trnxQI.js").then(e=>e.u),[])).stripVTControlCharacters}catch{}try{y=(await k(()=>import("./index-JiKw9JSs.js"),[])).default}catch{}try{L=(await k(()=>import("./index-BRR1ewVe.js").then(e=>e.i),__vite__mapDeps([0,1,2]))).highlight}catch{}V&&(!y||!L)&&(J||(J=!0,console.warn(`
3
3
  ✨ For enhanced console output with colors and syntax highlighting, install:
4
4
 
5
5
  npm install chalk cli-highlight
@@ -1 +1 @@
1
- import{_ as c,A as d}from"./index-BvWxscWX.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var _={};c(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};export{h as E,l as c,_ as e};
1
+ import{_ as c,A as d}from"./index-D4BJ-4dv.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var _={};c(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};export{h as E,l as c,_ as e};