@mcp-use/inspector 0.13.0-canary.13 → 0.13.0-canary.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +2 -2
- package/dist/client/assets/{browser-9Hcz8GQa.js → browser-DWTlE230.js} +10 -10
- package/dist/client/assets/{display-A5IEINAP-CDZgqATQ.js → display-A5IEINAP-BqXf1TEf.js} +2 -2
- package/dist/client/assets/{embeddings-B_c8FO0V.js → embeddings-T7SMbbwA.js} +1 -1
- package/dist/client/assets/{index-BcDWp7yL.js → index-BFDHTA3s.js} +1 -1
- package/dist/client/assets/{index-BWJOUedR.js → index-CQAG94lY.js} +1 -1
- package/dist/client/assets/{index-D6MZ_uWL.js → index-CSfP5GPL.js} +11 -11
- package/dist/client/assets/{index-D6VDHNX7.js → index-CWSqzUc_.js} +1 -1
- package/dist/client/assets/{index-COt7aP5z.js → index-Cyq-cOBe.js} +1 -1
- package/dist/client/assets/{index-CrP21sE-.js → index-D48Cm8M4.js} +1 -1
- package/dist/client/assets/{index-Q4cmml2q.js → index-DGiu3fcD.js} +1 -1
- package/dist/client/assets/{index-C7WKC4_c.js → index-JBzxP9jc.js} +1 -1
- package/dist/client/assets/{index-Dxsl-6OY.js → index-aOfNG-KD.js} +1 -1
- package/dist/client/assets/langfuse-74RGPTAH-N7gq8lpA.js +1 -0
- package/dist/client/assets/{llms-BEnmsJ6n.js → llms-UpKGGvfL.js} +1 -1
- package/dist/client/assets/{path-X6M8BSjL.js → path-DpGL3tFL.js} +1 -1
- package/dist/client/assets/{winston-CKwQ3MQO.js → winston-DrYP2ZsM.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/server/{chunk-OS2WTNLR.js → chunk-JEKCWLHD.js} +1 -1
- package/dist/server/{chunk-Z5QIR3IS.js → chunk-MCMZDGO6.js} +2 -2
- package/dist/server/{chunk-WLIY2SQG.js → chunk-XGILHZOF.js} +1 -1
- package/dist/server/cli.js +2 -2
- package/dist/server/index.js +3 -3
- package/dist/server/middleware.js +3 -3
- package/dist/server/server.js +2 -2
- package/dist/server/shared-routes.js +2 -2
- package/dist/server/shared-utils-browser.d.ts.map +1 -1
- package/dist/server/shared-utils-browser.js +1 -1
- package/package.json +2 -2
- package/dist/client/assets/langfuse-74RGPTAH-BwcKtZq0.js +0 -1
package/dist/cli.js
CHANGED
|
@@ -30,7 +30,7 @@ async function* handleChatRequestStream(requestBody) {
|
|
|
30
30
|
"Missing required fields: mcpServerUrl, llmConfig, messages"
|
|
31
31
|
);
|
|
32
32
|
}
|
|
33
|
-
const { MCPAgent, MCPClient } = await import("mcp-use");
|
|
33
|
+
const { MCPAgent, MCPClient } = await import("mcp-use/browser");
|
|
34
34
|
let llm;
|
|
35
35
|
if (llmConfig.provider === "openai") {
|
|
36
36
|
const { ChatOpenAI } = await import("@langchain/openai");
|
|
@@ -144,7 +144,7 @@ async function handleChatRequest(requestBody) {
|
|
|
144
144
|
"Missing required fields: mcpServerUrl, llmConfig, messages"
|
|
145
145
|
);
|
|
146
146
|
}
|
|
147
|
-
const { MCPAgent, MCPClient } = await import("mcp-use");
|
|
147
|
+
const { MCPAgent, MCPClient } = await import("mcp-use/browser");
|
|
148
148
|
let llm;
|
|
149
149
|
if (llmConfig.provider === "openai") {
|
|
150
150
|
const { ChatOpenAI } = await import("@langchain/openai");
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-74RGPTAH-
|
|
2
|
-
import{_ as A,
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-74RGPTAH-N7gq8lpA.js","assets/index-CSfP5GPL.js","assets/index-DQ7i0BFM.css","assets/path-MNZaYwxc.js","assets/path-DpGL3tFL.js","assets/index-Cyq-cOBe.js","assets/index-CQAG94lY.js","assets/index-JBzxP9jc.js","assets/index-DRz5BQNA.js","assets/embeddings-T7SMbbwA.js","assets/llms-UpKGGvfL.js","assets/display-A5IEINAP-BqXf1TEf.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as A,c as Ol,J as Nl,B as Il,v as eo,T as _s,w as m,M as Fi,H as Di,x as to,a as Jt,C as $l,y as Lo,z as Rl,o as we,s as Nr,A as Ee,Z as zr,j as Hr,e as jl,n as Ll,d as Fl,D as Dl,E as Ul,$ as Vl,p as Ui,F as Wn,G as Fo,k as qn,I as Bl,L as zl,K as Hl,V as Wl,N as ql,O as Do}from"./index-CSfP5GPL.js";import gn,{readFileSync as Kl}from"fs";import{a as Gl}from"./path-MNZaYwxc.js";import Jl from"child_process";import{r as Vi}from"./path-DpGL3tFL.js";import Ir from"node:process";import{PassThrough as Yl}from"node:stream";import{D as Kn,S as $r,t as Xl,a as Bi,T as Zl,b as Ql}from"./index-Cyq-cOBe.js";import{h as In,s as eu,k as tu,I as nu,C as ru,g as zi,d as su,l as ou,m as iu,t as au,n as cu,o as lu,p as uu,q as hu,r as du,u as fu,v as pu,w as mu,x as gu,y as yu,R as wu,z as vu,e as _u}from"./index-JBzxP9jc.js";import{aT as bu,aU as no,aV as Su,aw as Oe,e as dn,aW as Cu,aX as bn,a4 as fe,y as ke,aY as Hi,i as Eu,aZ as bs,g as J,aj as an,ah as pe,B as N,S as Q,p as Tu,C as ku,a_ as xu,aE as Wi,a$ as be,al as Sn,b0 as yn,F as qi,z as je,b1 as ro,u as Uo,D as Ss,E as Yt,ap as Xt,b2 as Mu,b3 as Au,b4 as Pu,b5 as Ou,b6 as Nu,b7 as Iu,b8 as $u,b9 as Ru,ba as ju,bb as Lu,bc as Fu,bd as Du,be as Uu,bf as Vu,bg as Bu,bh as zu,bi as Hu,L as Wu,bj as qu,bk as Ku,bl as Gu,A as Ve,k as wn,m as De,M as rt,at as Zt,bm as Ju,H as Yu,aF as Vo,au as Xu,bn as Bo,bo as zo,af as so,ae as Ho,ad as Cs,ag as Zu,V as Qu,a9 as oo,ac as Xe,bp as fr,o as z,bq as ce,br as eh,bs as Ie,bt as kt,bu as th,bv as io,f as U,aa as nh,r as rh,T as sh,bw as pr,bx as He,by as V,bz as Ki,s as ne,ab as oh,bA as Gn,bB as Gi,bC as Qt,bD as Cn,bE as mr,bF as gr,bG as ih,aP as ah,aN as ch,aM as lh,bH as uh}from"./index-CQAG94lY.js";import{E as Ji,c as hh,e as dh}from"./embeddings-T7SMbbwA.js";import{L as Yi,o as fh,l as ph}from"./llms-UpKGGvfL.js";var Wr,Fn,qr=0,Kr=0;function mh(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=Wr),i==null&&(i=Fn)),o==null||i==null){var a=t.random||(t.rng||bu)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Wr&&!t._v6&&(o[0]|=1,Wr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Fn===void 0&&!t._v6&&(Fn=i))}var c=t.msecs!==void 0?t.msecs:Date.now(),l=t.nsecs!==void 0?t.nsecs:Kr+1,u=c-qr+(l-Kr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||c>qr)&&t.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");qr=c,Kr=l,Fn=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||no(s)}function gh(t){var e=typeof t=="string"?Su(t):t,n=yh(e);return typeof t=="string"?no(n):n}function yh(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 Wo(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 qo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Wo(Object(n),!0).forEach(function(r){wh(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Wo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function wh(t,e,n){return(e=vh(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vh(t){var e=_h(t,"string");return typeof e=="symbol"?e:e+""}function _h(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 bh(t={},e,n=0){var r=mh(qo(qo({},t),{},{_v6:!0}),new Uint8Array(16));return r=gh(r),no(r)}async function*Xi(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(Xi,"streamEventsToAISDK");function Zi(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(Zi,"createReadableStreamFromGenerator");async function*Qi(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}
|
|
6
|
-
`;break}}A(Qi,"streamEventsToAISDKWithTools");
|
|
7
|
-
`);if(e===-1)return null;const n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
8
|
-
`}const
|
|
6
|
+
`;break}}A(Qi,"streamEventsToAISDKWithTools");const Sh={},Ch="browser",Eh="v18.0.0",Th={node:"18.0.0"},kh=()=>"/",xh=(t,...e)=>queueMicrotask(()=>t(...e)),Mh=!0,Ko={env:Sh,platform:Ch,version:Eh,versions:Th,cwd:kh,nextTick:xh,browser:Mh};var ot={exports:{}},Gr,Go;function Ah(){if(Go)return Gr;Go=1;var t={};Gr=s,s.sync=o;var e=gn;function n(i,a){var c=a.pathExt!==void 0?a.pathExt:t.PATHEXT;if(!c||(c=c.split(";"),c.indexOf("")!==-1))return!0;for(var l=0;l<c.length;l++){var u=c[l].toLowerCase();if(u&&i.substr(-u.length).toLowerCase()===u)return!0}return!1}function r(i,a,c){return!i.isSymbolicLink()&&!i.isFile()?!1:n(a,c)}function s(i,a,c){e.stat(i,function(l,u){c(l,l?!1:r(u,i,a))})}function o(i,a){return r(e.statSync(i),i,a)}return Gr}var Jr,Jo;function Ph(){if(Jo)return Jr;Jo=1,Jr=e,e.sync=n;var t=gn;function e(o,i,a){t.stat(o,function(c,l){a(c,c?!1:r(l,i))})}function n(o,i){return r(t.statSync(o),i)}function r(o,i){return o.isFile()&&s(o,i)}function s(o,i){var a=o.mode,c=o.uid,l=o.gid,u=i.uid!==void 0?i.uid:process.getuid&&process.getuid(),h=i.gid!==void 0?i.gid:process.getgid&&process.getgid(),d=parseInt("100",8),f=parseInt("010",8),g=parseInt("001",8),p=d|f,b=a&g||a&f&&l===h||a&d&&c===u||a&p&&u===0;return b}return Jr}var Yr,Yo;function Oh(){if(Yo)return Yr;Yo=1;var t;globalThis.TESTING_WINDOWS?t=Ah():t=Ph(),Yr=e,e.sync=n;function e(r,s,o){if(typeof s=="function"&&(o=s,s={}),!o){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(i,a){e(r,s||{},function(c,l){c?a(c):i(l)})})}t(r,s||{},function(i,a){i&&(i.code==="EACCES"||s&&s.ignoreErrors)&&(i=null,a=!1),o(i,a)})}function n(r,s){try{return t.sync(r,s||{})}catch(o){if(s&&s.ignoreErrors||o.code==="EACCES")return!1;throw o}}return Yr}var Xr,Xo;function Nh(){if(Xo)return Xr;Xo=1;var t={};const e=t.OSTYPE==="cygwin"||t.OSTYPE==="msys",n=Vi,r=e?";":":",s=Oh(),o=l=>Object.assign(new Error(`not found: ${l}`),{code:"ENOENT"}),i=(l,u)=>{const h=u.colon||r,d=l.match(/\//)||e&&l.match(/\\/)?[""]:[...e?[process.cwd()]:[],...(u.path||t.PATH||"").split(h)],f=e?u.pathExt||t.PATHEXT||".EXE;.CMD;.BAT;.COM":"",g=e?f.split(h):[""];return e&&l.indexOf(".")!==-1&&g[0]!==""&&g.unshift(""),{pathEnv:d,pathExt:g,pathExtExe:f}},a=(l,u,h)=>{typeof u=="function"&&(h=u,u={}),u||(u={});const{pathEnv:d,pathExt:f,pathExtExe:g}=i(l,u),p=[],b=y=>new Promise((_,w)=>{if(y===d.length)return u.all&&p.length?_(p):w(o(l));const E=d[y],T=/^".*"$/.test(E)?E.slice(1,-1):E,v=n.join(T,l),S=!T&&/^\.[\\\/]/.test(l)?l.slice(0,2)+v:v;_(C(S,y,0))}),C=(y,_,w)=>new Promise((E,T)=>{if(w===f.length)return E(b(_+1));const v=f[w];s(y+v,{pathExt:g},(S,k)=>{if(!S&&k)if(u.all)p.push(y+v);else return E(y+v);return E(C(y,_,w+1))})});return h?b(0).then(y=>h(null,y),h):b(0)},c=(l,u)=>{u=u||{};const{pathEnv:h,pathExt:d,pathExtExe:f}=i(l,u),g=[];for(let p=0;p<h.length;p++){const b=h[p],C=/^".*"$/.test(b)?b.slice(1,-1):b,y=n.join(C,l),_=!C&&/^\.[\\\/]/.test(l)?l.slice(0,2)+y:y;for(let w=0;w<d.length;w++){const E=_+d[w];try{if(s.sync(E,{pathExt:f}))if(u.all)g.push(E);else return E}catch{}}}if(u.all&&g.length)return g;if(u.nothrow)return null;throw o(l)};return Xr=a,a.sync=c,Xr}var Dn={exports:{}},Zo;function Ih(){if(Zo)return Dn.exports;Zo=1;var t={};const e=(n={})=>{const r=n.env||t;return(n.platform||"browser")!=="win32"?"PATH":Object.keys(r).reverse().find(o=>o.toUpperCase()==="PATH")||"Path"};return Dn.exports=e,Dn.exports.default=e,Dn.exports}var Zr,Qo;function $h(){if(Qo)return Zr;Qo=1;var t={};const e=Vi,n=Nh(),r=Ih();function s(i,a){const c=i.options.env||t,l=process.cwd(),u=i.options.cwd!=null,h=u&&process.chdir!==void 0&&!process.chdir.disabled;if(h)try{process.chdir(i.options.cwd)}catch{}let d;try{d=n.sync(i.command,{path:c[r({env:c})],pathExt:a?e.delimiter:void 0})}catch{}finally{h&&process.chdir(l)}return d&&(d=e.resolve(u?i.options.cwd:"",d)),d}function o(i){return s(i)||s(i,!0)}return Zr=o,Zr}var Qr,ei;function Rh(){if(ei)return Qr;ei=1,$h();function t(n){return n}function e(n,r,s){r&&!Array.isArray(r)&&(s=r,r=null),r=r?r.slice(0):[],s=Object.assign({},s);const o={command:n,args:r,options:s,file:void 0,original:{command:n,args:r}};return s.shell?o:o}return Qr=e,Qr}var es,ti;function jh(){if(ti)return es;ti=1;function t(s,o){return Object.assign(new Error(`${o} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${o} ${s.command}`,path:s.command,spawnargs:s.args})}function e(s,o){}function n(s,o){return null}function r(s,o){return null}return es={hookChildProcess:e,verifyENOENT:n,verifyENOENTSync:r,notFoundError:t},es}var ni;function Lh(){if(ni)return ot.exports;ni=1;const t=Jl,e=Rh(),n=jh();function r(o,i,a){const c=e(o,i,a),l=t.spawn(c.command,c.args,c.options);return n.hookChildProcess(l,c),l}function s(o,i,a){const c=e(o,i,a),l=t.spawnSync(c.command,c.args,c.options);return l.error=l.error||n.verifyENOENTSync(l.status,c),l}return ot.exports=r,ot.exports.spawn=r,ot.exports.sync=s,ot.exports._parse=e,ot.exports._enoent=n,ot.exports}var Fh=Lh();const Dh=Ol(Fh);class Uh{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf(`
|
|
7
|
+
`);if(e===-1)return null;const n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Vh(n)}clear(){this._buffer=void 0}}function Vh(t){return Nl.parse(JSON.parse(t))}function Bh(t){return JSON.stringify(t)+`
|
|
8
|
+
`}const zh=Ir.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Hh(){const t={};for(const e of zh){const n=Ir.env[e];n!==void 0&&(n.startsWith("()")||(t[e]=n))}return t}class Wh{constructor(e){this._readBuffer=new Uh,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Yl)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,n)=>{var r,s,o,i,a;this._process=Dh(this._serverParams.command,(r=this._serverParams.args)!==null&&r!==void 0?r:[],{env:{...Hh(),...this._serverParams.env},stdio:["pipe","pipe",(s=this._serverParams.stderr)!==null&&s!==void 0?s:"inherit"],shell:!1,windowsHide:Ir.platform==="win32"&&qh(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var l;n(c),(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var l;this._process=void 0,(l=this.onclose)===null||l===void 0||l.call(this)}),(o=this._process.stdin)===null||o===void 0||o.on("error",c=>{var l;(l=this.onerror)===null||l===void 0||l.call(this,c)}),(i=this._process.stdout)===null||i===void 0||i.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(a=this._process.stdout)===null||a===void 0||a.on("error",c=>{var l;(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,n;return this._stderrStream?this._stderrStream:(n=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&n!==void 0?n:null}get pid(){var e,n;return(n=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&n!==void 0?n:null}processReadBuffer(){for(var e,n;;)try{const r=this._readBuffer.readMessage();if(r===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,r)}catch(r){(n=this.onerror)===null||n===void 0||n.call(this,r)}}async close(){var e;if(this._process){const n=this._process;this._process=void 0;const r=new Promise(s=>{n.once("close",()=>{s()})});try{(e=n.stdin)===null||e===void 0||e.end()}catch{}if(await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())]),n.exitCode===null){try{n.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(s=>setTimeout(s,2e3).unref())])}if(n.exitCode===null)try{n.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(n=>{var r;if(!(!((r=this._process)===null||r===void 0)&&r.stdin))throw new Error("Not connected");const s=Bh(e);this._process.stdin.write(s)?n():this._process.stdin.once("drain",n)})}}function qh(){return"type"in Ir}var Kh={},Pt,ao=(Pt=class{client;_connecting=!1;constructor(e){this.client=e}async ensureServersConnected(){const e=this.client.getServerNames(),n=Object.keys(this.client.getAllActiveSessions()),r=e.filter(s=>!n.includes(s));if(r.length>0&&!this._connecting){this._connecting=!0;try{m.debug(`Connecting to configured servers for code execution: ${r.join(", ")}`),await this.client.createAllSessions()}finally{this._connecting=!1}}else if(r.length>0&&this._connecting){m.debug("Waiting for ongoing server connection...");const s=Date.now();for(;this._connecting&&Date.now()-s<5e3;)await new Promise(o=>setTimeout(o,100))}}getToolNamespaces(){const e=[],n=this.client.getAllActiveSessions();for(const[r,s]of Object.entries(n))if(r!=="code_mode")try{const o=s.connector;let i;try{i=o.tools}catch(a){m.warn(`Tools not available for server ${r}: ${a}`);continue}if(!i||i.length===0)continue;e.push({serverName:r,tools:i,session:s})}catch(o){m.warn(`Failed to load tools for server ${r}: ${o}`)}return e}createSearchToolsFunction(){return async(e="",n="full")=>{const r=[],s=new Set,o=e.toLowerCase(),i=this.client.getAllActiveSessions();for(const[c,l]of Object.entries(i))if(c!=="code_mode")try{const u=l.connector.tools;u&&u.length>0&&s.add(c);for(const h of u)n==="names"?r.push({name:h.name,server:c}):n==="descriptions"?r.push({name:h.name,server:c,description:h.description}):r.push({name:h.name,server:c,description:h.description,input_schema:h.inputSchema})}catch(u){m.warn(`Failed to search tools in server ${c}: ${u}`)}let a=r;return e&&(a=r.filter(c=>{const l=c.name.toLowerCase().includes(o),u=c.description?.toLowerCase().includes(o),h=c.server.toLowerCase().includes(o);return l||u||h})),{meta:{total_tools:r.length,namespaces:Array.from(s).sort(),result_count:a.length},results:a}}}},A(Pt,"BaseCodeExecutor"),Pt),Ot,ri=(Ot=class extends ao{e2bApiKey;codeExecSandbox=null;SandboxClass=null;timeoutMs;constructor(e,n){super(e),this.e2bApiKey=n.apiKey,this.timeoutMs=n.timeoutMs??3e5}async ensureSandboxClass(){if(!this.SandboxClass)try{const e=await Jt(()=>import("@e2b/code-interpreter"),[]);this.SandboxClass=e.Sandbox}catch{throw new Error("@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter")}}async getOrCreateCodeExecSandbox(){return this.codeExecSandbox?this.codeExecSandbox:(await this.ensureSandboxClass(),m.debug("Starting E2B sandbox for code execution..."),this.codeExecSandbox=await this.SandboxClass.create("base",{apiKey:this.e2bApiKey,timeoutMs:this.timeoutMs}),this.codeExecSandbox)}generateShim(e){let n=`
|
|
9
9
|
// MCP Bridge Shim
|
|
10
10
|
global.__callMcpTool = async (server, tool, args) => {
|
|
11
11
|
const id = Math.random().toString(36).substring(7);
|
|
@@ -86,7 +86,7 @@ ${this.generateShim(c)}
|
|
|
86
86
|
`,h=`exec_${Date.now()}.js`;await a.files.write(h,u);const d=await a.commands.run(`node ${h}`,{timeoutMs:n,onStdout:A(async f=>{try{const g=f.split(`
|
|
87
87
|
`);for(const p of g)if(p.trim().startsWith('{"type":"__MCP_TOOL_CALL__"')){const b=JSON.parse(p);if(b.type==="__MCP_TOOL_CALL__")try{m.debug(`[E2B Bridge] Calling tool ${b.server}.${b.tool}`);const y=this.client.getAllActiveSessions()[b.server];if(!y)throw new Error(`Server ${b.server} not found`);const _=await y.connector.callTool(b.tool,b.args);let w=_;if(_.content&&_.content.length>0){const T=_.content[0];if(T.type==="text")try{w=JSON.parse(T.text)}catch{w=T.text}else w=T}const E=`/tmp/mcp_result_${b.id}.json`;await a.files.write(E,JSON.stringify({data:w}))}catch(C){m.error(`[E2B Bridge] Tool execution failed: ${C.message}`);const y=`/tmp/mcp_result_${b.id}.json`;await a.files.write(y,JSON.stringify({error:C.message||String(C)}))}}}catch{}},"onStdout")});if(i=[d.stdout,d.stderr].filter(Boolean),d.exitCode!==0)o=d.stderr||"Execution failed";else{const f=d.stdout,g="__MCP_RESULT_START__",p="__MCP_RESULT_END__",b=f.indexOf(g),C=f.indexOf(p);if(b!==-1&&C!==-1){const y=f.substring(b+g.length,C).trim();try{s=JSON.parse(y)}catch{s=y}i=i.map(_=>{let w=_.replace(new RegExp(g+"[\\s\\S]*?"+p),"[Result captured]");return w=w.split(`
|
|
88
88
|
`).filter(E=>!E.includes("__MCP_TOOL_CALL__")).join(`
|
|
89
|
-
`),w})}}}catch(a){o=a.message||String(a),o&&(o.includes("timeout")||o.includes("timed out"))&&(o="Script execution timed out")}return{result:s,logs:i,error:o,execution_time:(Date.now()-r)/1e3}}async cleanup(){if(this.codeExecSandbox)try{await this.codeExecSandbox.kill(),this.codeExecSandbox=null,m.debug("E2B code execution sandbox stopped")}catch(e){m.error("Failed to stop E2B code execution sandbox:",e)}}},A(
|
|
89
|
+
`),w})}}}catch(a){o=a.message||String(a),o&&(o.includes("timeout")||o.includes("timed out"))&&(o="Script execution timed out")}return{result:s,logs:i,error:o,execution_time:(Date.now()-r)/1e3}}async cleanup(){if(this.codeExecSandbox)try{await this.codeExecSandbox.kill(),this.codeExecSandbox=null,m.debug("E2B code execution sandbox stopped")}catch(e){m.error("Failed to stop E2B code execution sandbox:",e)}}},A(Ot,"E2BCodeExecutor"),Ot),Ze=null,Es=!1;function co(){return["node","vm"].join(":")}A(co,"getVMModuleName");function Rr(){if(Es)return Ze!==null;Es=!0;try{const t=typeof Lo<"u"?Lo:null;if(t)return Ze=t(co()),!0}catch{m.debug("node:vm module not available via require")}return!1}A(Rr,"tryLoadVM");async function ea(){if(Ze!==null||!Es&&Rr())return!0;try{return Ze=await import(co()),!0}catch{return m.debug("node:vm module not available in this environment (e.g., Deno)"),!1}}A(ea,"tryLoadVMAsync");function Gh(){return Rr(),Ze!==null}A(Gh,"isVMAvailable");var Nt,si=(Nt=class extends ao{defaultTimeout;memoryLimitMb;constructor(e,n){super(e),this.defaultTimeout=n?.timeoutMs??3e4,this.memoryLimitMb=n?.memoryLimitMb,Rr()}async ensureVMLoaded(){if(Ze!==null)return;if(!await ea())throw new Error("node:vm module is not available in this environment. Please use E2B executor instead or run in a Node.js environment.")}async execute(e,n){const r=n??this.defaultTimeout;await this.ensureVMLoaded(),await this.ensureServersConnected();const s=[],o=Date.now();let i=null,a=null;try{const l=await this._buildContext(s),u=`
|
|
90
90
|
(async () => {
|
|
91
91
|
try {
|
|
92
92
|
${e}
|
|
@@ -94,7 +94,7 @@ ${this.generateShim(c)}
|
|
|
94
94
|
throw e;
|
|
95
95
|
}
|
|
96
96
|
})()
|
|
97
|
-
`;i=await new Ze.Script(u,{filename:"agent_code.js"}).runInNewContext(l,{timeout:r,displayErrors:!0})}catch(l){a=l.message||String(l),(l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"||l.message==="Script execution timed out."||typeof a=="string"&&(a.includes("timed out")||a.includes("timeout")))&&(a="Script execution timed out"),l.stack&&m.debug(`Code execution error stack: ${l.stack}`)}const c=(Date.now()-o)/1e3;return{result:i,logs:s,error:a,execution_time:c}}async _buildContext(e){const n=A((...i)=>{e.push(i.map(a=>typeof a=="object"?JSON.stringify(a,null,2):String(a)).join(" "))},"logHandler"),r={console:{log:n,error:A((...i)=>{n("[ERROR]",...i)},"error"),warn:A((...i)=>{n("[WARN]",...i)},"warn"),info:n,debug:n},Object,Array,String,Number,Boolean,Date,Math,JSON,RegExp,Map,Set,Promise,parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,setTimeout,clearTimeout,search_tools:this.createSearchToolsFunction(),__tool_namespaces:[]},s={},o=this.getToolNamespaces();for(const{serverName:i,tools:a,session:c}of o){const l={};for(const u of a){const h=u.name;l[h]=async d=>{const f=await c.connector.callTool(h,d||{});if(f.content&&f.content.length>0){const g=f.content[0];if(g.type==="text")try{return JSON.parse(g.text)}catch{return g.text}return g}return f}}r[i]=l,s[i]=!0}return r.__tool_namespaces=Object.keys(s),Ze.createContext(r)}async cleanup(){}},A(It,"VMCodeExecutor"),It),$t,Yh=($t=class extends Rl{serverParams;errlog;_transport=null;constructor(e,n=process.stderr){super(),this.serverParams=e,this.errlog=n}async establishConnection(){return this._transport=new qh(this.serverParams),this._transport.stderr&&typeof this._transport.stderr.pipe=="function"&&this._transport.stderr.pipe(this.errlog),m.debug(`${this.constructor.name} connected successfully`),this._transport}async closeConnection(e){if(this._transport)try{await this._transport.close()}catch(n){m.warn(`Error closing stdio transport: ${n}`)}finally{this._transport=null}}},A($t,"StdioConnectionManager"),$t),Rt,Xh=(Rt=class extends eo{command;args;env;errlog;clientInfo;constructor({command:e="npx",args:n=[],env:r,errlog:s=Ko.stderr,...o}={}){super(o),this.command=e,this.args=n,this.env=r,this.errlog=s,this.clientInfo=o.clientInfo??{name:"stdio-connector",version:"1.0.0"}}async connect(){if(this.connected){m.debug("Already connected to MCP implementation");return}m.debug(`Connecting to MCP implementation via stdio: ${this.command}`);try{let e;if(this.env){e={};for(const[o,i]of Object.entries(Ko.env))i!==void 0&&(e[o]=i);Object.assign(e,this.env)}const n={command:this.command,args:this.args,env:e};this.connectionManager=new Yh(n,this.errlog);const r=await this.connectionManager.start(),s={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};this.client=new $l(this.clientInfo,s),await this.client.connect(r),this.connected=!0,this.setupNotificationHandler(),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),m.debug(`Successfully connected to MCP implementation: ${this.command}`),this.trackConnectorInit({serverCommand:this.command,serverArgs:this.args,publicIdentifier:`${this.command} ${this.args.join(" ")}`})}catch(e){throw m.error(`Failed to connect to MCP implementation: ${e}`),await this.cleanupResources(),e}}get publicIdentifier(){return{type:"stdio","command&args":`${this.command} ${this.args.join(" ")}`}}},A(Rt,"StdioConnector"),Rt);function Ts(t){const e=Kl(t,"utf-8");return JSON.parse(e)}A(Ts,"loadConfigFile");function ta(t,e){if("command"in t&&"args"in t)return new Xh({command:t.command,args:t.args,env:t.env,...e});if("url"in t){const n=t.transport||"http";return new Di(t.url,{headers:t.headers,authToken:t.auth_token||t.authToken,preferSse:t.preferSse||n==="sse",...e})}throw new Error("Cannot determine connector type from config")}A(ta,"createConnectorFromConfig");var nt,Zh=(nt=class extends Il{static getPackageVersion(){return to()}codeMode=!1;_codeExecutor=null;_customCodeExecutor=null;_codeExecutorConfig="vm";_executorOptions;_samplingCallback;_elicitationCallback;constructor(e,n){e?typeof e=="string"?super(Ts(e)):super(e):super();let r=!1,s="vm",o;n?.codeMode&&(typeof n.codeMode=="boolean"?r=n.codeMode:(r=n.codeMode.enabled,s=n.codeMode.executor??"vm",o=n.codeMode.executorOptions)),this.codeMode=r,this._codeExecutorConfig=s,this._executorOptions=o,this._samplingCallback=n?.samplingCallback,this._elicitationCallback=n?.elicitationCallback,this.codeMode&&this._setupCodeModeConnector(),this._trackClientInit()}_trackClientInit(){const e=Object.keys(this.config.mcpServers??{}),n=!!this._samplingCallback,r=!!this._elicitationCallback;_s.getInstance().trackMCPClientInit({codeMode:this.codeMode,sandbox:!1,allCallbacks:n&&r,verify:!1,servers:e,numServers:e.length,isBrowser:!1}).catch(s=>m.debug(`Failed to track MCPClient init: ${s}`))}static fromDict(e,n){return new nt(e,n)}static fromConfigFile(e,n){return new nt(Ts(e),n)}saveConfig(e){const n=Gl.dirname(e);gn.existsSync(n)||gn.mkdirSync(n,{recursive:!0}),gn.writeFileSync(e,JSON.stringify(this.config,null,2),"utf-8")}createConnectorFromConfig(e){return ta(e,{samplingCallback:this._samplingCallback,elicitationCallback:this._elicitationCallback})}_setupCodeModeConnector(){m.debug("Code mode connector initialized as internal meta server");const e=new Sh(this),n=new Fi(e);this.sessions.code_mode=n,this.activeSessions.push("code_mode")}_ensureCodeExecutor(){if(!this._codeExecutor){const e=this._codeExecutorConfig;if(e instanceof ao)this._codeExecutor=e;else{if(typeof e=="function")throw this._customCodeExecutor=e,new Error("Custom executor function should be handled in executeCode");if(e==="e2b"){const n=this._executorOptions;if(n?.apiKey)this._codeExecutor=new ri(this,n);else{m.warn("E2B executor requires apiKey. Falling back to VM.");try{this._codeExecutor=new si(this,this._executorOptions)}catch{throw new Error("VM executor is not available in this environment and E2B API key is not provided. Please provide an E2B API key or run in a Node.js environment.")}}}else try{this._codeExecutor=new si(this,this._executorOptions)}catch{const r=this._executorOptions,s=r?.apiKey||Gh.E2B_API_KEY;if(s)m.info("VM executor not available in this environment. Falling back to E2B."),this._codeExecutor=new ri(this,{...r,apiKey:s});else throw new Error("VM executor is not available in this environment. Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, or run in a Node.js environment.")}}}return this._codeExecutor}async executeCode(e,n){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._customCodeExecutor?this._customCodeExecutor(e,n):this._ensureCodeExecutor().execute(e,n)}async searchTools(e="",n="full"){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._ensureCodeExecutor().createSearchToolsFunction()(e,n)}getServerNames(){const e=this.codeMode;return super.getServerNames().filter(n=>!e||n!=="code_mode")}async close(){this._codeExecutor&&(await this._codeExecutor.cleanup(),this._codeExecutor=null),await this.closeAllSessions()}},A(nt,"MCPClient"),nt),jt,na=(jt=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(m.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return m.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const o=this.convertTool(s,e);o&&n.push(o)}return this.connectorToolMap.set(e,n),m.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return m.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return m.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return m.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){m.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return m.error(`Error initializing connector: ${n}`),!1}}return!0}},A(jt,"BaseAdapter"),jt),Lt,Qh=(Lt=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,n){if(!n.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[s,o]of Object.entries(n.properties)){if(!(s in r)){if("const"in o)return!1;continue}const i=r[s];if("const"in o&&i!==o.const||"minimum"in o&&typeof i=="number"&&i<o.minimum||"maximum"in o&&typeof i=="number"&&i>o.maximum)return!1}return!0}static validateConditionalSchema(e,n,r){this.validateRequiredProperties(e,n,r),this.validatePropertyPatterns(e,n,r),this.validateNestedConditions(e,n,r)}static validateRequiredProperties(e,n,r){if(n.required){if(typeof e!="object"||e===null){for(const s of n.required)r.addIssue({code:zr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:zr.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(e,n,r){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const s=e;for(const[o,i]of Object.entries(n.properties)){if(!(o in s))continue;const a=s[o];i.pattern&&typeof a=="string"&&(new RegExp(i.pattern).test(a)||r.addIssue({code:zr.custom,message:`String '${a}' does not match pattern '${i.pattern}'`,path:[o]}))}}static validateNestedConditions(e,n,r){if(!n.if||!n.then)return;this.matchesCondition(e,n.if)?this.validateConditionalSchema(e,n.then,r):n.else&&this.validateConditionalSchema(e,n.else,r)}static parseSchema(e){return Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then?this.parseObject(e):e.properties&&(!e.type||e.type==="object")?this.parseObject(e):this.handleSingleType(e)}static handleTypeArray(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");return e.type.includes("null")?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");const n={...e};return n.type=e.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...e,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(e,n){const r=e.map(s=>{const o={...n,type:s};return this.parseSchema(o)});return Hr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):Ee();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return jl();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Ll();let r=n;return r=this.applyNumberBounds(n,e),r=this.applyNumberMultipleOf(n,e),r=this.applyNumberEnum(n,e),r=this.applyIntegerConstraint(n,e),r}static applyNumberBounds(e,n){let r=e;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(e,n){return n.multipleOf===void 0?e:e.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(e,n){if(!n.enum)return e;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?e:e.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(e,n){return n.type!=="integer"?e:e.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(e){const n=Nr();let r=n;return e.format?this.applyStringFormat(n,e):(r=this.applyStringPattern(n,e),r=this.applyStringLength(n,e),r=this.applyStringEnum(n,e),r)}static applyStringFormat(e,n){if(!n.format)return e;switch(n.format){case"email":return e.email();case"date-time":return e.datetime();case"uri":return e.url();case"uuid":return e.uuid();case"date":return e.date();default:return e}}static applyStringPattern(e,n){if(!n.pattern)return e;const r=new RegExp(n.pattern);return e.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(e,n){const r=e;return n.minLength!==void 0&&(e=e.min(n.minLength)),n.maxLength!==void 0&&(e=e.max(n.maxLength)),r}static applyStringEnum(e,n){return n.enum?e.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const o=e.items.map(i=>this.parseSchema(i));return Hr(o)}const n=e.items?this.parseSchema(e.items):Ee(),r=Fl(n);let s=r;return s=this.applyArrayConstraints(r,e),s}static applyArrayConstraints(e,n){return n.minItems!==void 0&&(e=e.min(n.minItems)),n.maxItems!==void 0&&(e=e.max(n.maxItems)),n.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);const n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,we(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const c=this.applyDefaultValues(i,e);this.matchesCondition(c,r)?this.validateConditionalSchema(c,s,a):o&&this.validateConditionalSchema(c,o,a)})}static createBaseObjectSchema(e){const n={},r=new Set(e.required||[]);for(const[o,i]of Object.entries(e.properties||{})){const a=this.parseSchema(i);n[o]=r.has(o)?a:a.optional()}const s=we(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return Ee();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Dl()):n.push(this.parseSchema(r));return n.length>=2?Hr(n):n.length===1?n[0]:Ee()}static parseAllOf(e){if(e.length===0)return Ee();if(e.length===1)return this.parseSchema(e[0]);const n=e.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(e,n){const r={...e,...n};if(e.properties&&n.properties){const s={...e.properties,...n.properties};r.properties=s}if(e.required&&n.required){const s=[...new Set([...e.required,...n.required])];r.required=s}return r}},A(Lt,"JSONSchemaToZod"),Lt);function ra(t){try{return Qh.convert(t)}catch(e){return m.warn(`Failed to convert JSON schema to Zod: ${e}`),Ee()}}A(ra,"schemaToZod");var Ft,vt=(Ft=class extends na{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?ra(e.inputSchema):we({}).optional();return new Kn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:A(async o=>{m.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return m.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=A(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Kn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:we({}).optional(),func:A(async()=>{m.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(c=>typeof c=="string"?c:c.text?c.text:c.uri?c.uri:JSON.stringify(c)).join(`
|
|
97
|
+
`;i=await new Ze.Script(u,{filename:"agent_code.js"}).runInNewContext(l,{timeout:r,displayErrors:!0})}catch(l){a=l.message||String(l),(l.code==="ERR_SCRIPT_EXECUTION_TIMEOUT"||l.message==="Script execution timed out."||typeof a=="string"&&(a.includes("timed out")||a.includes("timeout")))&&(a="Script execution timed out"),l.stack&&m.debug(`Code execution error stack: ${l.stack}`)}const c=(Date.now()-o)/1e3;return{result:i,logs:s,error:a,execution_time:c}}async _buildContext(e){const n=A((...i)=>{e.push(i.map(a=>typeof a=="object"?JSON.stringify(a,null,2):String(a)).join(" "))},"logHandler"),r={console:{log:n,error:A((...i)=>{n("[ERROR]",...i)},"error"),warn:A((...i)=>{n("[WARN]",...i)},"warn"),info:n,debug:n},Object,Array,String,Number,Boolean,Date,Math,JSON,RegExp,Map,Set,Promise,parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,setTimeout,clearTimeout,search_tools:this.createSearchToolsFunction(),__tool_namespaces:[]},s={},o=this.getToolNamespaces();for(const{serverName:i,tools:a,session:c}of o){const l={};for(const u of a){const h=u.name;l[h]=async d=>{const f=await c.connector.callTool(h,d||{});if(f.content&&f.content.length>0){const g=f.content[0];if(g.type==="text")try{return JSON.parse(g.text)}catch{return g.text}return g}return f}}r[i]=l,s[i]=!0}return r.__tool_namespaces=Object.keys(s),Ze.createContext(r)}async cleanup(){}},A(Nt,"VMCodeExecutor"),Nt),It,Jh=(It=class extends to{mcpClient;_tools;constructor(e){super(),this.mcpClient=e,this.connected=!0,this._tools=this._createToolsList()}async connect(){this.connected=!0}async disconnect(){this.connected=!1}get publicIdentifier(){return{name:"code_mode",version:"1.0.0"}}_createToolsList(){return[{name:"execute_code",description:"Execute JavaScript/TypeScript code with access to MCP tools. This is the PRIMARY way to interact with MCP servers in code mode. Write code that discovers tools using search_tools(), calls tools as async functions (e.g., await github.get_pull_request(...)), processes data efficiently, and returns results. Use 'await' for async operations and 'return' to return values. Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.",inputSchema:{type:"object",properties:{code:{type:"string",description:"JavaScript/TypeScript code to execute. Use 'await' for async operations. Use 'return' to return a value. Available: search_tools(), server.tool_name(), __tool_namespaces"},timeout:{type:"number",description:"Execution timeout in milliseconds",default:3e4}},required:["code"]}},{name:"search_tools",description:"Search and discover available MCP tools across all servers. Use this to find out what tools are available before writing code. Returns tool information including names, descriptions, and schemas. Can filter by query and control detail level.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query to filter tools by name or description",default:""},detail_level:{type:"string",description:"Detail level: 'names', 'descriptions', or 'full'",enum:["names","descriptions","full"],default:"full"}}}}]}get tools(){return this._tools}async initialize(){return this.toolsCache=this._tools,{capabilities:{},version:"1.0.0"}}async callTool(e,n){if(e==="execute_code"){const r=n.code,s=n.timeout||3e4,o=await this.mcpClient.executeCode(r,s);return{content:[{type:"text",text:JSON.stringify(o)}]}}else if(e==="search_tools"){const r=n.query||"",s=n.detail_level,o=await this.mcpClient.searchTools(r,s&&s in["names","descriptions","full"]?s:"full");return{content:[{type:"text",text:JSON.stringify(o)}]}}throw new Error(`Unknown tool: ${e}`)}},A(It,"CodeModeConnector"),It),$t,Yh=($t=class extends Rl{serverParams;errlog;_transport=null;constructor(e,n=process.stderr){super(),this.serverParams=e,this.errlog=n}async establishConnection(){return this._transport=new Wh(this.serverParams),this._transport.stderr&&typeof this._transport.stderr.pipe=="function"&&this._transport.stderr.pipe(this.errlog),m.debug(`${this.constructor.name} connected successfully`),this._transport}async closeConnection(e){if(this._transport)try{await this._transport.close()}catch(n){m.warn(`Error closing stdio transport: ${n}`)}finally{this._transport=null}}},A($t,"StdioConnectionManager"),$t),Rt,Xh=(Rt=class extends to{command;args;env;errlog;clientInfo;constructor({command:e="npx",args:n=[],env:r,errlog:s=Ko.stderr,...o}={}){super(o),this.command=e,this.args=n,this.env=r,this.errlog=s,this.clientInfo=o.clientInfo??{name:"stdio-connector",version:"1.0.0"}}async connect(){if(this.connected){m.debug("Already connected to MCP implementation");return}m.debug(`Connecting to MCP implementation via stdio: ${this.command}`);try{let e;if(this.env){e={};for(const[o,i]of Object.entries(Ko.env))i!==void 0&&(e[o]=i);Object.assign(e,this.env)}const n={command:this.command,args:this.args,env:e};this.connectionManager=new Yh(n,this.errlog);const r=await this.connectionManager.start(),s={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};this.client=new $l(this.clientInfo,s),await this.client.connect(r),this.connected=!0,this.setupNotificationHandler(),this.setupRootsHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),m.debug(`Successfully connected to MCP implementation: ${this.command}`),this.trackConnectorInit({serverCommand:this.command,serverArgs:this.args,publicIdentifier:`${this.command} ${this.args.join(" ")}`})}catch(e){throw m.error(`Failed to connect to MCP implementation: ${e}`),await this.cleanupResources(),e}}get publicIdentifier(){return{type:"stdio","command&args":`${this.command} ${this.args.join(" ")}`}}},A(Rt,"StdioConnector"),Rt);function Ts(t){const e=Kl(t,"utf-8");return JSON.parse(e)}A(Ts,"loadConfigFile");function ta(t,e){if("command"in t&&"args"in t)return new Xh({command:t.command,args:t.args,env:t.env,...e});if("url"in t){const n=t.transport||"http";return new Di(t.url,{headers:t.headers,authToken:t.auth_token||t.authToken,preferSse:t.preferSse||n==="sse",...e})}throw new Error("Cannot determine connector type from config")}A(ta,"createConnectorFromConfig");var nt,Zh=(nt=class extends Il{static getPackageVersion(){return eo()}codeMode=!1;_codeExecutor=null;_customCodeExecutor=null;_codeExecutorConfig="vm";_executorOptions;_samplingCallback;_elicitationCallback;constructor(e,n){e?typeof e=="string"?super(Ts(e)):super(e):super();let r=!1,s="vm",o;n?.codeMode&&(typeof n.codeMode=="boolean"?r=n.codeMode:(r=n.codeMode.enabled,s=n.codeMode.executor??"vm",o=n.codeMode.executorOptions)),this.codeMode=r,this._codeExecutorConfig=s,this._executorOptions=o,this._samplingCallback=n?.samplingCallback,this._elicitationCallback=n?.elicitationCallback,this.codeMode&&this._setupCodeModeConnector(),this._trackClientInit()}_trackClientInit(){const e=Object.keys(this.config.mcpServers??{}),n=!!this._samplingCallback,r=!!this._elicitationCallback;_s.getInstance().trackMCPClientInit({codeMode:this.codeMode,sandbox:!1,allCallbacks:n&&r,verify:!1,servers:e,numServers:e.length,isBrowser:!1}).catch(s=>m.debug(`Failed to track MCPClient init: ${s}`))}static fromDict(e,n){return new nt(e,n)}static fromConfigFile(e,n){return new nt(Ts(e),n)}saveConfig(e){const n=Gl.dirname(e);gn.existsSync(n)||gn.mkdirSync(n,{recursive:!0}),gn.writeFileSync(e,JSON.stringify(this.config,null,2),"utf-8")}createConnectorFromConfig(e){return ta(e,{samplingCallback:this._samplingCallback,elicitationCallback:this._elicitationCallback})}_setupCodeModeConnector(){m.debug("Code mode connector initialized as internal meta server");const e=new Jh(this),n=new Fi(e);this.sessions.code_mode=n,this.activeSessions.push("code_mode")}_ensureCodeExecutor(){if(!this._codeExecutor){const e=this._codeExecutorConfig;if(e instanceof ao)this._codeExecutor=e;else{if(typeof e=="function")throw this._customCodeExecutor=e,new Error("Custom executor function should be handled in executeCode");if(e==="e2b"){const n=this._executorOptions;if(n?.apiKey)this._codeExecutor=new ri(this,n);else{m.warn("E2B executor requires apiKey. Falling back to VM.");try{this._codeExecutor=new si(this,this._executorOptions)}catch{throw new Error("VM executor is not available in this environment and E2B API key is not provided. Please provide an E2B API key or run in a Node.js environment.")}}}else try{this._codeExecutor=new si(this,this._executorOptions)}catch{const r=this._executorOptions,s=r?.apiKey||Kh.E2B_API_KEY;if(s)m.info("VM executor not available in this environment. Falling back to E2B."),this._codeExecutor=new ri(this,{...r,apiKey:s});else throw new Error("VM executor is not available in this environment. Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, or run in a Node.js environment.")}}}return this._codeExecutor}async executeCode(e,n){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._customCodeExecutor?this._customCodeExecutor(e,n):this._ensureCodeExecutor().execute(e,n)}async searchTools(e="",n="full"){if(!this.codeMode)throw new Error("Code execution mode is not enabled");return this._ensureCodeExecutor().createSearchToolsFunction()(e,n)}getServerNames(){const e=this.codeMode;return super.getServerNames().filter(n=>!e||n!=="code_mode")}async close(){this._codeExecutor&&(await this._codeExecutor.cleanup(),this._codeExecutor=null),await this.closeAllSessions()}},A(nt,"MCPClient"),nt),jt,na=(jt=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){const r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(m.info("No active sessions found, creating new ones..."),await e.createAllSessions());const s=e.getAllActiveSessions(),o=Object.values(s).map(i=>i.connector);return r.createToolsFromConnectors(o)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const s=this.connectorToolMap.get(e);return m.debug(`Returning ${s.length} existing tools for connector`),s}const n=[];if(!await this.ensureConnectorInitialized(e))return[];for(const s of e.tools){const o=this.convertTool(s,e);o&&n.push(o)}return this.connectorToolMap.set(e,n),m.debug(`Loaded ${n.length} new tools for connector: ${n.map(s=>s?.name??String(s)).join(", ")}`),n}async createToolsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadToolsForConnector(r);n.push(...s)}return m.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of o){const a=this.convertResource(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new resources for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading resources for connector: ${s}`)}return n}async loadPromptsForConnector(e){const n=[];if(!await this.ensureConnectorInitialized(e))return[];try{const o=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of o){const a=this.convertPrompt(i,e);a&&n.push(a)}m.debug(`Loaded ${n.length} new prompts for connector: ${n.map(i=>i?.name??String(i)).join(", ")}`)}catch(s){m.warn(`Error loading prompts for connector: ${s}`)}return n}async createResourcesFromConnectors(e){const n=[];for(const r of e){const s=await this.loadResourcesForConnector(r);n.push(...s)}return m.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){const n=[];for(const r of e){const s=await this.loadPromptsForConnector(r);n.push(...s)}return m.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){m.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(n){return m.error(`Error initializing connector: ${n}`),!1}}return!0}},A(jt,"BaseAdapter"),jt),Lt,Qh=(Lt=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,n){if(!n.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[s,o]of Object.entries(n.properties)){if(!(s in r)){if("const"in o)return!1;continue}const i=r[s];if("const"in o&&i!==o.const||"minimum"in o&&typeof i=="number"&&i<o.minimum||"maximum"in o&&typeof i=="number"&&i>o.maximum)return!1}return!0}static validateConditionalSchema(e,n,r){this.validateRequiredProperties(e,n,r),this.validatePropertyPatterns(e,n,r),this.validateNestedConditions(e,n,r)}static validateRequiredProperties(e,n,r){if(n.required){if(typeof e!="object"||e===null){for(const s of n.required)r.addIssue({code:zr.custom,message:`Required property '${s}' is missing`,path:[s]});return}for(const s of n.required)s in e||r.addIssue({code:zr.custom,message:`Required property '${s}' is missing`,path:[s]})}}static validatePropertyPatterns(e,n,r){if(!n.properties||typeof e!="object"||e===null||Array.isArray(e))return;const s=e;for(const[o,i]of Object.entries(n.properties)){if(!(o in s))continue;const a=s[o];i.pattern&&typeof a=="string"&&(new RegExp(i.pattern).test(a)||r.addIssue({code:zr.custom,message:`String '${a}' does not match pattern '${i.pattern}'`,path:[o]}))}}static validateNestedConditions(e,n,r){if(!n.if||!n.then)return;this.matchesCondition(e,n.if)?this.validateConditionalSchema(e,n.then,r):n.else&&this.validateConditionalSchema(e,n.else,r)}static parseSchema(e){return Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then?this.parseObject(e):e.properties&&(!e.type||e.type==="object")?this.parseObject(e):this.handleSingleType(e)}static handleTypeArray(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");return e.type.includes("null")?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw new Error("Expected schema.type to be an array");const n={...e};return n.type=e.type.filter(s=>s!=="null"),n.type.length===1?this.handleSingleType({...e,type:n.type[0]}).nullable():this.parseSchema(n).nullable()}static createUnionFromTypes(e,n){const r=e.map(s=>{const o={...n,type:s};return this.parseSchema(o)});return Hr(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):Ee();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return jl();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const n=Ll();let r=n;return r=this.applyNumberBounds(n,e),r=this.applyNumberMultipleOf(n,e),r=this.applyNumberEnum(n,e),r=this.applyIntegerConstraint(n,e),r}static applyNumberBounds(e,n){let r=e;return n.minimum!==void 0&&(r=n.exclusiveMinimum?r.gt(n.minimum):r.gte(n.minimum)),n.maximum!==void 0&&(r=n.exclusiveMaximum?r.lt(n.maximum):r.lte(n.maximum)),r}static applyNumberMultipleOf(e,n){return n.multipleOf===void 0?e:e.refine(r=>r%n.multipleOf===0,{message:`Number must be a multiple of ${n.multipleOf}`})}static applyNumberEnum(e,n){if(!n.enum)return e;const r=n.enum.filter(s=>typeof s=="number");return r.length===0?e:e.refine(s=>r.includes(s),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(e,n){return n.type!=="integer"?e:e.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(e){const n=Nr();let r=n;return e.format?this.applyStringFormat(n,e):(r=this.applyStringPattern(n,e),r=this.applyStringLength(n,e),r=this.applyStringEnum(n,e),r)}static applyStringFormat(e,n){if(!n.format)return e;switch(n.format){case"email":return e.email();case"date-time":return e.datetime();case"uri":return e.url();case"uuid":return e.uuid();case"date":return e.date();default:return e}}static applyStringPattern(e,n){if(!n.pattern)return e;const r=new RegExp(n.pattern);return e.regex(r,{message:`String must match pattern: ${n.pattern}`})}static applyStringLength(e,n){const r=e;return n.minLength!==void 0&&(e=e.min(n.minLength)),n.maxLength!==void 0&&(e=e.max(n.maxLength)),r}static applyStringEnum(e,n){return n.enum?e.refine(r=>n.enum?.includes(r),{message:`Value must be one of: ${n.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const o=e.items.map(i=>this.parseSchema(i));return Hr(o)}const n=e.items?this.parseSchema(e.items):Ee(),r=Fl(n);let s=r;return s=this.applyArrayConstraints(r,e),s}static applyArrayConstraints(e,n){return n.minItems!==void 0&&(e=e.min(n.minItems)),n.maxItems!==void 0&&(e=e.max(n.maxItems)),n.uniqueItems?e.refine(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);const n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,we(n))}static processObjectProperties(e,n){const r=new Set(e.required||[]);if(e.properties)for(const[s,o]of Object.entries(e.properties)){const i=this.parseSchema(o);n[s]=r.has(s)?i:i.optional()}}static processAdditionalProperties(e,n){if(e.additionalProperties===!0)return n.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return n.catchall(r)}else return n.strict()}static parseConditional(e){const n=this.createBaseObjectSchema(e),r=e.if,s=e.then,o=e.else;return n.superRefine((i,a)=>{const c=this.applyDefaultValues(i,e);this.matchesCondition(c,r)?this.validateConditionalSchema(c,s,a):o&&this.validateConditionalSchema(c,o,a)})}static createBaseObjectSchema(e){const n={},r=new Set(e.required||[]);for(const[o,i]of Object.entries(e.properties||{})){const a=this.parseSchema(i);n[o]=r.has(o)?a:a.optional()}const s=we(n);return this.processAdditionalProperties(e,s)}static applyDefaultValues(e,n){if(typeof e!="object"||e===null||Array.isArray(e))return e;const s={...e};if(!n.properties)return s;for(const[o,i]of Object.entries(n.properties))!(o in s)&&"default"in i&&(s[o]=i.default);return s}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw new Error("Unsupported schema type")}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return Ee();if(e.length===1)return this.parseSchema(e[0]);const n=[];for(const r of e)r.type==="null"?n.push(Dl()):n.push(this.parseSchema(r));return n.length>=2?Hr(n):n.length===1?n[0]:Ee()}static parseAllOf(e){if(e.length===0)return Ee();if(e.length===1)return this.parseSchema(e[0]);const n=e.reduce((r,s)=>this.mergeSchemas(r,s));return this.parseSchema(n)}static mergeSchemas(e,n){const r={...e,...n};if(e.properties&&n.properties){const s={...e.properties,...n.properties};r.properties=s}if(e.required&&n.required){const s=[...new Set([...e.required,...n.required])];r.required=s}return r}},A(Lt,"JSONSchemaToZod"),Lt);function ra(t){try{return Qh.convert(t)}catch(e){return m.warn(`Failed to convert JSON schema to Zod: ${e}`),Ee()}}A(ra,"schemaToZod");var Ft,vt=(Ft=class extends na{constructor(e=[]){super(e)}convertTool(e,n){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?ra(e.inputSchema):we({}).optional();return new Kn({name:e.name??"NO NAME",description:e.description??"",schema:r,func:A(async o=>{m.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(o)}`);try{const i=await n.callTool(e.name,o);return JSON.stringify(i)}catch(i){return m.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,n){const s=A(a=>a.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),o=e.uri;return new Kn({name:s,description:e.description||`Return the content of the resource located at URI ${o}.`,schema:we({}).optional(),func:A(async()=>{m.debug(`Resource tool: "${s}" called`);try{const a=await n.readResource(o);return a.contents&&a.contents.length>0?a.contents.map(c=>typeof c=="string"?c:c.text?c.text:c.uri?c.uri:JSON.stringify(c)).join(`
|
|
98
98
|
`):"Resource is empty or unavailable"}catch(a){return m.error(`Error reading resource: ${a.message}`),`Error reading resource: ${String(a)}`}},"func")})}convertPrompt(e,n){let r=we({}).optional();if(e.arguments&&e.arguments.length>0){const o={};for(const i of e.arguments){const a=Nr();i.required!==!1?o[i.name]=a:o[i.name]=a.optional()}r=Object.keys(o).length>0?we(o):we({}).optional()}return new Kn({name:e.name,description:e.description||"",schema:r,func:A(async o=>{m.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(o)}`);try{const i=await n.getPrompt(e.name,o);return i.messages&&i.messages.length>0?i.messages.map(a=>typeof a=="string"?a:a.content?typeof a.content=="string"?a.content:JSON.stringify(a.content):JSON.stringify(a)).join(`
|
|
99
99
|
`):"Prompt returned no messages"}catch(i){return m.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},A(Ft,"LangChainAdapter"),Ft),ed=Object.defineProperty,sa=(t,e)=>{for(var n in e)ed(t,n,{get:e[n],enumerable:!0})},td={};sa(td,{ConfigurableModel:()=>ks,MODEL_PROVIDER_CONFIG:()=>jr,_inferModelProvider:()=>aa,getChatModelByClassName:()=>ia,initChatModel:()=>cn});const jr={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},fireworks:{package:"@langchain/community/chat_models/fireworks",className:"ChatFireworks",hasCircularDependency:!0},together:{package:"@langchain/community/chat_models/togetherai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/community/chat_models/perplexity",className:"ChatPerplexity",hasCircularDependency:!0}},oa=Object.keys(jr);async function ia(t){const e=Object.entries(jr).find(([,r])=>r.className===t);if(!e)return;const[,n]=e;try{return(await import(n.package))[n.className]}catch(r){const s=r;if("code"in s&&s.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in s){const o=s.message.split("Error: Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${o}. Please install with \`npm install ${o}\` or \`pnpm install ${o}\``)}throw r}}async function nd(t,e,n={}){const r=e||aa(t);if(!r)throw new Error(`Unable to infer model provider for { model: ${t} }, please specify modelProvider directly.`);const s=jr[r];if(!s){const c=oa.join(", ");throw new Error(`Unsupported { modelProvider: ${r} }.
|
|
100
100
|
|
|
@@ -417,7 +417,7 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
|
|
|
417
417
|
${i.map(c=>c.name).join(`
|
|
418
418
|
`)}`,m.info(r),r}catch(r){return m.error(`Failed to add or connect to server '${e}': ${r.message}`),`Failed to add or connect to server '${e}': ${r.message}`}}},A(Vt,"AddMCPServerFromConfigTool"),Vt),yy=we({serverName:Nr().describe("The name of the MCP server.")}),Bt,wy=(Bt=class extends Vr{name="connect_to_mcp_server";description="Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.";schema=yy;constructor(e){super(e)}async _call({serverName:e}){const n=this.manager.client.getServerNames();if(!n.includes(e)){const r=n.length>0?n.join(", "):"none";return`Server '${e}' not found. Available servers: ${r}`}if(this.manager.activeServer===e)return`Already connected to MCP server '${e}'`;try{let r=this.manager.client.getSession(e);if(m.debug(`Using existing session for server '${e}'`),r||(m.debug(`Creating new session for server '${e}'`),r=await this.manager.client.createSession(e)),this.manager.activeServer=e,!this.manager.serverTools[e]){const i=r.connector,a=await this.manager.adapter.createToolsFromConnectors([i]),c=await this.manager.adapter.createResourcesFromConnectors([i]),l=await this.manager.adapter.createPromptsFromConnectors([i]),u=[...a,...c,...l];this.manager.serverTools[e]=u,this.manager.initializedServers[e]=!0,m.debug(`Loaded ${u.length} items for server '${e}': ${a.length} tools, ${c.length} resources, ${l.length} prompts`)}const o=(this.manager.serverTools[e]||[]).length;return`Connected to MCP server '${e}'. ${o} tools, resources, and prompts are now available.`}catch(r){return m.error(`Error connecting to server '${e}': ${String(r)}`),`Failed to connect to server '${e}': ${String(r)}`}}},A(Bt,"ConnectMCPServerTool"),Bt),vy=we({}),zt,_y=(zt=class extends Vr{name="list_mcp_servers";description="Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.";schema=vy;constructor(e){super(e)}async _call(){const e=this.manager.client.getServerNames();if(e.length===0)return"No MCP servers are currently defined.";const n=["Available MCP servers:"];for(const r of e){const o=r===this.manager.activeServer?" (ACTIVE)":"";n.push(`- ${r}${o}`);try{const i=this.manager.serverTools?.[r]??[],a=Array.isArray(i)?i.length:0;n.push(`${a} tools available for this server
|
|
419
419
|
`)}catch(i){m.error(`Unexpected error listing tools for server '${r}': ${String(i)}`)}}return n.join(`
|
|
420
|
-
`)}},A(zt,"ListMCPServersTool"),zt),by=we({}),Ht,Sy=(Ht=class extends Vr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=by;constructor(e){super(e)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const e=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${e}'.`}},A(Ht,"ReleaseMCPServerConnectionTool"),Ht);function Or(t,e){if(t===e)return!0;if(t==null||e==null||typeof t!=typeof e)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?!1:t.every((n,r)=>Or(n,e[r]));if(typeof t=="object"&&typeof e=="object"){const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>Object.prototype.hasOwnProperty.call(e,s)&&Or(t[s],e[s]))}return!1}A(Or,"isEqual");var Wt,Li=(Wt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,m.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){m.info("Server Manager State: No servers configured.");return}const s=n.map(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));m.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&m.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),m.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(m.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),m.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(h){m.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const c=[...o,...i,...a],l=this.serverTools[n];!l||!Or(l,c)?(this.serverTools[n]=c,this.initializedServers[n]=!0,m.debug(`Prefetched ${c.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):m.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){m.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){m.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new gy(this),new _y(this),new wy(this),new my(this),new Sy(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return m.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},A(Wt,"ServerManager"),Wt),qt,Qs=(qt=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:n}=await Jt(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await import("./langfuse-74RGPTAH-BwcKtZq0.js");return{langfuseHandler:s,langfuseInitPromise:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Jt(async()=>{const{initializeLangfuse:o}=await import("./langfuse-74RGPTAH-BwcKtZq0.js");return{initializeLangfuse:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),m.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),m.debug("ObservabilityManager: Langfuse handler available"))}catch{m.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(m.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?m.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):m.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(m.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),m.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],m.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();m.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();m.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},A(qt,"ObservabilityManager"),qt),Cy="/api/v1/chats",Ey="/api/v1/chats/{chat_id}/execute";function Sl(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(Sl,"normalizeRemoteRunOptions");var Kt,Cl=(Kt=class{agentId;apiKey;baseUrl;chatId=null;constructor(e){this.agentId=e.agentId,this.baseUrl=e.baseUrl??"https://cloud.mcp-use.com";const n=e.apiKey??bl.MCP_USE_API_KEY;if(!n)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=n}pydanticToJsonSchema(e){return qn(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){m.warn(`Failed to parse structured output: ${s}`);const o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${Cy}`;m.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),c=s.status;throw c===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${c} - ${a}`)}const i=(await s.json()).id;return m.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(e,n,r,s,o){const{query:i,maxSteps:a,externalHistory:c,outputSchema:l}=Sl(e,n,r,s,o);c!==void 0&&m.warn("External history is not yet supported for remote execution");try{m.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const u=this.chatId,h={query:i,max_steps:a??10};l&&(h.output_schema=this.pydanticToJsonSchema(l),m.info("🔧 Using structured output with schema"));const d={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${Ey.replace("{chat_id}",u)}`;m.info(`🚀 Executing agent in chat ${u}`);const g=await fetch(f,{method:"POST",headers:d,body:JSON.stringify(h),signal:AbortSignal.timeout(3e5)});if(!g.ok){const b=await g.text(),C=g.status;throw C===401?(m.error(`❌ Authentication failed: ${b}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):C===403?(m.error(`❌ Access forbidden: ${b}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):C===404?(m.error(`❌ Agent not found: ${b}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):C===422?(m.error(`❌ Validation error: ${b}`),new Error(`Request validation failed: ${b}. Please check your query parameters and output schema format.`)):C===500?(m.error(`❌ Server error: ${b}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(m.error(`❌ Remote execution failed with status ${C}: ${b}`),new Error(`Remote agent execution failed: ${C} - ${b}`))}const p=await g.json();if(m.info(`🔧 Response: ${JSON.stringify(p)}`),m.info("✅ Remote execution completed successfully"),typeof p=="object"&&p!==null){if(p.status==="error"||p.error!==null){const b=p.error??String(p);throw m.error(`❌ Remote agent execution failed: ${b}`),new Error(`Remote agent execution failed: ${b}`)}if(String(p).includes("failed to initialize"))throw m.error(`❌ Agent initialization failed: ${p}`),new Error(`Agent initialization failed on remote server. This usually indicates:
|
|
420
|
+
`)}},A(zt,"ListMCPServersTool"),zt),by=we({}),Ht,Sy=(Ht=class extends Vr{name="disconnect_from_mcp_server";description="Disconnect from the currently active MCP (Model Context Protocol) server";schema=by;constructor(e){super(e)}async _call(){if(!this.manager.activeServer)return"No MCP server is currently active, so there's nothing to disconnect from.";const e=this.manager.activeServer;return this.manager.activeServer=null,`Successfully disconnected from MCP server '${e}'.`}},A(Ht,"ReleaseMCPServerConnectionTool"),Ht);function Or(t,e){if(t===e)return!0;if(t==null||e==null||typeof t!=typeof e)return!1;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(Array.isArray(t)&&Array.isArray(e))return t.length!==e.length?!1:t.every((n,r)=>Or(n,e[r]));if(typeof t=="object"&&typeof e=="object"){const n=Object.keys(t),r=Object.keys(e);return n.length!==r.length?!1:n.every(s=>Object.prototype.hasOwnProperty.call(e,s)&&Or(t[s],e[s]))}return!1}A(Or,"isEqual");var Wt,Li=(Wt=class{initializedServers={};serverTools={};client;adapter;activeServer=null;overrideManagementTools;constructor(e,n,r){this.client=e,this.adapter=n,this.overrideManagementTools=r}setManagementTools(e){this.overrideManagementTools=e,m.info(`Overriding default management tools with a new set of ${e.length} tools.`)}logState(e){const n=this.client.getServerNames(),r=Object.keys(this.client.getAllActiveSessions());if(n.length===0){m.info("Server Manager State: No servers configured.");return}const s=n.map(o=>({"Server Name":o,Connected:r.includes(o)?"✅":"❌",Initialized:this.initializedServers[o]?"✅":"❌","Tool Count":this.serverTools[o]?.length??0,Active:this.activeServer===o?"✅":"❌"}));m.info(`Server Manager State: [${e}]`),console.table(s)}initialize(){(this.client.getServerNames?.()).length===0&&m.warn("No MCP servers defined in client configuration")}async prefetchServerTools(){const e=this.client.getServerNames();for(const n of e)try{let r=null;if(r=this.client.getSession(n),m.debug(`Using existing session for server '${n}' to prefetch tools.`),r||(r=await this.client.createSession(n).catch(s=>(m.warn(`Could not create session for '${n}' during prefetch: ${s}`),null)),m.debug(`Temporarily created session for '${n}' to prefetch tools.`)),r){const s=r.connector;let o=[],i=[],a=[];try{o=await this.adapter.createToolsFromConnectors([s]),i=await this.adapter.createResourcesFromConnectors([s]),a=await this.adapter.createPromptsFromConnectors([s])}catch(h){m.error(`Failed to create tools/resources/prompts from connector for server '${n}': ${h}`);continue}const c=[...o,...i,...a],l=this.serverTools[n];!l||!Or(l,c)?(this.serverTools[n]=c,this.initializedServers[n]=!0,m.debug(`Prefetched ${c.length} items for server '${n}': ${o.length} tools, ${i.length} resources, ${a.length} prompts.`)):m.debug(`Tools for server '${n}' unchanged, using cached version.`)}}catch(r){m.error(`Error prefetching tools for server '${n}': ${r}`)}}get tools(){m.level==="debug"&&this.logState("Providing tools to agent");const e=this.overrideManagementTools??[new gy(this),new _y(this),new wy(this),new my(this),new Sy(this)];if(this.activeServer&&this.serverTools[this.activeServer]){const n=this.serverTools[this.activeServer];return m.debug(`Adding ${n.length} tools from active server '${this.activeServer}'`),[...e,...n]}return e}},A(Wt,"ServerManager"),Wt),qt,Qs=(qt=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:n}=await Jt(async()=>{const{langfuseHandler:s,langfuseInitPromise:o}=await import("./langfuse-74RGPTAH-N7gq8lpA.js");return{langfuseHandler:s,langfuseInitPromise:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:s}=await Jt(async()=>{const{initializeLangfuse:o}=await import("./langfuse-74RGPTAH-N7gq8lpA.js");return{initializeLangfuse:o}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10]));await s(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),m.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const s=n();s&&await s}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),m.debug("ObservabilityManager: Langfuse handler available"))}catch{m.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(m.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?m.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):m.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(m.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),n=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},s=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:n,metadata:r,tags:s}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),m.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],m.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const n of e)"flushAsync"in n&&typeof n.flushAsync=="function"&&await n.flushAsync();m.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const n of e)"shutdownAsync"in n&&typeof n.shutdownAsync=="function"?await n.shutdownAsync():"shutdown"in n&&typeof n.shutdown=="function"&&await n.shutdown();m.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},A(qt,"ObservabilityManager"),qt),Cy="/api/v1/chats",Ey="/api/v1/chats/{chat_id}/execute";function Sl(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(Sl,"normalizeRemoteRunOptions");var Kt,Cl=(Kt=class{agentId;apiKey;baseUrl;chatId=null;constructor(e){this.agentId=e.agentId,this.baseUrl=e.baseUrl??"https://cloud.mcp-use.com";const n=e.apiKey??bl.MCP_USE_API_KEY;if(!n)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=n}pydanticToJsonSchema(e){return qn(e)}parseStructuredResponse(e,n){let r;if(typeof e=="object"&&e!==null)if("result"in e){const s=e.result;typeof s=="object"&&s!==null&&"result"in s?r=s.result:r=s}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return n.parse(r)}catch(s){m.warn(`Failed to parse structured output: ${s}`);const o=n._def?.shape();if(o&&"content"in o)return n.parse({content:String(r)});throw s}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},n={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${Cy}`;m.info(`📝 Creating chat session for agent ${this.agentId}`);try{const s=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(e)});if(!s.ok){const a=await s.text(),c=s.status;throw c===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${c} - ${a}`)}const i=(await s.json()).id;return m.info(`✅ Chat session created: ${i}`),i}catch(s){throw s instanceof Error?new TypeError(`Failed to create chat session: ${s.message}`):new Error(`Failed to create chat session: ${String(s)}`)}}async run(e,n,r,s,o){const{query:i,maxSteps:a,externalHistory:c,outputSchema:l}=Sl(e,n,r,s,o);c!==void 0&&m.warn("External history is not yet supported for remote execution");try{m.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const u=this.chatId,h={query:i,max_steps:a??10};l&&(h.output_schema=this.pydanticToJsonSchema(l),m.info("🔧 Using structured output with schema"));const d={"Content-Type":"application/json","x-api-key":this.apiKey},f=`${this.baseUrl}${Ey.replace("{chat_id}",u)}`;m.info(`🚀 Executing agent in chat ${u}`);const g=await fetch(f,{method:"POST",headers:d,body:JSON.stringify(h),signal:AbortSignal.timeout(3e5)});if(!g.ok){const b=await g.text(),C=g.status;throw C===401?(m.error(`❌ Authentication failed: ${b}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):C===403?(m.error(`❌ Access forbidden: ${b}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):C===404?(m.error(`❌ Agent not found: ${b}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):C===422?(m.error(`❌ Validation error: ${b}`),new Error(`Request validation failed: ${b}. Please check your query parameters and output schema format.`)):C===500?(m.error(`❌ Server error: ${b}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(m.error(`❌ Remote execution failed with status ${C}: ${b}`),new Error(`Remote agent execution failed: ${C} - ${b}`))}const p=await g.json();if(m.info(`🔧 Response: ${JSON.stringify(p)}`),m.info("✅ Remote execution completed successfully"),typeof p=="object"&&p!==null){if(p.status==="error"||p.error!==null){const b=p.error??String(p);throw m.error(`❌ Remote agent execution failed: ${b}`),new Error(`Remote agent execution failed: ${b}`)}if(String(p).includes("failed to initialize"))throw m.error(`❌ Agent initialization failed: ${p}`),new Error(`Agent initialization failed on remote server. This usually indicates:
|
|
421
421
|
• Invalid agent configuration (LLM model, system prompt)
|
|
422
422
|
• Missing or invalid MCP server configurations
|
|
423
423
|
• Network connectivity issues with MCP servers
|
|
@@ -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 dr(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(dr,"normalizeRunOptions");var Gt,xy=(Gt=class{static getPackageVersion(){return to()}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 Cl({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=Wn.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qs({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=Wn.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 Li(this.client,this.adapter)}else this.adapter=e.adapter??new vt(this.disallowedTools);if(this.telemetry=Wn.getInstance(),this.llm){const[r,s]=Fo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Qs({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 jo(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=Fo(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 Li(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??Ty;this.systemMessage=Al(e,n,ky,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}=dr(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}=dr(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(k=>k.name)),S=new Set(this._tools.map(k=>k.name));(v.size!==S.size||[...v].some(k=>!S.has(k)))&&(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 k of S){for(const[M,P]of Object.entries(k))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)),Ln=new Set(this._tools.map(un=>un.name));if(Me.size!==Ln.size||[...Me].some(un=>!Ln.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-CDZgqATQ.js");return{prettyStreamEvents:c}},__vite__mapDeps([11,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=dr(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 k=S.data.chunk;if(k.content){C||(C="");const M=this._normalizeOutput(k.content);C+=M,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!C){const k=S.data.output;Array.isArray(k)&&k.length>0&&k[0]?.text?C=k[0].text:typeof k=="string"?C=k:k&&typeof k=="object"&&"output"in k&&(C=k.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let S=!1,k=null,M=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(S=!0,k=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;k&&(yield{event:"on_structured_output",data:{output:k}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(k)}`)),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 dr(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(dr,"normalizeRunOptions");var Gt,xy=(Gt=class{static getPackageVersion(){return eo()}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 Cl({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=Wn.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qs({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=Wn.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 Li(this.client,this.adapter)}else this.adapter=e.adapter??new vt(this.disallowedTools);if(this.telemetry=Wn.getInstance(),this.llm){const[r,s]=Fo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Qs({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 jo(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=Fo(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 Li(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??Ty;this.systemMessage=Al(e,n,ky,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}=dr(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}=dr(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(k=>k.name)),S=new Set(this._tools.map(k=>k.name));(v.size!==S.size||[...v].some(k=>!S.has(k)))&&(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 k of S){for(const[M,P]of Object.entries(k))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)),Ln=new Set(this._tools.map(un=>un.name));if(Me.size!==Ln.size||[...Me].some(un=>!Ln.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-BqXf1TEf.js");return{prettyStreamEvents:c}},__vite__mapDeps([11,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=dr(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 k=S.data.chunk;if(k.content){C||(C="");const M=this._normalizeOutput(k.content);C+=M,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!C){const k=S.data.output;Array.isArray(k)&&k.length>0&&k[0]?.text?C=k[0].text:typeof k=="string"?C=k:k&&typeof k=="object"&&"output"in k&&(C=k.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let S=!1,k=null,M=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(S=!0,k=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;k&&(yield{event:"on_structured_output",data:{output:k}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(k)}`)),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(qn(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=qn(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.
|
|
@@ -498,4 +498,4 @@ ${g}`);const b=await s.stream(g);let C=null,y=0;for await(const w of b){if(y++,m
|
|
|
498
498
|
|
|
499
499
|
Make sure you gather ALL the required information during your task execution.
|
|
500
500
|
If any required information is missing, continue working to find it.
|
|
501
|
-
`}catch(r){return m.warn(`Could not extract schema details: ${r}`),e}}},A(Gt,"MCPAgent"),Gt),X={},My=X.MCP_USE_LANGFUSE?.toLowerCase()==="false",Nn={handler:null,client:null,initPromise:null};async function Pl(t,e,n,r){try{const s=await Jt(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){m.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:o}=s,u=class u extends o{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,g,p,b){super(d),this.agentId=f,this.metadata=g,this.metadataProvider=p,this.tagsProvider=b,this.verbose=d?.verbose??!1}async handleChainStart(d,f,g,p,b,C,y,_){m.debug("Langfuse: Chain start intercepted");const w=this.getCustomTags(),E=this.getMetadata(),T=[...b||[],...w],v={...C||{},...E};return this.verbose&&(m.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(T)}`),m.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(v)}`)),super.handleChainStart(d,f,g,p,T,v,y,_)}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=X.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 m.debug("Langfuse: LLM start intercepted"),this.verbose&&m.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return m.debug("Langfuse: Tool start intercepted"),this.verbose&&m.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return m.debug("Langfuse: Retriever start intercepted"),this.verbose&&m.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return m.debug("Langfuse: Agent action intercepted"),this.verbose&&m.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return m.debug("Langfuse: Agent end intercepted"),this.verbose&&m.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};A(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),c=r?r():[],l={publicKey:X.LANGFUSE_PUBLIC_KEY,secretKey:X.LANGFUSE_SECRET_KEY,baseUrl:X.LANGFUSE_HOST||X.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(X.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(X.LANGFUSE_FLUSH_INTERVAL||"10000"),release:X.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(X.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:X.LANGFUSE_ENABLED!=="false",traceName:a.trace_name||X.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:c.length>0?c:void 0,metadata:a||void 0};m.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Nn.handler=new i(l,t,e,n,r),m.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await Jt(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;Nn.client=new d({publicKey:X.LANGFUSE_PUBLIC_KEY,secretKey:X.LANGFUSE_SECRET_KEY,baseUrl:X.LANGFUSE_HOST||"https://cloud.langfuse.com"}),m.debug("Langfuse client initialized")}}catch(h){m.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){m.debug(`Langfuse initialization error: ${s}`)}}A(Pl,"initializeLangfuse");My?m.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!X.LANGFUSE_PUBLIC_KEY||!X.LANGFUSE_SECRET_KEY?m.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Nn.initPromise=Pl();var zy=A(()=>Nn.handler,"langfuseHandler"),Hy=A(()=>Nn.initPromise,"langfuseInitPromise");const Wy=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:na,BaseConnector:
|
|
501
|
+
`}catch(r){return m.warn(`Could not extract schema details: ${r}`),e}}},A(Gt,"MCPAgent"),Gt),X={},My=X.MCP_USE_LANGFUSE?.toLowerCase()==="false",Nn={handler:null,client:null,initPromise:null};async function Pl(t,e,n,r){try{const s=await Jt(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!s){m.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:o}=s,u=class u extends o{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(d,f,g,p,b){super(d),this.agentId=f,this.metadata=g,this.metadataProvider=p,this.tagsProvider=b,this.verbose=d?.verbose??!1}async handleChainStart(d,f,g,p,b,C,y,_){m.debug("Langfuse: Chain start intercepted");const w=this.getCustomTags(),E=this.getMetadata(),T=[...b||[],...w],v={...C||{},...E};return this.verbose&&(m.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(T)}`),m.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(v)}`)),super.handleChainStart(d,f,g,p,T,v,y,_)}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=X.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 m.debug("Langfuse: LLM start intercepted"),this.verbose&&m.debug(`Langfuse: LLM start args: ${JSON.stringify(d)}`),super.handleLLMStart(...d)}async handleToolStart(...d){return m.debug("Langfuse: Tool start intercepted"),this.verbose&&m.debug(`Langfuse: Tool start args: ${JSON.stringify(d)}`),super.handleToolStart(...d)}async handleRetrieverStart(...d){return m.debug("Langfuse: Retriever start intercepted"),this.verbose&&m.debug(`Langfuse: Retriever start args: ${JSON.stringify(d)}`),super.handleRetrieverStart(...d)}async handleAgentAction(...d){return m.debug("Langfuse: Agent action intercepted"),this.verbose&&m.debug(`Langfuse: Agent action args: ${JSON.stringify(d)}`),super.handleAgentAction(...d)}async handleAgentEnd(...d){return m.debug("Langfuse: Agent end intercepted"),this.verbose&&m.debug(`Langfuse: Agent end args: ${JSON.stringify(d)}`),super.handleAgentEnd(...d)}};A(u,"LoggingCallbackHandler");let i=u;const a=e||(n?n():{}),c=r?r():[],l={publicKey:X.LANGFUSE_PUBLIC_KEY,secretKey:X.LANGFUSE_SECRET_KEY,baseUrl:X.LANGFUSE_HOST||X.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(X.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(X.LANGFUSE_FLUSH_INTERVAL||"10000"),release:X.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(X.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:X.LANGFUSE_ENABLED!=="false",traceName:a.trace_name||X.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:a.session_id||void 0,userId:a.user_id||void 0,tags:c.length>0?c:void 0,metadata:a||void 0};m.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Nn.handler=new i(l,t,e,n,r),m.debug("Langfuse observability initialized successfully with logging enabled");try{const h=await Jt(()=>import("langfuse"),[]).catch(()=>null);if(h){const{Langfuse:d}=h;Nn.client=new d({publicKey:X.LANGFUSE_PUBLIC_KEY,secretKey:X.LANGFUSE_SECRET_KEY,baseUrl:X.LANGFUSE_HOST||"https://cloud.langfuse.com"}),m.debug("Langfuse client initialized")}}catch(h){m.debug(`Langfuse client initialization failed: ${h}`)}}catch(s){m.debug(`Langfuse initialization error: ${s}`)}}A(Pl,"initializeLangfuse");My?m.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!X.LANGFUSE_PUBLIC_KEY||!X.LANGFUSE_SECRET_KEY?m.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Nn.initPromise=Pl();var zy=A(()=>Nn.handler,"langfuseHandler"),Hy=A(()=>Nn.initPromise,"langfuseInitPromise");const Wy=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:na,BaseConnector:to,BrowserOAuthClientProvider:Bl,BrowserTelemetry:_s,HttpConnector:Di,Logger:zl,MCPAgent:xy,MCPClient:Hl,MCPSession:Fi,ObservabilityManager:Qs,RemoteAgent:Cl,Tel:_s,Telemetry:Wn,VERSION:Wl,createLLMFromString:jo,createReadableStreamFromGenerator:Zi,getPackageVersion:eo,getSupportedProviders:kl,isValidLLMString:Tl,logger:m,onMcpAuthorization:ql,parseLLMString:Br,setBrowserTelemetrySource:Do,setTelemetrySource:Do,streamEventsToAISDK:Xi,streamEventsToAISDKWithTools:Qi},Symbol.toStringTag,{value:"Module"}));export{Hy as a,Wy as b,Pl as i,zy as l};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{_ as a,a as k}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BFDHTA3s.js","assets/index-CSfP5GPL.js","assets/index-DQ7i0BFM.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as a,a as k}from"./index-CSfP5GPL.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-BFDHTA3s.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-
|
|
1
|
+
import{g as c,q as d}from"./index-CQAG94lY.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};
|