@mcp-use/inspector 0.14.1 → 0.14.2-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +85 -73
- package/dist/client/utils/version.d.ts +8 -0
- package/dist/client/utils/version.d.ts.map +1 -0
- package/dist/server/{chunk-E4Y73JSU.js → chunk-OSJXVY3O.js} +4 -1
- package/dist/server/{chunk-OSMZGWSC.js → chunk-QCDOO2RF.js} +1 -1
- package/dist/server/cli.js +9 -2
- package/dist/server/index.js +2 -2
- package/dist/server/middleware.js +2 -2
- package/dist/server/server.d.ts.map +1 -1
- package/dist/server/server.js +9 -2
- package/dist/server/shared-routes.d.ts.map +1 -1
- package/dist/server/shared-routes.js +1 -1
- package/dist/web/assets/{browser-DlFcitTO.js → browser-Cl2hyqBR.js} +3 -3
- package/dist/web/assets/{client-B0kiUSNf.js → client-BBTHJ9hz.js} +8 -8
- package/dist/web/assets/{display-A5IEINAP-DCN-mqb-.js → display-A5IEINAP-Bj-spN90.js} +2 -2
- package/dist/web/assets/{embeddings-PkWsopkS.js → embeddings-DrV9Iibn.js} +1 -1
- package/dist/web/assets/{index-C32H1biP.js → index-BOJ_cC9T.js} +1 -1
- package/dist/web/assets/{index-bXy3E7Jj.js → index-CcIP-sZB.js} +1 -1
- package/dist/web/assets/{index-DnzC0xJC.js → index-D1URwTK7.js} +1 -1
- package/dist/web/assets/{index-jTu3K9E1.js → index-D4M_iUjy.js} +1 -1
- package/dist/web/assets/{index-D7yenyxx.js → index-D95D7M6g.js} +1 -1
- package/dist/web/assets/{index-wxr-Tnnz.js → index-DXmfJcUe.js} +1 -1
- package/dist/web/assets/{index-BcLYF5U-.js → index-DpRmkm3u.js} +131 -131
- package/dist/web/assets/{index-D2otlOyk.js → index-HgvFRYXy.js} +1 -1
- package/dist/web/assets/{index-C6pARb8N.js → index-fdbNM8aL.js} +1 -1
- package/dist/web/assets/{llms-BQE09I9T.js → llms-iMlFuJeL.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -10,6 +10,80 @@ import { cors } from "hono/cors";
|
|
|
10
10
|
import { logger } from "hono/logger";
|
|
11
11
|
import open from "open";
|
|
12
12
|
|
|
13
|
+
// src/server/shared-routes.ts
|
|
14
|
+
import { mountMcpProxy, mountOAuthProxy } from "mcp-use/server";
|
|
15
|
+
|
|
16
|
+
// src/server/rpc-log-bus.ts
|
|
17
|
+
var SimpleEventEmitter = class {
|
|
18
|
+
constructor() {
|
|
19
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Map());
|
|
20
|
+
}
|
|
21
|
+
on(event, listener) {
|
|
22
|
+
if (!this.listeners.has(event)) {
|
|
23
|
+
this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
24
|
+
}
|
|
25
|
+
this.listeners.get(event).add(listener);
|
|
26
|
+
}
|
|
27
|
+
off(event, listener) {
|
|
28
|
+
this.listeners.get(event)?.delete(listener);
|
|
29
|
+
}
|
|
30
|
+
emit(event, ...args2) {
|
|
31
|
+
this.listeners.get(event)?.forEach((listener) => {
|
|
32
|
+
try {
|
|
33
|
+
listener(...args2);
|
|
34
|
+
} catch (e) {
|
|
35
|
+
console.error("Error in event listener:", e);
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
var RpcLogBus = class {
|
|
41
|
+
constructor() {
|
|
42
|
+
__publicField(this, "emitter", new SimpleEventEmitter());
|
|
43
|
+
__publicField(this, "bufferByServer", /* @__PURE__ */ new Map());
|
|
44
|
+
}
|
|
45
|
+
publish(event) {
|
|
46
|
+
const buffer = this.bufferByServer.get(event.serverId) ?? [];
|
|
47
|
+
buffer.push(event);
|
|
48
|
+
if (buffer.length > 1e3) {
|
|
49
|
+
buffer.shift();
|
|
50
|
+
}
|
|
51
|
+
this.bufferByServer.set(event.serverId, buffer);
|
|
52
|
+
this.emitter.emit("event", event);
|
|
53
|
+
}
|
|
54
|
+
subscribe(serverIds, listener) {
|
|
55
|
+
const filter = new Set(serverIds);
|
|
56
|
+
const handler = (event) => {
|
|
57
|
+
if (filter.size === 0 || filter.has(event.serverId)) listener(event);
|
|
58
|
+
};
|
|
59
|
+
this.emitter.on("event", handler);
|
|
60
|
+
return () => this.emitter.off("event", handler);
|
|
61
|
+
}
|
|
62
|
+
getBuffer(serverIds, limit) {
|
|
63
|
+
const filter = new Set(serverIds);
|
|
64
|
+
const all = [];
|
|
65
|
+
for (const [serverId, buf] of this.bufferByServer.entries()) {
|
|
66
|
+
if (filter.size > 0 && !filter.has(serverId)) continue;
|
|
67
|
+
all.push(...buf);
|
|
68
|
+
}
|
|
69
|
+
all.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
|
|
70
|
+
if (limit === 0) return [];
|
|
71
|
+
if (!Number.isFinite(limit) || limit < 0) return all;
|
|
72
|
+
return all.slice(0, limit);
|
|
73
|
+
}
|
|
74
|
+
clear(serverIds) {
|
|
75
|
+
if (serverIds && serverIds.length > 0) {
|
|
76
|
+
const filter = new Set(serverIds);
|
|
77
|
+
for (const serverId of filter) {
|
|
78
|
+
this.bufferByServer.delete(serverId);
|
|
79
|
+
}
|
|
80
|
+
} else {
|
|
81
|
+
this.bufferByServer.clear();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var rpcLogBus = new RpcLogBus();
|
|
86
|
+
|
|
13
87
|
// src/server/shared-utils-browser.ts
|
|
14
88
|
function toBase64(str) {
|
|
15
89
|
if (typeof window !== "undefined" && typeof window.btoa === "function") {
|
|
@@ -790,79 +864,7 @@ function formatErrorResponse(error, context) {
|
|
|
790
864
|
};
|
|
791
865
|
}
|
|
792
866
|
|
|
793
|
-
// src/server/rpc-log-bus.ts
|
|
794
|
-
var SimpleEventEmitter = class {
|
|
795
|
-
constructor() {
|
|
796
|
-
__publicField(this, "listeners", /* @__PURE__ */ new Map());
|
|
797
|
-
}
|
|
798
|
-
on(event, listener) {
|
|
799
|
-
if (!this.listeners.has(event)) {
|
|
800
|
-
this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
801
|
-
}
|
|
802
|
-
this.listeners.get(event).add(listener);
|
|
803
|
-
}
|
|
804
|
-
off(event, listener) {
|
|
805
|
-
this.listeners.get(event)?.delete(listener);
|
|
806
|
-
}
|
|
807
|
-
emit(event, ...args2) {
|
|
808
|
-
this.listeners.get(event)?.forEach((listener) => {
|
|
809
|
-
try {
|
|
810
|
-
listener(...args2);
|
|
811
|
-
} catch (e) {
|
|
812
|
-
console.error("Error in event listener:", e);
|
|
813
|
-
}
|
|
814
|
-
});
|
|
815
|
-
}
|
|
816
|
-
};
|
|
817
|
-
var RpcLogBus = class {
|
|
818
|
-
constructor() {
|
|
819
|
-
__publicField(this, "emitter", new SimpleEventEmitter());
|
|
820
|
-
__publicField(this, "bufferByServer", /* @__PURE__ */ new Map());
|
|
821
|
-
}
|
|
822
|
-
publish(event) {
|
|
823
|
-
const buffer = this.bufferByServer.get(event.serverId) ?? [];
|
|
824
|
-
buffer.push(event);
|
|
825
|
-
if (buffer.length > 1e3) {
|
|
826
|
-
buffer.shift();
|
|
827
|
-
}
|
|
828
|
-
this.bufferByServer.set(event.serverId, buffer);
|
|
829
|
-
this.emitter.emit("event", event);
|
|
830
|
-
}
|
|
831
|
-
subscribe(serverIds, listener) {
|
|
832
|
-
const filter = new Set(serverIds);
|
|
833
|
-
const handler = (event) => {
|
|
834
|
-
if (filter.size === 0 || filter.has(event.serverId)) listener(event);
|
|
835
|
-
};
|
|
836
|
-
this.emitter.on("event", handler);
|
|
837
|
-
return () => this.emitter.off("event", handler);
|
|
838
|
-
}
|
|
839
|
-
getBuffer(serverIds, limit) {
|
|
840
|
-
const filter = new Set(serverIds);
|
|
841
|
-
const all = [];
|
|
842
|
-
for (const [serverId, buf] of this.bufferByServer.entries()) {
|
|
843
|
-
if (filter.size > 0 && !filter.has(serverId)) continue;
|
|
844
|
-
all.push(...buf);
|
|
845
|
-
}
|
|
846
|
-
all.sort((a, b) => b.timestamp.localeCompare(a.timestamp));
|
|
847
|
-
if (limit === 0) return [];
|
|
848
|
-
if (!Number.isFinite(limit) || limit < 0) return all;
|
|
849
|
-
return all.slice(0, limit);
|
|
850
|
-
}
|
|
851
|
-
clear(serverIds) {
|
|
852
|
-
if (serverIds && serverIds.length > 0) {
|
|
853
|
-
const filter = new Set(serverIds);
|
|
854
|
-
for (const serverId of filter) {
|
|
855
|
-
this.bufferByServer.delete(serverId);
|
|
856
|
-
}
|
|
857
|
-
} else {
|
|
858
|
-
this.bufferByServer.clear();
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
};
|
|
862
|
-
var rpcLogBus = new RpcLogBus();
|
|
863
|
-
|
|
864
867
|
// src/server/shared-routes.ts
|
|
865
|
-
import { mountMcpProxy } from "mcp-use/server";
|
|
866
868
|
function registerInspectorRoutes(app2, config) {
|
|
867
869
|
app2.get("/inspector/health", (c) => {
|
|
868
870
|
return c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
@@ -870,6 +872,9 @@ function registerInspectorRoutes(app2, config) {
|
|
|
870
872
|
mountMcpProxy(app2, {
|
|
871
873
|
path: "/inspector/api/proxy"
|
|
872
874
|
});
|
|
875
|
+
mountOAuthProxy(app2, {
|
|
876
|
+
basePath: "/inspector/api/oauth"
|
|
877
|
+
});
|
|
873
878
|
app2.post("/inspector/api/chat/stream", async (c) => {
|
|
874
879
|
try {
|
|
875
880
|
const requestBody = await c.req.json();
|
|
@@ -1463,7 +1468,14 @@ Examples:
|
|
|
1463
1468
|
}
|
|
1464
1469
|
}
|
|
1465
1470
|
var app = new Hono();
|
|
1466
|
-
app.use(
|
|
1471
|
+
app.use(
|
|
1472
|
+
"*",
|
|
1473
|
+
cors({
|
|
1474
|
+
origin: "*",
|
|
1475
|
+
exposeHeaders: ["*"]
|
|
1476
|
+
// Expose all headers since this is a proxy
|
|
1477
|
+
})
|
|
1478
|
+
);
|
|
1467
1479
|
app.use("/inspector/api/proxy/*", logger());
|
|
1468
1480
|
registerInspectorRoutes(app, { autoConnectUrl: mcpUrl });
|
|
1469
1481
|
registerStaticRoutes(app);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const VERSION = "0.14.1-canary.1";
|
|
2
|
+
/**
|
|
3
|
+
* Get the inspector package version.
|
|
4
|
+
* The version is embedded at build time via scripts/generate-version.mjs
|
|
5
|
+
* Works in all environments (Node.js, browser, Cloudflare Workers, Deno, etc.)
|
|
6
|
+
*/
|
|
7
|
+
export declare function getInspectorVersion(): string;
|
|
8
|
+
//# sourceMappingURL=version.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../../src/client/utils/version.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,oBAAoB,CAAC;AAEzC;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,CAE5C"}
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
} from "./chunk-Z5QIR3IS.js";
|
|
16
16
|
|
|
17
17
|
// src/server/shared-routes.ts
|
|
18
|
-
import { mountMcpProxy } from "mcp-use/server";
|
|
18
|
+
import { mountMcpProxy, mountOAuthProxy } from "mcp-use/server";
|
|
19
19
|
function registerInspectorRoutes(app, config) {
|
|
20
20
|
app.get("/inspector/health", (c) => {
|
|
21
21
|
return c.json({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
@@ -23,6 +23,9 @@ function registerInspectorRoutes(app, config) {
|
|
|
23
23
|
mountMcpProxy(app, {
|
|
24
24
|
path: "/inspector/api/proxy"
|
|
25
25
|
});
|
|
26
|
+
mountOAuthProxy(app, {
|
|
27
|
+
basePath: "/inspector/api/oauth"
|
|
28
|
+
});
|
|
26
29
|
app.post("/inspector/api/chat/stream", async (c) => {
|
|
27
30
|
try {
|
|
28
31
|
const requestBody = await c.req.json();
|
package/dist/server/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
registerInspectorRoutes
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-OSJXVY3O.js";
|
|
5
5
|
import {
|
|
6
6
|
findAvailablePort,
|
|
7
7
|
isValidUrl
|
|
@@ -69,7 +69,14 @@ Examples:
|
|
|
69
69
|
}
|
|
70
70
|
}
|
|
71
71
|
var app = new Hono();
|
|
72
|
-
app.use(
|
|
72
|
+
app.use(
|
|
73
|
+
"*",
|
|
74
|
+
cors({
|
|
75
|
+
origin: "*",
|
|
76
|
+
exposeHeaders: ["*"]
|
|
77
|
+
// Expose all headers since this is a proxy
|
|
78
|
+
})
|
|
79
|
+
);
|
|
73
80
|
app.use("/inspector/api/proxy/*", logger());
|
|
74
81
|
registerInspectorRoutes(app, { autoConnectUrl: mcpUrl });
|
|
75
82
|
registerStaticRoutes(app);
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/server/server.ts"],"names":[],"mappings":"AAyBA;;;;;;;;;;GAUG;AACH,iBAAe,WAAW;;;GAkFzB;;;;AAOD,wBAA+B"}
|
package/dist/server/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
registerInspectorRoutes
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-OSJXVY3O.js";
|
|
4
4
|
import {
|
|
5
5
|
isPortAvailable,
|
|
6
6
|
parsePortFromArgs
|
|
@@ -19,7 +19,14 @@ import { Hono } from "hono";
|
|
|
19
19
|
import { cors } from "hono/cors";
|
|
20
20
|
import open from "open";
|
|
21
21
|
var app = new Hono();
|
|
22
|
-
app.use(
|
|
22
|
+
app.use(
|
|
23
|
+
"*",
|
|
24
|
+
cors({
|
|
25
|
+
origin: "*",
|
|
26
|
+
exposeHeaders: ["*"]
|
|
27
|
+
// Expose all headers since this is a proxy
|
|
28
|
+
})
|
|
29
|
+
);
|
|
23
30
|
registerInspectorRoutes(app);
|
|
24
31
|
registerStaticRoutesWithDevProxy(app);
|
|
25
32
|
async function startServer() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-routes.d.ts","sourceRoot":"","sources":["../../src/server/shared-routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAiBjC;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,IAAI,EACT,MAAM,CAAC,EAAE;IAAE,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,
|
|
1
|
+
{"version":3,"file":"shared-routes.d.ts","sourceRoot":"","sources":["../../src/server/shared-routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAiBjC;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,IAAI,EACT,MAAM,CAAC,EAAE;IAAE,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,QAqiB5C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-
|
|
2
|
-
import{O as co,P as Rl,Q as jl,_ as N,o as we,l as m,s as br,S as ke,Z as Mr,w as Ar,j as Ll,n as Dl,i as Fl,U as Ul,V as Vl,W as Bl,p as ti,e as zl,X as Pr,Y as uo,a as Ut,x as $n}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-BBTHJ9hz.js","assets/index-DpRmkm3u.js","assets/index-G80eS8Oh.css","assets/display-A5IEINAP-Bj-spN90.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{O as co,P as Rl,Q as jl,_ as N,o as we,l as m,s as br,S as ke,Z as Mr,w as Ar,j as Ll,n as Dl,i as Fl,U as Ul,V as Vl,W as Bl,p as ti,e as zl,X as Pr,Y as uo,a as Ut,x as $n}from"./index-DpRmkm3u.js";import{B as fg,a0 as pg,T as mg,H as gg,a1 as yg,a2 as wg,M as vg,T as bg,a3 as _g,a4 as Sg,a5 as Cg,a5 as kg}from"./index-DpRmkm3u.js";import{D as Rn,S as _r,t as Wl,a as ni,T as Hl,b as Gl}from"./index-HgvFRYXy.js";import{h as Cn,s as Kl,k as ql,I as Jl,C as Yl,g as ri,d as Xl,l as Zl,m as Ql,t as ec,n as tc,o as nc,p as rc,q as sc,r as oc,u as ic,v as ac,w as lc,x as cc,y as uc,R as hc,z as dc,e as fc}from"./index-D95D7M6g.js";import{aT as pc,aU as Ps,aV as mc,aw as Oe,e as nn,aW as gc,aX as hn,a4 as fe,y as Ee,aY as si,i as yc,aZ as Qr,g as J,aj as Xt,ah as pe,B as O,S as Q,p as wc,C as vc,a_ as bc,aE as oi,a$ as _e,al as dn,b0 as an,F as ii,z as je,b1 as Os,u as ho,D as es,E as Vt,ap as Bt,b2 as _c,b3 as Sc,b4 as Cc,b5 as kc,b6 as Tc,b7 as Ec,b8 as xc,b9 as Mc,ba as Ac,bb as Pc,bc as Oc,bd as Nc,be as Ic,bf as $c,bg as Rc,bh as jc,bi as Lc,L as Dc,bj as Fc,bk as Uc,bl as Vc,A as Ve,k as ln,m as Fe,M as tt,at as zt,bm as Bc,H as zc,aF as fo,au as Wc,bn as po,bo as mo,af as Ns,ae as go,ad as ts,ag as Hc,V as Gc,a9 as Is,ac as Xe,bp as tr,o as z,bq as le,br as Kc,bs as Ie,bt as Ct,bu as qc,bv as $s,f as U,aa as Jc,r as Yc,T as Xc,bw as nr,bx as We,by as V,bz as ai,s as ne,ab as Zc,bA as jn,bB as li,bC as Wt,bD as fn,bE as rr,bF as sr,bG as Qc,aP as eu,aN as tu,aM as nu,bH as ru}from"./index-BOJ_cC9T.js";import{E as ci,c as su,e as ou}from"./embeddings-DrV9Iibn.js";import{L as ui,o as iu,l as au}from"./llms-iMlFuJeL.js";const lu=t=>{const e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},cu=()=>{const t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}const n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${lu(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Rl(r.values[0])}`:`Invalid option: expected one of ${co(r.values,"|")}`;case"too_big":{const s=r.inclusive?"<=":"<",o=e(r.origin);return o?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{const s=r.inclusive?">=":">",o=e(r.origin);return o?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${o.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{const s=r;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${co(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function uu(){return{localeError:cu()}}jl(uu());var Or,Mn,Nr=0,Ir=0;function hu(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=Or),i==null&&(i=Mn)),o==null||i==null){var a=t.random||(t.rng||pc)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Or&&!t._v6&&(o[0]|=1,Or=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Mn===void 0&&!t._v6&&(Mn=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Ir+1,u=l-Nr+(c-Ir)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Nr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Nr=l,Ir=c,Mn=i,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||Ps(s)}function du(t){var e=typeof t=="string"?mc(t):t,n=fu(e);return typeof t=="string"?Ps(n):n}function fu(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 yo(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 wo(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?yo(Object(n),!0).forEach(function(r){pu(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):yo(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function pu(t,e,n){return(e=mu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mu(t){var e=gu(t,"string");return typeof e=="symbol"?e:e+""}function gu(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 yu(t={},e,n=0){var r=hu(wo(wo({},t),{},{_v6:!0}),new Uint8Array(16));return r=du(r),Ps(r)}async function*wu(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)}}N(wu,"streamEventsToAISDK");function vu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}N(vu,"createReadableStreamFromGenerator");async function*bu(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}
|
|
@@ -374,7 +374,7 @@ You can then use these server-specific tools in subsequent steps.
|
|
|
374
374
|
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
375
375
|
change when you connect to a server):
|
|
376
376
|
{tool_descriptions}
|
|
377
|
-
`;function er(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}}N(er,"normalizeRunOptions");var Ft,ug=(Ft=class{static getPackageVersion(){return zl()}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 qm({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 gt,this.telemetry=Pr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Zo({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 gt(this.disallowedTools),this.telemetry=Pr.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 gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Xo(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Pr.getInstance(),this.llm){const[r,s]=uo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Zo({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:N(()=>this.getMetadata(),"metadataProvider"),tagsProvider:N(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:N(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:N(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:N(()=>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)...`);const{MCPClient:r}=await Ut(async()=>{const{MCPClient:s}=await import("./client-B0kiUSNf.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")}if(this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await Ol(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=uo(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 Xo(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??Xm;this.systemMessage=$l(e,n,Zm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof _e))])}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=[Ml({runLimit:this.maxSteps})],s=yl({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 _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),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 gt(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 O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof 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 O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=er(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,l,c,u);const h=this.stream(i,a,l,c,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=er(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,l,c,u);let h=!1;const d=Date.now();let f=!1,g=null,p=0;try{if(l&&!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 M=this.serverManager.tools,w=new Set(M.map(T=>T.name)),v=new Set(this._tools.map(T=>T.name));(w.size!==v.size||[...w].some(T=>!v.has(T)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=M,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const M of S)(this._isHumanMessageLike(M)||this._isAIMessageLike(M)||this._isToolMessageLike(M))&&C.push(M);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 b=0;const k=[...C,new pe(i)];for(;b<=_;){const M={messages:k};let w=!1;const v=await this._agentExecutor.stream(M,{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 T of v){for(const[x,A]of Object.entries(T))if(m.debug(`📦 Node '${x}' output: ${JSON.stringify(A)}`),A&&typeof A=="object"&&"messages"in A){let I=A.messages;Array.isArray(I)||(I=[I]);for(const j of I)k.includes(j)||k.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(en=>en.name)),xn=new Set(this._tools.map(en=>en.name));if(Me.size!==xn.size||[...Me].some(en=>!xn.has(en))){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(),w=!0,b++,m.info(`🔃 Restarting execution with updated tools (restart ${b}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(b>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const M=k.slice(C.length);for(const w of M)this.addToHistory(w)}if(u&&g)try{m.info("🔧 Attempting structured output...");const M=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(M)}`)),m.info("✅ Structured output successful"),f=!0,M}catch(M){throw m.error(`❌ Structured output failed: ${M}`),new Error(`Failed to generate structured output: ${M instanceof Error?M.message:String(M)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(S){throw m.error(`❌ Error running query: ${S}`),h&&l&&(m.info("🧹 Cleaning up resources after error"),await this.close()),S}finally{const S=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(b=>b.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(b=>b.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:y}),l&&!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 gt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ut(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-DCN-mqb-.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=er(e,n,r,s,o);let{query:a}=i;const{maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let g=!1,p=0,S=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{c&&!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=l??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 b=u??this.conversationHistory,k=[];for(const v of b)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?k.push(v):m.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const M=[...k,new pe(a)];m.info("callbacks",this.callbacks);const w=y.streamEvents({messages:M},{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 v of w)if(p++,!(!v||typeof v!="object")){if(v.event==="on_chat_model_stream"&&v.data?.chunk?.content&&(S+=v.data.chunk.content.length),v.event==="on_chat_model_stream"&&v.data?.chunk){const T=v.data.chunk;if(T.content){C||(C="");const x=this._normalizeOutput(T.content);C+=x,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const T=v.data.output;Array.isArray(T)&&T.length>0&&T[0]?.text?C=T[0].text:typeof T=="string"?C=T:T&&typeof T=="object"&&"output"in T&&(C=T.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let v=!1,T=null,x=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(v=!0,T=I,I)).catch(I=>{throw v=!0,x=I,I});let A=0;for(;!v;)await new Promise(I=>setTimeout(I,2e3)),v||(A++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${A*2}s)`,elapsed:A*2}});if(x)throw x;T&&(yield{event:"on_structured_output",data:{output:T}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"))}catch(v){m.warn(`⚠️ Structured output failed: ${v}`),yield{event:"on_structured_output_error",data:{error:v instanceof Error?v.message:String(v)}}}}else this.memoryEnabled&&C&&this.addToHistory(new O(C));console.log(`
|
|
377
|
+
`;function er(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}}N(er,"normalizeRunOptions");var Ft,ug=(Ft=class{static getPackageVersion(){return zl()}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 qm({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 gt,this.telemetry=Pr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Zo({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 gt(this.disallowedTools),this.telemetry=Pr.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 gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Xo(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Pr.getInstance(),this.llm){const[r,s]=uo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Zo({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:N(()=>this.getMetadata(),"metadataProvider"),tagsProvider:N(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:N(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:N(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:N(()=>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)...`);const{MCPClient:r}=await Ut(async()=>{const{MCPClient:s}=await import("./client-BBTHJ9hz.js");return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),m.info("✅ MCPClient created successfully")}if(this.llmString){m.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await Ol(this.llmString,this.llmConfig),m.info("✅ LLM created successfully");const[r,s]=uo(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 Xo(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??Xm;this.systemMessage=$l(e,n,Zm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof _e))])}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=[Ml({runLimit:this.maxSteps})],s=yl({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 _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),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 gt(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 O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof 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 O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=er(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(i,a,l,c,u);const h=this.stream(i,a,l,c,u);return this._consumeAndReturn(h)}async*stream(e,n,r=!0,s,o){const{query:i,maxSteps:a,manageConnector:l,externalHistory:c,outputSchema:u}=er(e,n,r,s,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(i,a,l,c,u);let h=!1;const d=Date.now();let f=!1,g=null,p=0;try{if(l&&!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 M=this.serverManager.tools,w=new Set(M.map(T=>T.name)),v=new Set(this._tools.map(T=>T.name));(w.size!==v.size||[...w].some(T=>!v.has(T)))&&(m.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=M,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const S=c??this.conversationHistory,C=[];for(const M of S)(this._isHumanMessageLike(M)||this._isAIMessageLike(M)||this._isToolMessageLike(M))&&C.push(M);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 b=0;const k=[...C,new pe(i)];for(;b<=_;){const M={messages:k};let w=!1;const v=await this._agentExecutor.stream(M,{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 T of v){for(const[x,A]of Object.entries(T))if(m.debug(`📦 Node '${x}' output: ${JSON.stringify(A)}`),A&&typeof A=="object"&&"messages"in A){let I=A.messages;Array.isArray(I)||(I=[I]);for(const j of I)k.includes(j)||k.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(en=>en.name)),xn=new Set(this._tools.map(en=>en.name));if(Me.size!==xn.size||[...Me].some(en=>!xn.has(en))){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(),w=!0,b++,m.info(`🔃 Restarting execution with updated tools (restart ${b}/${_})`);break}}}this._isAIMessageLike(j)&&!this._messageHasToolCalls(j)&&(g=this._normalizeOutput(this._getMessageContent(j)),m.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(b>_){m.warn(`⚠️ Max restarts (${_}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const M=k.slice(C.length);for(const w of M)this.addToHistory(w)}if(u&&g)try{m.info("🔧 Attempting structured output...");const M=await this._attemptStructuredOutput(g,this.llm,u);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(M)}`)),m.info("✅ Structured output successful"),f=!0,M}catch(M){throw m.error(`❌ Structured output failed: ${M}`),new Error(`Failed to generate structured output: ${M instanceof Error?M.message:String(M)}`)}return m.info(`🎉 Agent execution complete in ${((Date.now()-d)/1e3).toFixed(2)} seconds`),f=!0,g||"No output generated"}catch(S){throw m.error(`❌ Error running query: ${S}`),h&&l&&(m.info("🧹 Cleaning up resources after error"),await this.close()),S}finally{const S=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(b=>b.publicIdentifier),totalToolsAvailable:_.length,toolsAvailableNames:_.map(b=>b.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:a??null,manageConnector:l??!0,externalHistoryUsed:c!==void 0,stepsTaken:p,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||"",executionTimeMs:S,errorType:f?null:"execution_error",conversationHistoryLength:y}),l&&!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 gt)}finally{this._initialized=!1,m.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await Ut(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-Bj-spN90.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o){const i=er(e,n,r,s,o);let{query:a}=i;const{maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:h}=i;let d=!1;const f=Date.now();let g=!1,p=0,S=0,C="";h&&(a=this._enhanceQueryWithSchema(a,h));try{c&&!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=l??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 b=u??this.conversationHistory,k=[];for(const v of b)this._isHumanMessageLike(v)||this._isAIMessageLike(v)||this._isToolMessageLike(v)?k.push(v):m.info(`⚠️ Skipped message of type: ${v.constructor?.name||typeof v}`);const M=[...k,new pe(a)];m.info("callbacks",this.callbacks);const w=y.streamEvents({messages:M},{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 v of w)if(p++,!(!v||typeof v!="object")){if(v.event==="on_chat_model_stream"&&v.data?.chunk?.content&&(S+=v.data.chunk.content.length),v.event==="on_chat_model_stream"&&v.data?.chunk){const T=v.data.chunk;if(T.content){C||(C="");const x=this._normalizeOutput(T.content);C+=x,m.debug(`📝 Accumulated response length: ${C.length}`)}}if(yield v,v.event==="on_chain_end"&&v.data?.output&&!C){const T=v.data.output;Array.isArray(T)&&T.length>0&&T[0]?.text?C=T[0].text:typeof T=="string"?C=T:T&&typeof T=="object"&&"output"in T&&(C=T.output)}}if(h&&C){m.info("🔧 Attempting structured output conversion...");try{let v=!1,T=null,x=null;this._attemptStructuredOutput(C,this.llm,h).then(I=>(v=!0,T=I,I)).catch(I=>{throw v=!0,x=I,I});let A=0;for(;!v;)await new Promise(I=>setTimeout(I,2e3)),v||(A++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${A*2}s)`,elapsed:A*2}});if(x)throw x;T&&(yield{event:"on_structured_output",data:{output:T}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(T)}`)),m.info("✅ Structured output successful"))}catch(v){m.warn(`⚠️ Structured output failed: ${v}`),yield{event:"on_structured_output_error",data:{error:v instanceof Error?v.message:String(v)}}}}else this.memoryEnabled&&C&&this.addToHistory(new O(C));console.log(`
|
|
378
378
|
|
|
379
379
|
`),m.info(`🎉 StreamEvents complete - ${p} events emitted`),g=!0}catch(y){throw m.error(`❌ Error during streamEvents: ${y}`),d&&c&&(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 b=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(k=>k.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(k=>k.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,response:`[STREAMED RESPONSE - ${S} chars]`,executionTimeMs:y,errorType:g?null:"streaming_error",conversationHistoryLength:b}),c&&!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($n(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=$n(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,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=`
|
|
380
380
|
Please format the following information according to the EXACT schema specified below.
|