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