@mcp-use/inspector 0.13.0-canary.18 → 0.13.0-canary.19

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.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-D6vc2Rzl.js","assets/index-JEpQCCTw.js","assets/index-DQ7i0BFM.css"])))=>i.map(i=>d[i]);
2
- import{_ as A,g as Ml,c as Al,J as Pl,E as Ol,F as $i,T as Nl,G as m,M as Il,H as $l,I as Ri,a as Jt,K as Rl,L as Io,N as jl,o as we,s as Or,O as Ee,Z as Ur,j as Vr,e as Ll,n as Fl,d as Dl,P as Ul,Q as Vl,S as Bl,p as ji,U as Br,V as $o,k as Hn}from"./index-JEpQCCTw.js";import{W as Jy,X as Yy,Y as Xy,a0 as Zy,a1 as Qy,a2 as ew,a2 as tw}from"./index-JEpQCCTw.js";import{a as zr,r as zl}from"./fs-u42MReIY.js";import{a as Hl}from"./path-MNZaYwxc.js";import{r as Li,a as Fi}from"./path-DImnYYhy.js";import{D as Wn,S as Nr,t as Wl,a as Di,T as ql,b as Kl}from"./index-Bp167cgV.js";import{h as Nn,s as Gl,k as Jl,I as Yl,C as Xl,g as Ui,d as Zl,l as Ql,m as eu,t as tu,n as nu,o as ru,p as su,q as ou,r as iu,u as au,v as cu,w as lu,x as uu,y as hu,R as du,z as fu,e as pu}from"./index-BlTsCqBl.js";import{aT as mu,aU as Xs,aV as gu,aw as Oe,e as dn,aW as yu,aX as _n,a4 as fe,y as xe,aY as Vi,i as wu,aZ as vs,g as J,aj as an,ah as pe,B as N,S as Q,p as vu,C as _u,a_ as bu,aE as Bi,a$ as be,al as bn,b0 as gn,F as zi,z as je,b1 as Zs,u as Ro,D as _s,E as Yt,ap as Xt,b2 as Su,b3 as Cu,b4 as Eu,b5 as Tu,b6 as xu,b7 as ku,b8 as Mu,b9 as Au,ba as Pu,bb as Ou,bc as Nu,bd as Iu,be as $u,bf as Ru,bg as ju,bh as Lu,bi as Fu,L as Du,bj as Uu,bk as Vu,bl as Bu,A as Ve,k as yn,m as De,M as rt,at as Zt,bm as zu,H as Hu,aF as jo,au as Wu,bn as Lo,bo as Fo,af as Qs,ae as Do,ad as bs,ag as qu,V as Ku,a9 as eo,ac as Xe,bp as hr,o as z,bq as ce,br as Gu,bs as Ie,bt as xt,bu as Ju,bv as to,f as U,aa as Yu,r as Xu,T as Zu,bw as dr,bx as He,by as V,bz as Hi,s as ne,ab as Qu,bA as qn,bB as Wi,bC as Qt,bD as Sn,bE as fr,bF as pr,bG as eh,aP as th,aN as nh,aM as rh,bH as sh}from"./index-DDtG6uBj.js";import{E as qi,c as oh,e as ih}from"./embeddings-BON0Gj74.js";import{L as Ki,o as ah,l as ch}from"./llms-u9DMr6Pm.js";import"./index-DRz5BQNA.js";var Hr,Ln,Wr=0,qr=0;function lh(t,e,n){var r=0,s=e||new Array(16);t=t||{};var o=t.node,i=t.clockseq;if(t._v6||(o||(o=Hr),i==null&&(i=Ln)),o==null||i==null){var a=t.random||(t.rng||mu)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Hr&&!t._v6&&(o[0]|=1,Hr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Ln===void 0&&!t._v6&&(Ln=i))}var c=t.msecs!==void 0?t.msecs:Date.now(),l=t.nsecs!==void 0?t.nsecs:qr+1,u=c-Wr+(l-qr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||c>Wr)&&t.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Wr=c,qr=l,Ln=i,c+=122192928e5;var h=((c&268435455)*1e4+l)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=c/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++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||Xs(s)}function uh(t){var e=typeof t=="string"?gu(t):t,n=hh(e);return typeof t=="string"?Xs(n):n}function hh(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 Uo(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 Vo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Uo(Object(n),!0).forEach(function(r){dh(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Uo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function dh(t,e,n){return(e=fh(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function fh(t){var e=ph(t,"string");return typeof e=="symbol"?e:e+""}function ph(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 mh(t={},e,n=0){var r=lh(Vo(Vo({},t),{},{_v6:!0}),new Uint8Array(16));return r=uh(r),Xs(r)}async function*gh(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)}}A(gh,"streamEventsToAISDK");function yh(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}A(yh,"createReadableStreamFromGenerator");async function*wh(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-DO2Oxxrw.js","assets/index-kDTO4Twg.js","assets/index-DQ7i0BFM.css"])))=>i.map(i=>d[i]);
2
+ import{_ as A,g as Ml,c as Al,J as Pl,E as Ol,F as $i,T as Nl,G as m,M as Il,H as $l,I as Ri,a as Jt,K as Rl,L as Io,N as jl,o as we,s as Or,O as Ee,Z as Ur,j as Vr,e as Ll,n as Fl,d as Dl,P as Ul,Q as Vl,S as Bl,p as ji,U as Br,V as $o,k as Hn}from"./index-kDTO4Twg.js";import{W as Jy,X as Yy,Y as Xy,a0 as Zy,a1 as Qy,a2 as ew,a2 as tw}from"./index-kDTO4Twg.js";import{a as zr,r as zl}from"./fs-u42MReIY.js";import{a as Hl}from"./path-MNZaYwxc.js";import{r as Li,a as Fi}from"./path-BChWcjOf.js";import{D as Wn,S as Nr,t as Wl,a as Di,T as ql,b as Kl}from"./index-BuYBGFlF.js";import{h as Nn,s as Gl,k as Jl,I as Yl,C as Xl,g as Ui,d as Zl,l as Ql,m as eu,t as tu,n as nu,o as ru,p as su,q as ou,r as iu,u as au,v as cu,w as lu,x as uu,y as hu,R as du,z as fu,e as pu}from"./index-CfKE-Cf4.js";import{aT as mu,aU as Xs,aV as gu,aw as Oe,e as dn,aW as yu,aX as _n,a4 as fe,y as xe,aY as Vi,i as wu,aZ as vs,g as J,aj as an,ah as pe,B as N,S as Q,p as vu,C as _u,a_ as bu,aE as Bi,a$ as be,al as bn,b0 as gn,F as zi,z as je,b1 as Zs,u as Ro,D as _s,E as Yt,ap as Xt,b2 as Su,b3 as Cu,b4 as Eu,b5 as Tu,b6 as xu,b7 as ku,b8 as Mu,b9 as Au,ba as Pu,bb as Ou,bc as Nu,bd as Iu,be as $u,bf as Ru,bg as ju,bh as Lu,bi as Fu,L as Du,bj as Uu,bk as Vu,bl as Bu,A as Ve,k as yn,m as De,M as rt,at as Zt,bm as zu,H as Hu,aF as jo,au as Wu,bn as Lo,bo as Fo,af as Qs,ae as Do,ad as bs,ag as qu,V as Ku,a9 as eo,ac as Xe,bp as hr,o as z,bq as ce,br as Gu,bs as Ie,bt as xt,bu as Ju,bv as to,f as U,aa as Yu,r as Xu,T as Zu,bw as dr,bx as He,by as V,bz as Hi,s as ne,ab as Qu,bA as qn,bB as Wi,bC as Qt,bD as Sn,bE as fr,bF as pr,bG as eh,aP as th,aN as nh,aM as rh,bH as sh}from"./index-kPmN3fDk.js";import{E as qi,c as oh,e as ih}from"./embeddings-D7vUVvZ5.js";import{L as Ki,o as ah,l as ch}from"./llms-BCoxDIc3.js";import"./index-DRz5BQNA.js";var Hr,Ln,Wr=0,qr=0;function lh(t,e,n){var r=0,s=e||new Array(16);t=t||{};var o=t.node,i=t.clockseq;if(t._v6||(o||(o=Hr),i==null&&(i=Ln)),o==null||i==null){var a=t.random||(t.rng||mu)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Hr&&!t._v6&&(o[0]|=1,Hr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Ln===void 0&&!t._v6&&(Ln=i))}var c=t.msecs!==void 0?t.msecs:Date.now(),l=t.nsecs!==void 0?t.nsecs:qr+1,u=c-Wr+(l-qr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||c>Wr)&&t.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Wr=c,qr=l,Ln=i,c+=122192928e5;var h=((c&268435455)*1e4+l)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=c/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++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||Xs(s)}function uh(t){var e=typeof t=="string"?gu(t):t,n=hh(e);return typeof t=="string"?Xs(n):n}function hh(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 Uo(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 Vo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Uo(Object(n),!0).forEach(function(r){dh(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Uo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function dh(t,e,n){return(e=fh(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function fh(t){var e=ph(t,"string");return typeof e=="symbol"?e:e+""}function ph(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 mh(t={},e,n=0){var r=lh(Vo(Vo({},t),{},{_v6:!0}),new Uint8Array(16));return r=uh(r),Xs(r)}async function*gh(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)}}A(gh,"streamEventsToAISDK");function yh(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}A(yh,"createReadableStreamFromGenerator");async function*wh(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}
@@ -465,7 +465,7 @@ You can then use these server-specific tools in subsequent steps.
465
465
  Here are the tools *currently* available to you (this list includes server management tools and will
466
466
  change when you connect to a server):
467
467
  {tool_descriptions}
468
- `;function ur(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}A(ur,"normalizeRunOptions");var Gt,qy=(Gt=class{static getPackageVersion(){return $i()}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;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new xy({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 vt,this.telemetry=Br.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Ni({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(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],m.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(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.isSimplifiedMode)this.adapter=e.adapter??new vt(this.disallowedTools),this.telemetry=Br.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new vt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Oi(this.client,this.adapter)}else this.adapter=e.adapter??new vt(this.disallowedTools);if(this.telemetry=Br.getInstance(),this.llm){const[r,s]=$o(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Ni({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:A(()=>this.getMetadata(),"metadataProvider"),tagsProvider:A(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:A(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:A(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:A(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(m.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(m.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig&&(m.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`),this.client=new Zh({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")),this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await El(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=$o(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new Oi(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&m.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),m.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(),m.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(m.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),m.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]),m.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],m.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{m.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),m.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}m.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),m.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),m.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Ay;this.systemMessage=kl(e,n,Py,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(o=>o.name);m.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[_l({runLimit:this.maxSteps})],s=ll({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return m.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(),m.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new vt(this.disallowedTools),this._initialized&&m.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},m.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])],m.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){m.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(m.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){m.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else m.warn(`Unsupported metadata value type for key '${o}': ${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 o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){m.warn(`Failed to get config for server '${s}': ${o}`),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){m.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 o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)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 pe)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 N||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,o){const{query:i,maxSteps:a,manageConnector:c,externalHistory:l,outputSchema:u}=ur(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,c,l,u);const h=this.stream(i,a,c,l,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:c,externalHistory:l,outputSchema:u}=ur(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,c,l,u);let h=!1;const d=Date.now();let f=!1,g=null,p=0;try{if(c&&!this._initialized?(await this.initialize(),h=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),h=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const T=this.serverManager.tools,v=new Set(T.map(x=>x.name)),S=new Set(this._tools.map(x=>x.name));(v.size!==S.size||[...v].some(x=>!S.has(x)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...v].join(", ")}`),this._tools=T,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const b=l??this.conversationHistory,C=[];for(const T of b)(this._isHumanMessageLike(T)||this._isAIMessageLike(T)||this._isToolMessageLike(T))&&C.push(T);const y=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");m.info(`💬 Received query: '${y}'`),m.info("🏁 Starting agent execution");const _=3;let w=0;const E=[...C,new pe(i)];for(;w<=_;){const T={messages:E};let v=!1;const S=await this._agentExecutor.stream(T,{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 x of S){for(const[M,P]of Object.entries(x))if(m.debug(`📦 Node '${M}' output: ${JSON.stringify(P)}`),P&&typeof P=="object"&&"messages"in P){let I=P.messages;Array.isArray(I)||(I=[I]);for(const j of I)E.includes(j)||E.push(j);for(const j of I){if("tool_calls"in j&&Array.isArray(j.tool_calls)&&j.tool_calls.length>0)for(const ee of j.tool_calls){const re=ee.name||"unknown",Se=ee.args||{};this.toolsUsedNames.push(re),p++;let Me=JSON.stringify(Se);Me.length>100&&(Me=`${Me.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${Me}`),yield{action:{tool:re,toolInput:Se,log:`Calling tool ${re}`},observation:""}}if(this._isToolMessageLike(j)){const ee=j.content;let re=String(ee);if(re.length>100&&(re=`${re.slice(0,97)}...`),re=re.replace(/\n/g," "),m.info(`📄 Tool result: ${re}`),this.useServerManager&&this.serverManager){const Se=this.serverManager.tools,Me=new Set(Se.map(un=>un.name)),jn=new Set(this._tools.map(un=>un.name));if(Me.size!==jn.size||[...Me].some(un=>!jn.has(un))){m.info(`🔄 Tools changed during execution. New tools: ${[...Me].join(", ")}`),this._tools=Se,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),v=!0,w++,m.info(`🔃 Restarting execution with updated tools (restart ${w}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(v)break}if(v)break}if(!v)break;if(w>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const T=E.slice(C.length);for(const v of T)this.addToHistory(v)}if(u&&g)try{m.info("🔧 Attempting structured output...");const T=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"),f=!0,T}catch(T){throw m.error(`❌ Structured output failed: ${T}`),new Error(`Failed to generate structured output: ${T instanceof Error?T.message:String(T)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(b){throw m.error(`❌ Error running query: ${b}`),h&&c&&(m.info("🧹 Cleaning up resources after error"),await this.close()),b}finally{const b=Date.now()-d;let C=0;this.client?C=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(C=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0,_=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:c??!0,externalHistoryUsed:l!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:b,errorType:f?null:"execution_error",conversationHistoryLength:y}),c&&!this.client&&h&&(m.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(m.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}m.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(m.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(m.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)m.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(m.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new vt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Jt(async()=>{const{prettyStreamEvents:c}=await import("./display-A5IEINAP-D6vc2Rzl.js");return{prettyStreamEvents:c}},__vite__mapDeps([0,1,2])),a="";for await(const c of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=ur(e,n,r,s,o);let{query:a}=i;const{maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let g=!1,p=0,b=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{l&&!this._initialized?(await this.initialize(),d=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),d=!0);const y=this._agentExecutor;if(!y)throw new Error("MCP agent failed to initialize");this.maxSteps=c??this.maxSteps;const _=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);m.info(`💬 Received query for streamEvents: '${_}'`),this.memoryEnabled&&(m.info(`🔄 Adding user message to history: ${_}`),this.addToHistory(new pe({content:a})));const w=u??this.conversationHistory,E=[];for(const S of w)this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S)?E.push(S):m.info(`⚠️ Skipped message of type: ${S.constructor?.name||typeof S}`);const T=[...E,new pe(a)];m.info("callbacks",this.callbacks);const v=y.streamEvents({messages:T},{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 S of v)if(p++,!(!S||typeof S!="object")){if(S.event==="on_chat_model_stream"&&S.data?.chunk?.content&&(b+=S.data.chunk.content.length),S.event==="on_chat_model_stream"&&S.data?.chunk){const x=S.data.chunk;if(x.content){C||(C="");const M=this._normalizeOutput(x.content);C+=M,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!C){const x=S.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?C=x[0].text:typeof x=="string"?C=x:x&&typeof x=="object"&&"output"in x&&(C=x.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let S=!1,x=null,M=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(S=!0,x=I,I)).catch(I=>{throw S=!0,M=I,I});let P=0;for(;!S;)await new Promise(I=>setTimeout(I,2e3)),S||(P++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${P*2}s)`,elapsed:P*2}});if(M)throw M;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(x)}`)),m.info("✅ Structured output successful"))}catch(S){m.warn(`⚠️ Structured output failed: ${S}`),yield{event:"on_structured_output_error",data:{error:S instanceof Error?S.message:String(S)}}}}else this.memoryEnabled&&C&&this.addToHistory(new N(C));console.log(`
468
+ `;function ur(t,e,n,r,s){if(typeof t=="object"&&t!==null){const o=t;return{query:o.prompt,maxSteps:o.maxSteps,manageConnector:o.manageConnector,externalHistory:o.externalHistory,outputSchema:o.schema}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s}}A(ur,"normalizeRunOptions");var Gt,qy=(Gt=class{static getPackageVersion(){return $i()}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;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new xy({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 vt,this.telemetry=Br.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Ni({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(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],m.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(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.isSimplifiedMode)this.adapter=e.adapter??new vt(this.disallowedTools),this.telemetry=Br.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new vt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Oi(this.client,this.adapter)}else this.adapter=e.adapter??new vt(this.disallowedTools);if(this.telemetry=Br.getInstance(),this.llm){const[r,s]=$o(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Ni({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:A(()=>this.getMetadata(),"metadataProvider"),tagsProvider:A(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:A(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:A(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:A(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(m.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(m.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig&&(m.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`),this.client=new Zh({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")),this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await El(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=$o(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new Oi(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&m.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),m.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(),m.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(m.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),m.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]),m.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=await this.adapter.createToolsFromConnectors(Object.values(this.sessions).map(a=>a.connector)),o=await this.adapter.createResourcesFromConnectors(Object.values(this.sessions).map(a=>a.connector)),i=await this.adapter.createPromptsFromConnectors(Object.values(this.sessions).map(a=>a.connector));this._tools=[...s,...o,...i],m.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${s.length} tools, ${o.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{m.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),m.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}m.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),m.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),m.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Ay;this.systemMessage=kl(e,n,Py,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(o=>o.name);m.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[_l({runLimit:this.maxSteps})],s=ll({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return m.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(),m.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new vt(this.disallowedTools),this._initialized&&m.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},m.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])],m.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){m.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(m.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){m.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else m.warn(`Unsupported metadata value type for key '${o}': ${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 o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){m.warn(`Failed to get config for server '${s}': ${o}`),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){m.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 o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)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 pe)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 N||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,o){const{query:i,maxSteps:a,manageConnector:c,externalHistory:l,outputSchema:u}=ur(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,c,l,u);const h=this.stream(i,a,c,l,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:c,externalHistory:l,outputSchema:u}=ur(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,c,l,u);let h=!1;const d=Date.now();let f=!1,g=null,p=0;try{if(c&&!this._initialized?(await this.initialize(),h=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),h=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const T=this.serverManager.tools,v=new Set(T.map(x=>x.name)),S=new Set(this._tools.map(x=>x.name));(v.size!==S.size||[...v].some(x=>!S.has(x)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...v].join(", ")}`),this._tools=T,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const b=l??this.conversationHistory,C=[];for(const T of b)(this._isHumanMessageLike(T)||this._isAIMessageLike(T)||this._isToolMessageLike(T))&&C.push(T);const y=i.length>50?`${i.slice(0,50).replace(/\n/g," ")}...`:i.replace(/\n/g," ");m.info(`💬 Received query: '${y}'`),m.info("🏁 Starting agent execution");const _=3;let w=0;const E=[...C,new pe(i)];for(;w<=_;){const T={messages:E};let v=!1;const S=await this._agentExecutor.stream(T,{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 x of S){for(const[M,P]of Object.entries(x))if(m.debug(`📦 Node '${M}' output: ${JSON.stringify(P)}`),P&&typeof P=="object"&&"messages"in P){let I=P.messages;Array.isArray(I)||(I=[I]);for(const j of I)E.includes(j)||E.push(j);for(const j of I){if("tool_calls"in j&&Array.isArray(j.tool_calls)&&j.tool_calls.length>0)for(const ee of j.tool_calls){const re=ee.name||"unknown",Se=ee.args||{};this.toolsUsedNames.push(re),p++;let Me=JSON.stringify(Se);Me.length>100&&(Me=`${Me.slice(0,97)}...`),m.info(`🔧 Tool call: ${re} with input: ${Me}`),yield{action:{tool:re,toolInput:Se,log:`Calling tool ${re}`},observation:""}}if(this._isToolMessageLike(j)){const ee=j.content;let re=String(ee);if(re.length>100&&(re=`${re.slice(0,97)}...`),re=re.replace(/\n/g," "),m.info(`📄 Tool result: ${re}`),this.useServerManager&&this.serverManager){const Se=this.serverManager.tools,Me=new Set(Se.map(un=>un.name)),jn=new Set(this._tools.map(un=>un.name));if(Me.size!==jn.size||[...Me].some(un=>!jn.has(un))){m.info(`🔄 Tools changed during execution. New tools: ${[...Me].join(", ")}`),this._tools=Se,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),v=!0,w++,m.info(`🔃 Restarting execution with updated tools (restart ${w}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(v)break}if(v)break}if(!v)break;if(w>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const T=E.slice(C.length);for(const v of T)this.addToHistory(v)}if(u&&g)try{m.info("🔧 Attempting structured output...");const T=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"),f=!0,T}catch(T){throw m.error(`❌ Structured output failed: ${T}`),new Error(`Failed to generate structured output: ${T instanceof Error?T.message:String(T)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(b){throw m.error(`❌ Error running query: ${b}`),h&&c&&(m.info("🧹 Cleaning up resources after error"),await this.close()),b}finally{const b=Date.now()-d;let C=0;this.client?C=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(C=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0,_=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:i,success:f,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:C,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:c??!0,externalHistoryUsed:l!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:b,errorType:f?null:"execution_error",conversationHistoryLength:y}),c&&!this.client&&h&&(m.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(m.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}m.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(m.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(m.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)m.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(m.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new vt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Jt(async()=>{const{prettyStreamEvents:c}=await import("./display-A5IEINAP-DO2Oxxrw.js");return{prettyStreamEvents:c}},__vite__mapDeps([0,1,2])),a="";for await(const c of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=ur(e,n,r,s,o);let{query:a}=i;const{maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let g=!1,p=0,b=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{l&&!this._initialized?(await this.initialize(),d=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),d=!0);const y=this._agentExecutor;if(!y)throw new Error("MCP agent failed to initialize");this.maxSteps=c??this.maxSteps;const _=typeof a=="string"&&a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:typeof a=="string"?a.replace(/\n/g," "):String(a);m.info(`💬 Received query for streamEvents: '${_}'`),this.memoryEnabled&&(m.info(`🔄 Adding user message to history: ${_}`),this.addToHistory(new pe({content:a})));const w=u??this.conversationHistory,E=[];for(const S of w)this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S)?E.push(S):m.info(`⚠️ Skipped message of type: ${S.constructor?.name||typeof S}`);const T=[...E,new pe(a)];m.info("callbacks",this.callbacks);const v=y.streamEvents({messages:T},{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 S of v)if(p++,!(!S||typeof S!="object")){if(S.event==="on_chat_model_stream"&&S.data?.chunk?.content&&(b+=S.data.chunk.content.length),S.event==="on_chat_model_stream"&&S.data?.chunk){const x=S.data.chunk;if(x.content){C||(C="");const M=this._normalizeOutput(x.content);C+=M,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!C){const x=S.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?C=x[0].text:typeof x=="string"?C=x:x&&typeof x=="object"&&"output"in x&&(C=x.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let S=!1,x=null,M=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(S=!0,x=I,I)).catch(I=>{throw S=!0,M=I,I});let P=0;for(;!S;)await new Promise(I=>setTimeout(I,2e3)),S||(P++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${P*2}s)`,elapsed:P*2}});if(M)throw M;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(x)}`)),m.info("✅ Structured output successful"))}catch(S){m.warn(`⚠️ Structured output failed: ${S}`),yield{event:"on_structured_output_error",data:{error:S instanceof Error?S.message:String(S)}}}}else this.memoryEnabled&&C&&this.addToHistory(new N(C));console.log(`
469
469
 
470
470
  `),m.info(`🎉 StreamEvents complete - ${p} events emitted`),g=!0}catch(y){throw m.error(`❌ Error during streamEvents: ${y}`),d&&l&&(m.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),y}finally{const y=Date.now()-f;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const w=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:a,success:g,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(E=>E.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(E=>E.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:l??!0,externalHistoryUsed:u!==void 0,response:`[STREAMED RESPONSE - ${b} chars]`,executionTimeMs:y,errorType:g?null:"streaming_error",conversationHistoryLength:w}),l&&!this.client&&d&&(m.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){m.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),m.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(m.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Hn(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 i=Hn(r),{$schema:a,additionalProperties:c,...l}=i;o=JSON.stringify(l,null,2),m.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),m.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){m.info(`🔄 Structured output attempt ${f}/${h}`);let g=`
471
471
  Please format the following information according to the EXACT schema specified below.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-KM9i0bDf.js","assets/index-JEpQCCTw.js","assets/index-DQ7i0BFM.css"])))=>i.map(i=>d[i]);
2
- import{_ as a,a as k}from"./index-JEpQCCTw.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-KM9i0bDf.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-B9kl_QA3.js","assets/index-kDTO4Twg.js","assets/index-DQ7i0BFM.css"])))=>i.map(i=>d[i]);
2
+ import{_ as a,a as k}from"./index-kDTO4Twg.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-B9kl_QA3.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{g as c,q as d}from"./index-DDtG6uBj.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 h={};c(h,{Embeddings:()=>i});var i=class{caller;constructor(r){this.caller=new d(r??{})}};export{i as E,l as c,h as e};
1
+ import{g as c,q as d}from"./index-kPmN3fDk.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 h={};c(h,{Embeddings:()=>i});var i=class{caller;constructor(r){this.caller=new d(r??{})}};export{i as E,l as c,h as e};
@@ -1,4 +1,4 @@
1
- import{g as wn,O as Ut,h as bn,c as $t,f as xn,S as Sn,J as kn,R as Bt}from"./index-BlTsCqBl.js";import{r as Tn,K as xs,t as Lt,ah as jt,I as Mn,J as On,E as N,B as qt,L as vn,y as ie,i as at,D as In,M as Rn}from"./index-DDtG6uBj.js";import{o as y,d as Wt,e as An,f as Cn,u as Dt,s as b,l as w,n as E,h as Ze,t as Mt,i as Pn,j as En}from"./index-JEpQCCTw.js";import"./index-Bp167cgV.js";import"./index-DRz5BQNA.js";var Ft=class extends wn{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const s=await Tn(this.zodSchema,e);if(s.success)return s.data;throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:a}=r;return Array.isArray(a.content)?Ss(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[s]=e;return await this._validateResult(s.args)}};function Ss(t){const e=[];for(const s of t)s.type==="tool_use"&&e.push({name:s.name,args:s.input,id:s.id,type:"tool_call"});return e}function Nn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Un=y({cache_control:Cn().optional().nullable(),defer_loading:An().optional(),input_examples:Wt(Dt()).optional(),allowed_callers:Wt(Dt()).optional()}),Ht={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function $n(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Bn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ln(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function jn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=xs({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Wn=t=>t();function Dn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Fn(t){function*e(){for(const s of t)Dn(s)&&(s.source==="char"?yield{type:"char_location",file_id:s.url??"",start_char_index:s.startIndex??0,end_char_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="page"?yield{type:"page_location",file_id:s.url??"",start_page_number:s.startIndex??0,end_page_number:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="block"?yield{type:"content_block_location",file_id:s.url??"",start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="url"?yield{type:"web_search_result_location",url:s.url??"",title:s.title??null,encrypted_index:String(s.startIndex??0),cited_text:s.citedText??""}:s.source==="search"&&(yield{type:"search_result_location",title:s.title??null,start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,search_result_index:0,source:s.source??"",cited_text:s.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Hn(t)}function Hn(t){const e=[];for(let s=0,{length:n}=t;s<n;s++)e.push(String.fromCharCode(t[s]));return btoa(e.join(""))}function it(t){return(t??"").split(";")[0].toLowerCase()}function ke(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const s=ke(e,"cache_control");s!==void 0&&(t.cache_control=s);const n=ke(e,"citations");n!==void 0&&(t.citations=n);const r=ke(e,"context");r!==void 0&&(t.context=r);const a=ke(e,"title");return a!==void 0&&(t.title=a),t}function ot(t,e){const s=ke(e,"cache_control");return s!==void 0&&(t.cache_control=s),t}function Jt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Jn(t){const e=[],s=t.response_metadata,n="model_provider"in s&&s?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Fn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const a=Wn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:a})}else if(r.type==="reasoning"&&n)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&n)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&n)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const a=r.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:a})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const a=r.metadata;if(r.fileId){e.push(Z({type:"document",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){const i=it(r.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:r.url}},a));continue}}if(r.data){const i=it(r.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(r.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},a));else if(Jt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(r.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const a=r.metadata;if(r.fileId){e.push(ot({type:"image",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){e.push(ot({type:"image",source:{type:"url",url:r.url}},a));continue}if(r.data){const i=it(r.mimeType)||"image/png";Jt(i)&&e.push(ot({type:"image",source:{type:"base64",data:oe(r.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&n&&e.push(r.value))}return e}function Kt(t){const e=xs({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let s;try{s=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
1
+ import{g as wn,O as Ut,h as bn,c as $t,f as xn,S as Sn,J as kn,R as Bt}from"./index-CfKE-Cf4.js";import{r as Tn,K as xs,t as Lt,ah as jt,I as Mn,J as On,E as N,B as qt,L as vn,y as ie,i as at,D as In,M as Rn}from"./index-kPmN3fDk.js";import{o as y,d as Wt,e as An,f as Cn,u as Dt,s as b,l as w,n as E,h as Ze,t as Mt,i as Pn,j as En}from"./index-kDTO4Twg.js";import"./index-BuYBGFlF.js";import"./index-DRz5BQNA.js";var Ft=class extends wn{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const s=await Tn(this.zodSchema,e);if(s.success)return s.data;throw new Ut(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:a}=r;return Array.isArray(a.content)?Ss(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[s]=e;return await this._validateResult(s.args)}};function Ss(t){const e=[];for(const s of t)s.type==="tool_use"&&e.push({name:s.name,args:s.input,id:s.id,type:"tool_call"});return e}function Nn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Un=y({cache_control:Cn().optional().nullable(),defer_loading:An().optional(),input_examples:Wt(Dt()).optional(),allowed_callers:Wt(Dt()).optional()}),Ht={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function $n(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Bn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ln(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function jn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=xs({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Wn=t=>t();function Dn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Fn(t){function*e(){for(const s of t)Dn(s)&&(s.source==="char"?yield{type:"char_location",file_id:s.url??"",start_char_index:s.startIndex??0,end_char_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="page"?yield{type:"page_location",file_id:s.url??"",start_page_number:s.startIndex??0,end_page_number:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="block"?yield{type:"content_block_location",file_id:s.url??"",start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,document_title:s.title??null,document_index:0,cited_text:s.citedText??""}:s.source==="url"?yield{type:"web_search_result_location",url:s.url??"",title:s.title??null,encrypted_index:String(s.startIndex??0),cited_text:s.citedText??""}:s.source==="search"&&(yield{type:"search_result_location",title:s.title??null,start_block_index:s.startIndex??0,end_block_index:s.endIndex??0,search_result_index:0,source:s.source??"",cited_text:s.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Hn(t)}function Hn(t){const e=[];for(let s=0,{length:n}=t;s<n;s++)e.push(String.fromCharCode(t[s]));return btoa(e.join(""))}function it(t){return(t??"").split(";")[0].toLowerCase()}function ke(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const s=ke(e,"cache_control");s!==void 0&&(t.cache_control=s);const n=ke(e,"citations");n!==void 0&&(t.citations=n);const r=ke(e,"context");r!==void 0&&(t.context=r);const a=ke(e,"title");return a!==void 0&&(t.title=a),t}function ot(t,e){const s=ke(e,"cache_control");return s!==void 0&&(t.cache_control=s),t}function Jt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Jn(t){const e=[],s=t.response_metadata,n="model_provider"in s&&s?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Fn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const a=Wn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:a})}else if(r.type==="reasoning"&&n)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&n)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&n)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const a=r.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:a})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const a=r.metadata;if(r.fileId){e.push(Z({type:"document",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){const i=it(r.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:r.url}},a));continue}}if(r.data){const i=it(r.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(r.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},a));else if(Jt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(r.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const a=r.metadata;if(r.fileId){e.push(ot({type:"image",source:{type:"file",file_id:r.fileId}},a));continue}if(r.url){e.push(ot({type:"image",source:{type:"url",url:r.url}},a));continue}if(r.data){const i=it(r.mimeType)||"image/png";Jt(i)&&e.push(ot({type:"image",source:{type:"base64",data:oe(r.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(Z({type:"document",source:{type:"text",data:oe(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&n&&e.push(r.value))}return e}function Kt(t){const e=xs({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let s;try{s=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
2
2
 
3
3
  `))}if(s.protocol==="http:"||s.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(s.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
4
4