agents 0.0.79 → 0.0.81
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/ai-chat-agent.d.ts +27 -1
- package/dist/ai-chat-agent.js +100 -103
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +11 -0
- package/dist/ai-react.js +1 -1
- package/dist/chunk-BZXOAZUX.js +106 -0
- package/dist/chunk-BZXOAZUX.js.map +1 -0
- package/dist/{chunk-HMLY7DHA.js → chunk-NOUFNU2O.js} +1 -5
- package/dist/{chunk-JR3NW4A7.js → chunk-NPGUKHFR.js} +245 -93
- package/dist/chunk-NPGUKHFR.js.map +1 -0
- package/dist/chunk-QSGN3REV.js +123 -0
- package/dist/chunk-QSGN3REV.js.map +1 -0
- package/dist/{chunk-7VFQNJFK.js → chunk-Y67CHZBI.js} +25 -23
- package/dist/chunk-Y67CHZBI.js.map +1 -0
- package/dist/client.d.ts +9 -1
- package/dist/client.js +7 -126
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +60 -3
- package/dist/index.js +5 -3
- package/dist/mcp/client.d.ts +13 -15
- package/dist/mcp/client.js +2 -2
- package/dist/mcp/do-oauth-client-provider.d.ts +3 -3
- package/dist/mcp/do-oauth-client-provider.js +4 -103
- package/dist/mcp/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/index.d.ts +10 -1
- package/dist/mcp/index.js +86 -122
- package/dist/mcp/index.js.map +1 -1
- package/dist/react.d.ts +14 -0
- package/dist/react.js +5 -1
- package/dist/react.js.map +1 -1
- package/dist/schedule.js +1 -1
- package/package.json +1 -1
- package/src/index.ts +330 -43
- package/dist/chunk-7VFQNJFK.js.map +0 -1
- package/dist/chunk-JR3NW4A7.js.map +0 -1
- /package/dist/{chunk-HMLY7DHA.js.map → chunk-NOUFNU2O.js.map} +0 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import {
|
|
3
|
+
PartySocket
|
|
4
|
+
} from "partysocket";
|
|
5
|
+
function camelCaseToKebabCase(str) {
|
|
6
|
+
if (str === str.toUpperCase() && str !== str.toLowerCase()) {
|
|
7
|
+
return str.toLowerCase().replace(/_/g, "-");
|
|
8
|
+
}
|
|
9
|
+
let kebabified = str.replace(
|
|
10
|
+
/[A-Z]/g,
|
|
11
|
+
(letter) => `-${letter.toLowerCase()}`
|
|
12
|
+
);
|
|
13
|
+
kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
|
|
14
|
+
return kebabified.replace(/_/g, "-").replace(/-$/, "");
|
|
15
|
+
}
|
|
16
|
+
var AgentClient = class extends PartySocket {
|
|
17
|
+
constructor(options) {
|
|
18
|
+
const agentNamespace = camelCaseToKebabCase(options.agent);
|
|
19
|
+
super({
|
|
20
|
+
prefix: "agents",
|
|
21
|
+
party: agentNamespace,
|
|
22
|
+
room: options.name || "default",
|
|
23
|
+
...options
|
|
24
|
+
});
|
|
25
|
+
this._pendingCalls = /* @__PURE__ */ new Map();
|
|
26
|
+
this.agent = agentNamespace;
|
|
27
|
+
this.name = options.name || "default";
|
|
28
|
+
this.options = options;
|
|
29
|
+
this.addEventListener("message", (event) => {
|
|
30
|
+
if (typeof event.data === "string") {
|
|
31
|
+
let parsedMessage;
|
|
32
|
+
try {
|
|
33
|
+
parsedMessage = JSON.parse(event.data);
|
|
34
|
+
} catch (error) {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (parsedMessage.type === "cf_agent_state") {
|
|
38
|
+
this.options.onStateUpdate?.(parsedMessage.state, "server");
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (parsedMessage.type === "rpc") {
|
|
42
|
+
const response = parsedMessage;
|
|
43
|
+
const pending = this._pendingCalls.get(response.id);
|
|
44
|
+
if (!pending) return;
|
|
45
|
+
if (!response.success) {
|
|
46
|
+
pending.reject(new Error(response.error));
|
|
47
|
+
this._pendingCalls.delete(response.id);
|
|
48
|
+
pending.stream?.onError?.(response.error);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if ("done" in response) {
|
|
52
|
+
if (response.done) {
|
|
53
|
+
pending.resolve(response.result);
|
|
54
|
+
this._pendingCalls.delete(response.id);
|
|
55
|
+
pending.stream?.onDone?.(response.result);
|
|
56
|
+
} else {
|
|
57
|
+
pending.stream?.onChunk?.(response.result);
|
|
58
|
+
}
|
|
59
|
+
} else {
|
|
60
|
+
pending.resolve(response.result);
|
|
61
|
+
this._pendingCalls.delete(response.id);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* @deprecated Use agentFetch instead
|
|
69
|
+
*/
|
|
70
|
+
static fetch(_opts) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
"AgentClient.fetch is not implemented, use agentFetch instead"
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
setState(state) {
|
|
76
|
+
this.send(JSON.stringify({ type: "cf_agent_state", state }));
|
|
77
|
+
this.options.onStateUpdate?.(state, "client");
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Call a method on the Agent
|
|
81
|
+
* @param method Name of the method to call
|
|
82
|
+
* @param args Arguments to pass to the method
|
|
83
|
+
* @param streamOptions Options for handling streaming responses
|
|
84
|
+
* @returns Promise that resolves with the method's return value
|
|
85
|
+
*/
|
|
86
|
+
async call(method, args = [], streamOptions) {
|
|
87
|
+
return new Promise((resolve, reject) => {
|
|
88
|
+
const id = Math.random().toString(36).slice(2);
|
|
89
|
+
this._pendingCalls.set(id, {
|
|
90
|
+
resolve: (value) => resolve(value),
|
|
91
|
+
reject,
|
|
92
|
+
stream: streamOptions,
|
|
93
|
+
type: null
|
|
94
|
+
});
|
|
95
|
+
const request = {
|
|
96
|
+
type: "rpc",
|
|
97
|
+
id,
|
|
98
|
+
method,
|
|
99
|
+
args
|
|
100
|
+
};
|
|
101
|
+
this.send(JSON.stringify(request));
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
function agentFetch(opts, init) {
|
|
106
|
+
const agentNamespace = camelCaseToKebabCase(opts.agent);
|
|
107
|
+
return PartySocket.fetch(
|
|
108
|
+
{
|
|
109
|
+
prefix: "agents",
|
|
110
|
+
party: agentNamespace,
|
|
111
|
+
room: opts.name || "default",
|
|
112
|
+
...opts
|
|
113
|
+
},
|
|
114
|
+
init
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export {
|
|
119
|
+
camelCaseToKebabCase,
|
|
120
|
+
AgentClient,
|
|
121
|
+
agentFetch
|
|
122
|
+
};
|
|
123
|
+
//# sourceMappingURL=chunk-QSGN3REV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import {\n PartySocket,\n type PartySocketOptions,\n type PartyFetchOptions,\n} from \"partysocket\";\nimport type { RPCRequest, RPCResponse } from \"./\";\n\n/**\n * Options for creating an AgentClient\n */\nexport type AgentClientOptions<State = unknown> = Omit<\n PartySocketOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n /** Called when the Agent's state is updated */\n onStateUpdate?: (state: State, source: \"server\" | \"client\") => void;\n};\n\n/**\n * Options for streaming RPC calls\n */\nexport type StreamOptions = {\n /** Called when a chunk of data is received */\n onChunk?: (chunk: unknown) => void;\n /** Called when the stream ends */\n onDone?: (finalChunk: unknown) => void;\n /** Called when an error occurs */\n onError?: (error: string) => void;\n};\n\n/**\n * Options for the agentFetch function\n */\nexport type AgentClientFetchOptions = Omit<\n PartyFetchOptions,\n \"party\" | \"room\"\n> & {\n /** Name of the agent to connect to */\n agent: string;\n /** Name of the specific Agent instance */\n name?: string;\n};\n\n/**\n * Convert a camelCase string to a kebab-case string\n * @param str The string to convert\n * @returns The kebab-case string\n */\nexport function camelCaseToKebabCase(str: string): string {\n // If string is all uppercase, convert to lowercase\n if (str === str.toUpperCase() && str !== str.toLowerCase()) {\n return str.toLowerCase().replace(/_/g, \"-\");\n }\n\n // Otherwise handle camelCase to kebab-case\n let kebabified = str.replace(\n /[A-Z]/g,\n (letter) => `-${letter.toLowerCase()}`\n );\n kebabified = kebabified.startsWith(\"-\") ? kebabified.slice(1) : kebabified;\n // Convert any remaining underscores to hyphens and remove trailing -'s\n return kebabified.replace(/_/g, \"-\").replace(/-$/, \"\");\n}\n\n/**\n * WebSocket client for connecting to an Agent\n */\nexport class AgentClient<State = unknown> extends PartySocket {\n /**\n * @deprecated Use agentFetch instead\n */\n static fetch(_opts: PartyFetchOptions): Promise<Response> {\n throw new Error(\n \"AgentClient.fetch is not implemented, use agentFetch instead\"\n );\n }\n agent: string;\n name: string;\n private options: AgentClientOptions<State>;\n private _pendingCalls = new Map<\n string,\n {\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n stream?: StreamOptions;\n type?: unknown;\n }\n >();\n\n constructor(options: AgentClientOptions<State>) {\n const agentNamespace = camelCaseToKebabCase(options.agent);\n super({\n prefix: \"agents\",\n party: agentNamespace,\n room: options.name || \"default\",\n ...options,\n });\n this.agent = agentNamespace;\n this.name = options.name || \"default\";\n this.options = options;\n\n this.addEventListener(\"message\", (event) => {\n if (typeof event.data === \"string\") {\n let parsedMessage: Record<string, unknown>;\n try {\n parsedMessage = JSON.parse(event.data);\n } catch (error) {\n // silently ignore invalid messages for now\n // TODO: log errors with log levels\n return;\n }\n if (parsedMessage.type === \"cf_agent_state\") {\n this.options.onStateUpdate?.(parsedMessage.state as State, \"server\");\n return;\n }\n if (parsedMessage.type === \"rpc\") {\n const response = parsedMessage as RPCResponse;\n const pending = this._pendingCalls.get(response.id);\n if (!pending) return;\n\n if (!response.success) {\n pending.reject(new Error(response.error));\n this._pendingCalls.delete(response.id);\n pending.stream?.onError?.(response.error);\n return;\n }\n\n // Handle streaming responses\n if (\"done\" in response) {\n if (response.done) {\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n pending.stream?.onDone?.(response.result);\n } else {\n pending.stream?.onChunk?.(response.result);\n }\n } else {\n // Non-streaming response\n pending.resolve(response.result);\n this._pendingCalls.delete(response.id);\n }\n }\n }\n });\n }\n\n setState(state: State) {\n this.send(JSON.stringify({ type: \"cf_agent_state\", state }));\n this.options.onStateUpdate?.(state, \"client\");\n }\n\n /**\n * Call a method on the Agent\n * @param method Name of the method to call\n * @param args Arguments to pass to the method\n * @param streamOptions Options for handling streaming responses\n * @returns Promise that resolves with the method's return value\n */\n async call<T = unknown>(\n method: string,\n args: unknown[] = [],\n streamOptions?: StreamOptions\n ): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const id = Math.random().toString(36).slice(2);\n this._pendingCalls.set(id, {\n resolve: (value: unknown) => resolve(value as T),\n reject,\n stream: streamOptions,\n type: null as T,\n });\n\n const request: RPCRequest = {\n type: \"rpc\",\n id,\n method,\n args,\n };\n\n this.send(JSON.stringify(request));\n });\n }\n}\n\n/**\n * Make an HTTP request to an Agent\n * @param opts Connection options\n * @param init Request initialization options\n * @returns Promise resolving to a Response\n */\nexport function agentFetch(opts: AgentClientFetchOptions, init?: RequestInit) {\n const agentNamespace = camelCaseToKebabCase(opts.agent);\n\n return PartySocket.fetch(\n {\n prefix: \"agents\",\n party: agentNamespace,\n room: opts.name || \"default\",\n ...opts,\n },\n init\n );\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAGK;AAgDA,SAAS,qBAAqB,KAAqB;AAExD,MAAI,QAAQ,IAAI,YAAY,KAAK,QAAQ,IAAI,YAAY,GAAG;AAC1D,WAAO,IAAI,YAAY,EAAE,QAAQ,MAAM,GAAG;AAAA,EAC5C;AAGA,MAAI,aAAa,IAAI;AAAA,IACnB;AAAA,IACA,CAAC,WAAW,IAAI,OAAO,YAAY,CAAC;AAAA,EACtC;AACA,eAAa,WAAW,WAAW,GAAG,IAAI,WAAW,MAAM,CAAC,IAAI;AAEhE,SAAO,WAAW,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C/B,iBAAK,cAAc,OAAO,SAAS,EAAE;AAAA,UACvC;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAzEA,OAAO,MAAM,OAA6C;AACxD,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EAuEA,SAAS,OAAc;AACrB,SAAK,KAAK,KAAK,UAAU,EAAE,MAAM,kBAAkB,MAAM,CAAC,CAAC;AAC3D,SAAK,QAAQ,gBAAgB,OAAO,QAAQ;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,KACJ,QACA,OAAkB,CAAC,GACnB,eACY;AACZ,WAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACzC,YAAM,KAAK,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC;AAC7C,WAAK,cAAc,IAAI,IAAI;AAAA,QACzB,SAAS,CAAC,UAAmB,QAAQ,KAAU;AAAA,QAC/C;AAAA,QACA,QAAQ;AAAA,QACR,MAAM;AAAA,MACR,CAAC;AAED,YAAM,UAAsB;AAAA,QAC1B,MAAM;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAEA,WAAK,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,IACnC,CAAC;AAAA,EACH;AACF;AAQO,SAAS,WAAW,MAA+B,MAAoB;AAC5E,QAAM,iBAAiB,qBAAqB,KAAK,KAAK;AAEtD,SAAO,YAAY;AAAA,IACjB;AAAA,MACE,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,MAAM,KAAK,QAAQ;AAAA,MACnB,GAAG;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
@@ -53,7 +53,7 @@ import {
|
|
|
53
53
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
54
54
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
55
55
|
var MCPClientConnection = class {
|
|
56
|
-
constructor(url, info, options = { transport: {}, client: {}
|
|
56
|
+
constructor(url, info, options = { transport: {}, client: {} }) {
|
|
57
57
|
this.url = url;
|
|
58
58
|
this.options = options;
|
|
59
59
|
this.connectionState = "connecting";
|
|
@@ -62,7 +62,6 @@ var MCPClientConnection = class {
|
|
|
62
62
|
this.resources = [];
|
|
63
63
|
this.resourceTemplates = [];
|
|
64
64
|
this.client = new Client(info, options.client);
|
|
65
|
-
this.client.registerCapabilities(options.capabilities);
|
|
66
65
|
}
|
|
67
66
|
/**
|
|
68
67
|
* Initialize a client connection
|
|
@@ -70,7 +69,7 @@ var MCPClientConnection = class {
|
|
|
70
69
|
* @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized
|
|
71
70
|
* @returns
|
|
72
71
|
*/
|
|
73
|
-
async init(code
|
|
72
|
+
async init(code) {
|
|
74
73
|
try {
|
|
75
74
|
const transport = new SSEEdgeClientTransport(
|
|
76
75
|
this.url,
|
|
@@ -227,15 +226,15 @@ import { jsonSchema } from "ai";
|
|
|
227
226
|
import { nanoid } from "nanoid";
|
|
228
227
|
var MCPClientManager = class {
|
|
229
228
|
/**
|
|
230
|
-
* @param
|
|
231
|
-
* @param
|
|
229
|
+
* @param _name Name of the MCP client
|
|
230
|
+
* @param _version Version of the MCP Client
|
|
232
231
|
* @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
|
|
233
232
|
*/
|
|
234
|
-
constructor(
|
|
235
|
-
this.
|
|
236
|
-
this.
|
|
233
|
+
constructor(_name, _version) {
|
|
234
|
+
this._name = _name;
|
|
235
|
+
this._version = _version;
|
|
237
236
|
this.mcpConnections = {};
|
|
238
|
-
this.
|
|
237
|
+
this._callbackUrls = [];
|
|
239
238
|
}
|
|
240
239
|
/**
|
|
241
240
|
* Connect to and register an MCP server
|
|
@@ -252,42 +251,45 @@ var MCPClientManager = class {
|
|
|
252
251
|
);
|
|
253
252
|
} else {
|
|
254
253
|
options.transport.authProvider.serverId = id;
|
|
254
|
+
if (options.reconnect?.oauthClientId) {
|
|
255
|
+
options.transport.authProvider.clientId = options.reconnect?.oauthClientId;
|
|
256
|
+
}
|
|
255
257
|
}
|
|
256
258
|
this.mcpConnections[id] = new MCPClientConnection(
|
|
257
259
|
new URL(url),
|
|
258
260
|
{
|
|
259
|
-
name: this.
|
|
260
|
-
version: this.
|
|
261
|
+
name: this._name,
|
|
262
|
+
version: this._version
|
|
261
263
|
},
|
|
262
264
|
{
|
|
263
265
|
transport: options.transport ?? {},
|
|
264
|
-
client: options.client ?? {}
|
|
265
|
-
capabilities: options.client ?? {}
|
|
266
|
+
client: options.client ?? {}
|
|
266
267
|
}
|
|
267
268
|
);
|
|
268
|
-
await this.mcpConnections[id].init(
|
|
269
|
-
options.reconnect?.oauthCode,
|
|
270
|
-
options.reconnect?.oauthClientId
|
|
271
|
-
);
|
|
269
|
+
await this.mcpConnections[id].init(options.reconnect?.oauthCode);
|
|
272
270
|
const authUrl = options.transport?.authProvider?.authUrl;
|
|
273
271
|
if (authUrl && options.transport?.authProvider?.redirectUrl) {
|
|
274
|
-
this.
|
|
272
|
+
this._callbackUrls.push(
|
|
275
273
|
options.transport.authProvider.redirectUrl.toString()
|
|
276
274
|
);
|
|
275
|
+
return {
|
|
276
|
+
id,
|
|
277
|
+
authUrl,
|
|
278
|
+
clientId: options.transport?.authProvider?.clientId
|
|
279
|
+
};
|
|
277
280
|
}
|
|
278
281
|
return {
|
|
279
|
-
id
|
|
280
|
-
authUrl
|
|
282
|
+
id
|
|
281
283
|
};
|
|
282
284
|
}
|
|
283
285
|
isCallbackRequest(req) {
|
|
284
|
-
return req.method === "GET" && !!this.
|
|
286
|
+
return req.method === "GET" && !!this._callbackUrls.find((url) => {
|
|
285
287
|
return req.url.startsWith(url);
|
|
286
288
|
});
|
|
287
289
|
}
|
|
288
290
|
async handleCallbackRequest(req) {
|
|
289
291
|
const url = new URL(req.url);
|
|
290
|
-
const urlMatch = this.
|
|
292
|
+
const urlMatch = this._callbackUrls.find((url2) => {
|
|
291
293
|
return req.url.startsWith(url2);
|
|
292
294
|
});
|
|
293
295
|
if (!urlMatch) {
|
|
@@ -459,4 +461,4 @@ export {
|
|
|
459
461
|
MCPClientManager,
|
|
460
462
|
getNamespacedData
|
|
461
463
|
};
|
|
462
|
-
//# sourceMappingURL=chunk-
|
|
464
|
+
//# sourceMappingURL=chunk-Y67CHZBI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mcp/sse-edge.ts","../src/mcp/client-connection.ts","../src/mcp/client.ts"],"sourcesContent":["import {\n SSEClientTransport,\n type SSEClientTransportOptions,\n} from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\n\nexport class SSEEdgeClientTransport extends SSEClientTransport {\n private authProvider: OAuthClientProvider | undefined;\n /**\n * Creates a new EdgeSSEClientTransport, which overrides fetch to be compatible with the CF workers environment\n */\n constructor(url: URL, options: SSEClientTransportOptions) {\n const fetchOverride: typeof fetch = async (\n fetchUrl: RequestInfo | URL,\n fetchInit: RequestInit = {}\n ) => {\n // add auth headers\n const headers = await this.authHeaders();\n const workerOptions = {\n ...fetchInit,\n headers: {\n ...options.requestInit?.headers,\n ...fetchInit?.headers,\n ...headers,\n },\n };\n\n // Remove unsupported properties\n // biome-ignore lint/performance/noDelete: workaround for workers environment\n delete workerOptions.mode;\n\n // Call the original fetch with fixed options\n return (\n (options.eventSourceInit?.fetch?.(\n fetchUrl as URL | string,\n // @ts-expect-error Expects FetchLikeInit from EventSource but is compatible with RequestInit\n workerOptions\n ) as Promise<Response>) || fetch(fetchUrl, workerOptions)\n );\n };\n\n super(url, {\n ...options,\n eventSourceInit: {\n ...options.eventSourceInit,\n fetch: fetchOverride,\n },\n });\n this.authProvider = options.authProvider;\n }\n\n async authHeaders() {\n if (this.authProvider) {\n const tokens = await this.authProvider.tokens();\n if (tokens) {\n return {\n Authorization: `Bearer ${tokens.access_token}`,\n };\n }\n }\n }\n}\n","import { SSEEdgeClientTransport } from \"./sse-edge\";\n\nimport {\n ToolListChangedNotificationSchema,\n type ClientCapabilities,\n type Resource,\n type Tool,\n type Prompt,\n ResourceListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n type ListToolsResult,\n type ListResourcesResult,\n type ListPromptsResult,\n type ServerCapabilities,\n type ResourceTemplate,\n type ListResourceTemplatesResult,\n type Notification,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\n\nexport class MCPClientConnection {\n client: Client;\n connectionState:\n | \"authenticating\"\n | \"connecting\"\n | \"ready\"\n | \"discovering\"\n | \"failed\" = \"connecting\";\n instructions?: string;\n tools: Tool[] = [];\n prompts: Prompt[] = [];\n resources: Resource[] = [];\n resourceTemplates: ResourceTemplate[] = [];\n serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n public url: URL,\n info: ConstructorParameters<typeof Client>[0],\n public options: {\n transport: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\n client: ConstructorParameters<typeof Client>[1];\n } = { transport: {}, client: {} }\n ) {\n this.client = new Client(info, options.client);\n }\n\n /**\n * Initialize a client connection\n *\n * @param code Optional OAuth code to initialize the connection with if auth hasn't been initialized\n * @returns\n */\n async init(code?: string) {\n try {\n const transport = new SSEEdgeClientTransport(\n this.url,\n this.options.transport\n );\n\n if (code) {\n await transport.finishAuth(code);\n }\n\n await this.client.connect(transport);\n // biome-ignore lint/suspicious/noExplicitAny: allow for the error check here\n } catch (e: any) {\n if (e.toString().includes(\"Unauthorized\")) {\n // unauthorized, we should wait for the user to authenticate\n this.connectionState = \"authenticating\";\n return;\n }\n this.connectionState = \"failed\";\n throw e;\n }\n\n this.connectionState = \"discovering\";\n\n this.serverCapabilities = await this.client.getServerCapabilities();\n if (!this.serverCapabilities) {\n throw new Error(\"The MCP Server failed to return server capabilities\");\n }\n\n const [instructions, tools, resources, prompts, resourceTemplates] =\n await Promise.all([\n this.client.getInstructions(),\n this.registerTools(),\n this.registerResources(),\n this.registerPrompts(),\n this.registerResourceTemplates(),\n ]);\n\n this.instructions = instructions;\n this.tools = tools;\n this.resources = resources;\n this.prompts = prompts;\n this.resourceTemplates = resourceTemplates;\n\n this.connectionState = \"ready\";\n }\n\n /**\n * Notification handler registration\n */\n async registerTools(): Promise<Tool[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.tools) {\n return [];\n }\n\n if (this.serverCapabilities.tools.listChanged) {\n this.client.setNotificationHandler(\n ToolListChangedNotificationSchema,\n async (_notification) => {\n this.tools = await this.fetchTools();\n }\n );\n }\n\n return this.fetchTools();\n }\n\n async registerResources(): Promise<Resource[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n if (this.serverCapabilities.resources.listChanged) {\n this.client.setNotificationHandler(\n ResourceListChangedNotificationSchema,\n async (_notification) => {\n this.resources = await this.fetchResources();\n }\n );\n }\n\n return this.fetchResources();\n }\n\n async registerPrompts(): Promise<Prompt[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.prompts) {\n return [];\n }\n\n if (this.serverCapabilities.prompts.listChanged) {\n this.client.setNotificationHandler(\n PromptListChangedNotificationSchema,\n async (_notification) => {\n this.prompts = await this.fetchPrompts();\n }\n );\n }\n\n return this.fetchPrompts();\n }\n\n async registerResourceTemplates(): Promise<ResourceTemplate[]> {\n if (!this.serverCapabilities || !this.serverCapabilities.resources) {\n return [];\n }\n\n return this.fetchResourceTemplates();\n }\n\n async fetchTools() {\n let toolsAgg: Tool[] = [];\n let toolsResult: ListToolsResult = { tools: [] };\n do {\n toolsResult = await this.client\n .listTools({\n cursor: toolsResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ tools: [] }, \"tools/list\"));\n toolsAgg = toolsAgg.concat(toolsResult.tools);\n } while (toolsResult.nextCursor);\n return toolsAgg;\n }\n\n async fetchResources() {\n let resourcesAgg: Resource[] = [];\n let resourcesResult: ListResourcesResult = { resources: [] };\n do {\n resourcesResult = await this.client\n .listResources({\n cursor: resourcesResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ resources: [] }, \"resources/list\"));\n resourcesAgg = resourcesAgg.concat(resourcesResult.resources);\n } while (resourcesResult.nextCursor);\n return resourcesAgg;\n }\n\n async fetchPrompts() {\n let promptsAgg: Prompt[] = [];\n let promptsResult: ListPromptsResult = { prompts: [] };\n do {\n promptsResult = await this.client\n .listPrompts({\n cursor: promptsResult.nextCursor,\n })\n .catch(capabilityErrorHandler({ prompts: [] }, \"prompts/list\"));\n promptsAgg = promptsAgg.concat(promptsResult.prompts);\n } while (promptsResult.nextCursor);\n return promptsAgg;\n }\n\n async fetchResourceTemplates() {\n let templatesAgg: ResourceTemplate[] = [];\n let templatesResult: ListResourceTemplatesResult = {\n resourceTemplates: [],\n };\n do {\n templatesResult = await this.client\n .listResourceTemplates({\n cursor: templatesResult.nextCursor,\n })\n .catch(\n capabilityErrorHandler(\n { resourceTemplates: [] },\n \"resources/templates/list\"\n )\n );\n templatesAgg = templatesAgg.concat(templatesResult.resourceTemplates);\n } while (templatesResult.nextCursor);\n return templatesAgg;\n }\n}\n\nfunction capabilityErrorHandler<T>(empty: T, method: string) {\n return (e: { code: number }) => {\n // server is badly behaved and returning invalid capabilities. This commonly occurs for resource templates\n if (e.code === -32601) {\n console.error(\n `The server advertised support for the capability ${method.split(\"/\")[0]}, but returned \"Method not found\" for '${method}'.`\n );\n return empty;\n }\n throw e;\n };\n}\n","import { MCPClientConnection } from \"./client-connection\";\n\nimport type {\n CallToolRequest,\n CallToolResultSchema,\n CompatibilityCallToolResultSchema,\n ReadResourceRequest,\n GetPromptRequest,\n Tool,\n Resource,\n Prompt,\n ResourceTemplate,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SSEClientTransportOptions } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type { AgentsOAuthProvider } from \"./do-oauth-client-provider\";\nimport { jsonSchema, type ToolSet } from \"ai\";\nimport { nanoid } from \"nanoid\";\n\n/**\n * Utility class that aggregates multiple MCP clients into one\n */\nexport class MCPClientManager {\n public mcpConnections: Record<string, MCPClientConnection> = {};\n private _callbackUrls: string[] = [];\n\n /**\n * @param _name Name of the MCP client\n * @param _version Version of the MCP Client\n * @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider\n */\n constructor(\n private _name: string,\n private _version: string\n ) {}\n\n /**\n * Connect to and register an MCP server\n *\n * @param transportConfig Transport config\n * @param clientConfig Client config\n * @param capabilities Client capabilities (i.e. if the client supports roots/sampling)\n */\n async connect(\n url: string,\n options: {\n // Allows you to reconnect to a server (in the case of a auth reconnect)\n reconnect?: {\n id: string;\n oauthClientId?: string;\n oauthCode?: string;\n };\n // we're overriding authProvider here because we want to be able to access the auth URL\n transport?: SSEClientTransportOptions & {\n authProvider?: AgentsOAuthProvider;\n };\n client?: ConstructorParameters<typeof Client>[1];\n } = {}\n ): Promise<{\n id: string;\n authUrl?: string;\n clientId?: string;\n }> {\n const id = options.reconnect?.id ?? nanoid(8);\n\n if (!options.transport?.authProvider) {\n console.warn(\n \"No authProvider provided in the transport options. This client will only support unauthenticated remote MCP Servers\"\n );\n } else {\n // reconnect with auth\n options.transport.authProvider.serverId = id;\n if (options.reconnect?.oauthClientId) {\n options.transport.authProvider.clientId =\n options.reconnect?.oauthClientId;\n }\n }\n\n this.mcpConnections[id] = new MCPClientConnection(\n new URL(url),\n {\n name: this._name,\n version: this._version,\n },\n {\n transport: options.transport ?? {},\n client: options.client ?? {},\n }\n );\n\n await this.mcpConnections[id].init(options.reconnect?.oauthCode);\n\n const authUrl = options.transport?.authProvider?.authUrl;\n if (authUrl && options.transport?.authProvider?.redirectUrl) {\n this._callbackUrls.push(\n options.transport.authProvider.redirectUrl.toString()\n );\n return {\n id,\n authUrl,\n clientId: options.transport?.authProvider?.clientId,\n };\n }\n\n return {\n id,\n };\n }\n\n isCallbackRequest(req: Request): boolean {\n return (\n req.method === \"GET\" &&\n !!this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n })\n );\n }\n\n async handleCallbackRequest(req: Request) {\n const url = new URL(req.url);\n const urlMatch = this._callbackUrls.find((url) => {\n return req.url.startsWith(url);\n });\n if (!urlMatch) {\n throw new Error(\n `No callback URI match found for the request url: ${req.url}. Was the request matched with \\`isCallbackRequest()\\`?`\n );\n }\n const code = url.searchParams.get(\"code\");\n const clientId = url.searchParams.get(\"state\");\n const urlParams = urlMatch.split(\"/\");\n const serverId = urlParams[urlParams.length - 1];\n if (!code) {\n throw new Error(\"Unauthorized: no code provided\");\n }\n if (!clientId) {\n throw new Error(\"Unauthorized: no state provided\");\n }\n\n if (this.mcpConnections[serverId] === undefined) {\n throw new Error(`Could not find serverId: ${serverId}`);\n }\n\n if (this.mcpConnections[serverId].connectionState !== \"authenticating\") {\n throw new Error(\n \"Failed to authenticate: the client isn't in the `authenticating` state\"\n );\n }\n\n const conn = this.mcpConnections[serverId];\n if (!conn.options.transport.authProvider) {\n throw new Error(\n \"Trying to finalize authentication for a server connection without an authProvider\"\n );\n }\n\n conn.options.transport.authProvider.clientId = clientId;\n conn.options.transport.authProvider.serverId = serverId;\n\n // reconnect to server with authorization\n const serverUrl = conn.url.toString();\n await this.connect(serverUrl, {\n reconnect: {\n id: serverId,\n oauthClientId: clientId,\n oauthCode: code,\n },\n ...conn.options,\n });\n\n if (this.mcpConnections[serverId].connectionState === \"authenticating\") {\n throw new Error(\"Failed to authenticate: client failed to initialize\");\n }\n\n return { serverId };\n }\n\n /**\n * @returns namespaced list of tools\n */\n listTools(): NamespacedData[\"tools\"] {\n return getNamespacedData(this.mcpConnections, \"tools\");\n }\n\n /**\n * @returns a set of tools that you can use with the AI SDK\n */\n unstable_getAITools(): ToolSet {\n return Object.fromEntries(\n getNamespacedData(this.mcpConnections, \"tools\").map((tool) => {\n return [\n `${tool.serverId}_${tool.name}`,\n {\n parameters: jsonSchema(tool.inputSchema),\n description: tool.description,\n execute: async (args) => {\n const result = await this.callTool({\n name: tool.name,\n arguments: args,\n serverId: tool.serverId,\n });\n if (result.isError) {\n // @ts-expect-error TODO we should fix this\n throw new Error(result.content[0].text);\n }\n return result;\n },\n },\n ];\n })\n );\n }\n\n /**\n * Closes all connections to MCP servers\n */\n async closeAllConnections() {\n return Promise.all(\n Object.values(this.mcpConnections).map(async (connection) => {\n await connection.client.close();\n })\n );\n }\n\n /**\n * Closes a connection to an MCP server\n * @param id The id of the connection to close\n */\n async closeConnection(id: string) {\n if (!this.mcpConnections[id]) {\n throw new Error(`Connection with id \"${id}\" does not exist.`);\n }\n await this.mcpConnections[id].client.close();\n }\n\n /**\n * @returns namespaced list of prompts\n */\n listPrompts(): NamespacedData[\"prompts\"] {\n return getNamespacedData(this.mcpConnections, \"prompts\");\n }\n\n /**\n * @returns namespaced list of tools\n */\n listResources(): NamespacedData[\"resources\"] {\n return getNamespacedData(this.mcpConnections, \"resources\");\n }\n\n /**\n * @returns namespaced list of resource templates\n */\n listResourceTemplates(): NamespacedData[\"resourceTemplates\"] {\n return getNamespacedData(this.mcpConnections, \"resourceTemplates\");\n }\n\n /**\n * Namespaced version of callTool\n */\n callTool(\n params: CallToolRequest[\"params\"] & { serverId: string },\n resultSchema?:\n | typeof CallToolResultSchema\n | typeof CompatibilityCallToolResultSchema,\n options?: RequestOptions\n ) {\n const unqualifiedName = params.name.replace(`${params.serverId}.`, \"\");\n return this.mcpConnections[params.serverId].client.callTool(\n {\n ...params,\n name: unqualifiedName,\n },\n resultSchema,\n options\n );\n }\n\n /**\n * Namespaced version of readResource\n */\n readResource(\n params: ReadResourceRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.readResource(\n params,\n options\n );\n }\n\n /**\n * Namespaced version of getPrompt\n */\n getPrompt(\n params: GetPromptRequest[\"params\"] & { serverId: string },\n options: RequestOptions\n ) {\n return this.mcpConnections[params.serverId].client.getPrompt(\n params,\n options\n );\n }\n}\n\ntype NamespacedData = {\n tools: (Tool & { serverId: string })[];\n prompts: (Prompt & { serverId: string })[];\n resources: (Resource & { serverId: string })[];\n resourceTemplates: (ResourceTemplate & { serverId: string })[];\n};\n\nexport function getNamespacedData<T extends keyof NamespacedData>(\n mcpClients: Record<string, MCPClientConnection>,\n type: T\n): NamespacedData[T] {\n const sets = Object.entries(mcpClients).map(([name, conn]) => {\n return { name, data: conn[type] };\n });\n\n const namespacedData = sets.flatMap(({ name: serverId, data }) => {\n return data.map((item) => {\n return {\n ...item,\n // we add a serverId so we can easily pull it out and send the tool call to the right server\n serverId,\n };\n });\n });\n\n return namespacedData as NamespacedData[T]; // Type assertion needed due to TS limitations with conditional return types\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAEK;AAGA,IAAM,yBAAN,cAAqC,mBAAmB;AAAA;AAAA;AAAA;AAAA,EAK7D,YAAY,KAAU,SAAoC;AACxD,UAAM,gBAA8B,OAClC,UACA,YAAyB,CAAC,MACvB;AAEH,YAAM,UAAU,MAAM,KAAK,YAAY;AACvC,YAAM,gBAAgB;AAAA,QACpB,GAAG;AAAA,QACH,SAAS;AAAA,UACP,GAAG,QAAQ,aAAa;AAAA,UACxB,GAAG,WAAW;AAAA,UACd,GAAG;AAAA,QACL;AAAA,MACF;AAIA,aAAO,cAAc;AAGrB,aACG,QAAQ,iBAAiB;AAAA,QACxB;AAAA;AAAA,QAEA;AAAA,MACF,KAA2B,MAAM,UAAU,aAAa;AAAA,IAE5D;AAEA,UAAM,KAAK;AAAA,MACT,GAAG;AAAA,MACH,iBAAiB;AAAA,QACf,GAAG,QAAQ;AAAA,QACX,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AACD,SAAK,eAAe,QAAQ;AAAA,EAC9B;AAAA,EAEA,MAAM,cAAc;AAClB,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A;AAAA;AAAA;AAAA,EAKA,UACE,QACA,SACA;AACA,WAAO,KAAK,eAAe,OAAO,QAAQ,EAAE,OAAO;AAAA,MACjD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,kBACd,YACA,MACmB;AACnB,QAAM,OAAO,OAAO,QAAQ,UAAU,EAAE,IAAI,CAAC,CAAC,MAAM,IAAI,MAAM;AAC5D,WAAO,EAAE,MAAM,MAAM,KAAK,IAAI,EAAE;AAAA,EAClC,CAAC;AAED,QAAM,iBAAiB,KAAK,QAAQ,CAAC,EAAE,MAAM,UAAU,KAAK,MAAM;AAChE,WAAO,KAAK,IAAI,CAAC,SAAS;AACxB,aAAO;AAAA,QACL,GAAG;AAAA;AAAA,QAEH;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AAED,SAAO;AACT;","names":["url"]}
|
package/dist/client.d.ts
CHANGED
|
@@ -38,17 +38,24 @@ type AgentClientFetchOptions = Omit<PartyFetchOptions, "party" | "room"> & {
|
|
|
38
38
|
/** Name of the specific Agent instance */
|
|
39
39
|
name?: string;
|
|
40
40
|
};
|
|
41
|
+
/**
|
|
42
|
+
* Convert a camelCase string to a kebab-case string
|
|
43
|
+
* @param str The string to convert
|
|
44
|
+
* @returns The kebab-case string
|
|
45
|
+
*/
|
|
46
|
+
declare function camelCaseToKebabCase(str: string): string;
|
|
41
47
|
/**
|
|
42
48
|
* WebSocket client for connecting to an Agent
|
|
43
49
|
*/
|
|
44
50
|
declare class AgentClient<State = unknown> extends PartySocket {
|
|
45
|
-
#private;
|
|
46
51
|
/**
|
|
47
52
|
* @deprecated Use agentFetch instead
|
|
48
53
|
*/
|
|
49
54
|
static fetch(_opts: PartyFetchOptions): Promise<Response>;
|
|
50
55
|
agent: string;
|
|
51
56
|
name: string;
|
|
57
|
+
private options;
|
|
58
|
+
private _pendingCalls;
|
|
52
59
|
constructor(options: AgentClientOptions<State>);
|
|
53
60
|
setState(state: State): void;
|
|
54
61
|
/**
|
|
@@ -81,4 +88,5 @@ export {
|
|
|
81
88
|
type AgentClientOptions,
|
|
82
89
|
type StreamOptions,
|
|
83
90
|
agentFetch,
|
|
91
|
+
camelCaseToKebabCase,
|
|
84
92
|
};
|
package/dist/client.js
CHANGED
|
@@ -1,131 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
} from "./chunk-
|
|
6
|
-
|
|
7
|
-
// src/client.ts
|
|
8
|
-
import {
|
|
9
|
-
PartySocket
|
|
10
|
-
} from "partysocket";
|
|
11
|
-
function camelCaseToKebabCase(str) {
|
|
12
|
-
if (str === str.toUpperCase() && str !== str.toLowerCase()) {
|
|
13
|
-
return str.toLowerCase().replace(/_/g, "-");
|
|
14
|
-
}
|
|
15
|
-
let kebabified = str.replace(
|
|
16
|
-
/[A-Z]/g,
|
|
17
|
-
(letter) => `-${letter.toLowerCase()}`
|
|
18
|
-
);
|
|
19
|
-
kebabified = kebabified.startsWith("-") ? kebabified.slice(1) : kebabified;
|
|
20
|
-
return kebabified.replace(/_/g, "-").replace(/-$/, "");
|
|
21
|
-
}
|
|
22
|
-
var _options, _pendingCalls;
|
|
23
|
-
var AgentClient = class extends PartySocket {
|
|
24
|
-
constructor(options) {
|
|
25
|
-
const agentNamespace = camelCaseToKebabCase(options.agent);
|
|
26
|
-
super({
|
|
27
|
-
prefix: "agents",
|
|
28
|
-
party: agentNamespace,
|
|
29
|
-
room: options.name || "default",
|
|
30
|
-
...options
|
|
31
|
-
});
|
|
32
|
-
__privateAdd(this, _options);
|
|
33
|
-
__privateAdd(this, _pendingCalls, /* @__PURE__ */ new Map());
|
|
34
|
-
this.agent = agentNamespace;
|
|
35
|
-
this.name = options.name || "default";
|
|
36
|
-
__privateSet(this, _options, options);
|
|
37
|
-
this.addEventListener("message", (event) => {
|
|
38
|
-
if (typeof event.data === "string") {
|
|
39
|
-
let parsedMessage;
|
|
40
|
-
try {
|
|
41
|
-
parsedMessage = JSON.parse(event.data);
|
|
42
|
-
} catch (error) {
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
if (parsedMessage.type === "cf_agent_state") {
|
|
46
|
-
__privateGet(this, _options).onStateUpdate?.(parsedMessage.state, "server");
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
if (parsedMessage.type === "rpc") {
|
|
50
|
-
const response = parsedMessage;
|
|
51
|
-
const pending = __privateGet(this, _pendingCalls).get(response.id);
|
|
52
|
-
if (!pending) return;
|
|
53
|
-
if (!response.success) {
|
|
54
|
-
pending.reject(new Error(response.error));
|
|
55
|
-
__privateGet(this, _pendingCalls).delete(response.id);
|
|
56
|
-
pending.stream?.onError?.(response.error);
|
|
57
|
-
return;
|
|
58
|
-
}
|
|
59
|
-
if ("done" in response) {
|
|
60
|
-
if (response.done) {
|
|
61
|
-
pending.resolve(response.result);
|
|
62
|
-
__privateGet(this, _pendingCalls).delete(response.id);
|
|
63
|
-
pending.stream?.onDone?.(response.result);
|
|
64
|
-
} else {
|
|
65
|
-
pending.stream?.onChunk?.(response.result);
|
|
66
|
-
}
|
|
67
|
-
} else {
|
|
68
|
-
pending.resolve(response.result);
|
|
69
|
-
__privateGet(this, _pendingCalls).delete(response.id);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
/**
|
|
76
|
-
* @deprecated Use agentFetch instead
|
|
77
|
-
*/
|
|
78
|
-
static fetch(_opts) {
|
|
79
|
-
throw new Error(
|
|
80
|
-
"AgentClient.fetch is not implemented, use agentFetch instead"
|
|
81
|
-
);
|
|
82
|
-
}
|
|
83
|
-
setState(state) {
|
|
84
|
-
this.send(JSON.stringify({ type: "cf_agent_state", state }));
|
|
85
|
-
__privateGet(this, _options).onStateUpdate?.(state, "client");
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Call a method on the Agent
|
|
89
|
-
* @param method Name of the method to call
|
|
90
|
-
* @param args Arguments to pass to the method
|
|
91
|
-
* @param streamOptions Options for handling streaming responses
|
|
92
|
-
* @returns Promise that resolves with the method's return value
|
|
93
|
-
*/
|
|
94
|
-
async call(method, args = [], streamOptions) {
|
|
95
|
-
return new Promise((resolve, reject) => {
|
|
96
|
-
const id = Math.random().toString(36).slice(2);
|
|
97
|
-
__privateGet(this, _pendingCalls).set(id, {
|
|
98
|
-
resolve: (value) => resolve(value),
|
|
99
|
-
reject,
|
|
100
|
-
stream: streamOptions,
|
|
101
|
-
type: null
|
|
102
|
-
});
|
|
103
|
-
const request = {
|
|
104
|
-
type: "rpc",
|
|
105
|
-
id,
|
|
106
|
-
method,
|
|
107
|
-
args
|
|
108
|
-
};
|
|
109
|
-
this.send(JSON.stringify(request));
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
};
|
|
113
|
-
_options = new WeakMap();
|
|
114
|
-
_pendingCalls = new WeakMap();
|
|
115
|
-
function agentFetch(opts, init) {
|
|
116
|
-
const agentNamespace = camelCaseToKebabCase(opts.agent);
|
|
117
|
-
return PartySocket.fetch(
|
|
118
|
-
{
|
|
119
|
-
prefix: "agents",
|
|
120
|
-
party: agentNamespace,
|
|
121
|
-
room: opts.name || "default",
|
|
122
|
-
...opts
|
|
123
|
-
},
|
|
124
|
-
init
|
|
125
|
-
);
|
|
126
|
-
}
|
|
2
|
+
AgentClient,
|
|
3
|
+
agentFetch,
|
|
4
|
+
camelCaseToKebabCase
|
|
5
|
+
} from "./chunk-QSGN3REV.js";
|
|
6
|
+
import "./chunk-NOUFNU2O.js";
|
|
127
7
|
export {
|
|
128
8
|
AgentClient,
|
|
129
|
-
agentFetch
|
|
9
|
+
agentFetch,
|
|
10
|
+
camelCaseToKebabCase
|
|
130
11
|
};
|
|
131
12
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Server, Connection, PartyServerOptions } from "partyserver";
|
|
2
2
|
export { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
3
3
|
import { MCPClientManager } from "./mcp/client.js";
|
|
4
|
+
import { Tool, Prompt, Resource } from "@modelcontextprotocol/sdk/types.js";
|
|
5
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
4
6
|
import "zod";
|
|
5
|
-
import "@modelcontextprotocol/sdk/types.js";
|
|
6
|
-
import "@modelcontextprotocol/sdk/client/index.js";
|
|
7
7
|
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
8
8
|
import "./mcp/do-oauth-client-provider.js";
|
|
9
9
|
import "@modelcontextprotocol/sdk/client/auth.js";
|
|
@@ -103,6 +103,27 @@ type Schedule<T = string> = {
|
|
|
103
103
|
cron: string;
|
|
104
104
|
}
|
|
105
105
|
);
|
|
106
|
+
/**
|
|
107
|
+
* MCP Server state update message from server -> Client
|
|
108
|
+
*/
|
|
109
|
+
type MCPServerMessage = {
|
|
110
|
+
type: "cf_agent_mcp_servers";
|
|
111
|
+
mcp: MCPServersState;
|
|
112
|
+
};
|
|
113
|
+
type MCPServersState = {
|
|
114
|
+
servers: {
|
|
115
|
+
[id: string]: MCPServer;
|
|
116
|
+
};
|
|
117
|
+
tools: Tool[];
|
|
118
|
+
prompts: Prompt[];
|
|
119
|
+
resources: Resource[];
|
|
120
|
+
};
|
|
121
|
+
type MCPServer = {
|
|
122
|
+
name: string;
|
|
123
|
+
server_url: string;
|
|
124
|
+
auth_url: string | null;
|
|
125
|
+
state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
126
|
+
};
|
|
106
127
|
declare function getCurrentAgent<
|
|
107
128
|
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
108
129
|
>(): {
|
|
@@ -117,6 +138,8 @@ declare function getCurrentAgent<
|
|
|
117
138
|
*/
|
|
118
139
|
declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
119
140
|
#private;
|
|
141
|
+
private _state;
|
|
142
|
+
private _ParentClass;
|
|
120
143
|
mcp: MCPClientManager;
|
|
121
144
|
/**
|
|
122
145
|
* Initial state for the Agent
|
|
@@ -146,6 +169,7 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
146
169
|
...values: (string | number | boolean | null)[]
|
|
147
170
|
): T[];
|
|
148
171
|
constructor(ctx: AgentContext, env: Env);
|
|
172
|
+
private _setStateInternal;
|
|
149
173
|
/**
|
|
150
174
|
* Update the Agent's state
|
|
151
175
|
* @param state New state to set
|
|
@@ -162,6 +186,7 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
162
186
|
* @param email Email message to process
|
|
163
187
|
*/
|
|
164
188
|
onEmail(email: ForwardableEmailMessage): Promise<void>;
|
|
189
|
+
private _tryCatch;
|
|
165
190
|
onError(connection: Connection, error: unknown): void | Promise<void>;
|
|
166
191
|
onError(error: unknown): void | Promise<void>;
|
|
167
192
|
/**
|
|
@@ -208,6 +233,7 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
208
233
|
* @returns true if the task was cancelled, false otherwise
|
|
209
234
|
*/
|
|
210
235
|
cancelSchedule(id: string): Promise<boolean>;
|
|
236
|
+
private _scheduleNextAlarm;
|
|
211
237
|
/**
|
|
212
238
|
* Method called when an alarm fires.
|
|
213
239
|
* Executes any scheduled tasks that are due.
|
|
@@ -221,6 +247,32 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
221
247
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
222
248
|
*/
|
|
223
249
|
destroy(): Promise<void>;
|
|
250
|
+
private _isCallable;
|
|
251
|
+
/**
|
|
252
|
+
* Connect to a new MCP Server
|
|
253
|
+
*
|
|
254
|
+
* @param url MCP Server SSE URL
|
|
255
|
+
* @param callbackHost Base host for the agent, used for the redirect URI.
|
|
256
|
+
* @param agentsPrefix agents routing prefix if not using `agents`
|
|
257
|
+
* @param options MCP client and transport (header) options
|
|
258
|
+
* @returns authUrl
|
|
259
|
+
*/
|
|
260
|
+
addMcpServer(
|
|
261
|
+
serverName: string,
|
|
262
|
+
url: string,
|
|
263
|
+
callbackHost: string,
|
|
264
|
+
agentsPrefix?: string,
|
|
265
|
+
options?: {
|
|
266
|
+
client?: ConstructorParameters<typeof Client>[1];
|
|
267
|
+
transport?: {
|
|
268
|
+
headers: HeadersInit;
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
): Promise<{
|
|
272
|
+
id: string;
|
|
273
|
+
authUrl: string | undefined;
|
|
274
|
+
}>;
|
|
275
|
+
removeMcpServer(id: string): Promise<void>;
|
|
224
276
|
}
|
|
225
277
|
/**
|
|
226
278
|
* Namespace for creating Agent instances
|
|
@@ -285,7 +337,9 @@ declare function getAgentByName<Env, T extends Agent<Env>>(
|
|
|
285
337
|
* A wrapper for streaming responses in callable methods
|
|
286
338
|
*/
|
|
287
339
|
declare class StreamingResponse {
|
|
288
|
-
|
|
340
|
+
private _connection;
|
|
341
|
+
private _id;
|
|
342
|
+
private _closed;
|
|
289
343
|
constructor(connection: Connection, id: string);
|
|
290
344
|
/**
|
|
291
345
|
* Send a chunk of data to the client
|
|
@@ -305,6 +359,9 @@ export {
|
|
|
305
359
|
type AgentNamespace,
|
|
306
360
|
type AgentOptions,
|
|
307
361
|
type CallableMetadata,
|
|
362
|
+
type MCPServer,
|
|
363
|
+
type MCPServerMessage,
|
|
364
|
+
type MCPServersState,
|
|
308
365
|
type RPCRequest,
|
|
309
366
|
type RPCResponse,
|
|
310
367
|
type Schedule,
|
package/dist/index.js
CHANGED
|
@@ -6,9 +6,11 @@ import {
|
|
|
6
6
|
routeAgentEmail,
|
|
7
7
|
routeAgentRequest,
|
|
8
8
|
unstable_callable
|
|
9
|
-
} from "./chunk-
|
|
10
|
-
import "./chunk-
|
|
11
|
-
import "./chunk-
|
|
9
|
+
} from "./chunk-NPGUKHFR.js";
|
|
10
|
+
import "./chunk-BZXOAZUX.js";
|
|
11
|
+
import "./chunk-QSGN3REV.js";
|
|
12
|
+
import "./chunk-Y67CHZBI.js";
|
|
13
|
+
import "./chunk-NOUFNU2O.js";
|
|
12
14
|
export {
|
|
13
15
|
Agent,
|
|
14
16
|
StreamingResponse,
|