agents 0.0.0-fd36bbc → 0.0.0-fd59ae2

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.
Files changed (48) hide show
  1. package/README.md +130 -28
  2. package/dist/ai-chat-agent.d.ts +52 -3
  3. package/dist/ai-chat-agent.js +170 -82
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-react.d.ts +26 -8
  6. package/dist/ai-react.js +62 -48
  7. package/dist/ai-react.js.map +1 -1
  8. package/dist/ai-types.d.ts +5 -0
  9. package/dist/chunk-DQJFYHG3.js +1290 -0
  10. package/dist/chunk-DQJFYHG3.js.map +1 -0
  11. package/dist/chunk-EM3J4KV7.js +598 -0
  12. package/dist/chunk-EM3J4KV7.js.map +1 -0
  13. package/dist/chunk-KUH345EY.js +116 -0
  14. package/dist/chunk-KUH345EY.js.map +1 -0
  15. package/dist/chunk-PVQZBKN7.js +106 -0
  16. package/dist/chunk-PVQZBKN7.js.map +1 -0
  17. package/dist/client-DgyzBU_8.d.ts +4601 -0
  18. package/dist/client.d.ts +16 -2
  19. package/dist/client.js +6 -133
  20. package/dist/client.js.map +1 -1
  21. package/dist/index.d.ts +265 -20
  22. package/dist/index.js +12 -4
  23. package/dist/mcp/client.d.ts +11 -0
  24. package/dist/mcp/client.js +9 -0
  25. package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
  26. package/dist/mcp/do-oauth-client-provider.js +7 -0
  27. package/dist/mcp/do-oauth-client-provider.js.map +1 -0
  28. package/dist/mcp/index.d.ts +112 -0
  29. package/dist/mcp/index.js +955 -0
  30. package/dist/mcp/index.js.map +1 -0
  31. package/dist/observability/index.d.ts +46 -0
  32. package/dist/observability/index.js +10 -0
  33. package/dist/observability/index.js.map +1 -0
  34. package/dist/react.d.ts +88 -5
  35. package/dist/react.js +50 -31
  36. package/dist/react.js.map +1 -1
  37. package/dist/schedule.d.ts +6 -6
  38. package/dist/schedule.js +4 -6
  39. package/dist/schedule.js.map +1 -1
  40. package/dist/serializable.d.ts +32 -0
  41. package/dist/serializable.js +1 -0
  42. package/dist/serializable.js.map +1 -0
  43. package/package.json +87 -43
  44. package/src/index.ts +1217 -185
  45. package/dist/chunk-HMLY7DHA.js +0 -16
  46. package/dist/chunk-X6BBKLSC.js +0 -568
  47. package/dist/chunk-X6BBKLSC.js.map +0 -1
  48. /package/dist/{chunk-HMLY7DHA.js.map → mcp/client.js.map} +0 -0
package/README.md CHANGED
@@ -66,13 +66,13 @@ export class AIAgent extends Agent {
66
66
  async onRequest(request) {
67
67
  // Connect with AI capabilities
68
68
  const ai = new OpenAI({
69
- apiKey: this.env.OPENAI_API_KEY,
69
+ apiKey: this.env.OPENAI_API_KEY
70
70
  });
71
71
 
72
72
  // Process and understand
73
73
  const response = await ai.chat.completions.create({
74
74
  model: "gpt-4",
75
- messages: [{ role: "user", content: await request.text() }],
75
+ messages: [{ role: "user", content: await request.text() }]
76
76
  });
77
77
 
78
78
  return new Response(response.choices[0].message.content);
@@ -96,17 +96,17 @@ Define your agent's domain:
96
96
  "bindings": [
97
97
  {
98
98
  "name": "AIAgent",
99
- "class_name": "AIAgent",
100
- },
101
- ],
99
+ "class_name": "AIAgent"
100
+ }
101
+ ]
102
102
  },
103
103
  "migrations": [
104
104
  {
105
105
  "tag": "v1",
106
106
  // Mandatory for the Agent to store state
107
- "new_sqlite_classes": ["AIAgent"],
108
- },
109
- ],
107
+ "new_sqlite_classes": ["AIAgent"]
108
+ }
109
+ ]
110
110
  }
111
111
  ```
112
112
 
@@ -123,7 +123,7 @@ const agent = env.AIAgent.get(id);
123
123
  await agent.processTask({
124
124
  type: "analysis",
125
125
  context: "incoming_data",
126
- parameters: initialConfig,
126
+ parameters: initialConfig
127
127
  });
128
128
 
129
129
  // Or reconnect with an existing one
@@ -143,7 +143,7 @@ export class APIAgent extends Agent {
143
143
 
144
144
  return Response.json({
145
145
  insight: await this.process(data),
146
- moment: Date.now(),
146
+ moment: Date.now()
147
147
  });
148
148
  }
149
149
  }
@@ -175,7 +175,7 @@ import { AgentClient } from "agents/client";
175
175
 
176
176
  const connection = new AgentClient({
177
177
  agent: "dialogue-agent",
178
- name: "insight-seeker",
178
+ name: "insight-seeker"
179
179
  });
180
180
 
181
181
  connection.addEventListener("message", (event) => {
@@ -185,7 +185,7 @@ connection.addEventListener("message", (event) => {
185
185
  connection.send(
186
186
  JSON.stringify({
187
187
  type: "inquiry",
188
- content: "What patterns do you see?",
188
+ content: "What patterns do you see?"
189
189
  })
190
190
  );
191
191
  ```
@@ -205,14 +205,14 @@ function AgentInterface() {
205
205
  console.log("Understanding received:", message.data);
206
206
  },
207
207
  onOpen: () => console.log("Connection established"),
208
- onClose: () => console.log("Connection closed"),
208
+ onClose: () => console.log("Connection closed")
209
209
  });
210
210
 
211
211
  const inquire = () => {
212
212
  connection.send(
213
213
  JSON.stringify({
214
214
  type: "inquiry",
215
- content: "What insights have you gathered?",
215
+ content: "What insights have you gathered?"
216
216
  })
217
217
  );
218
218
  };
@@ -235,14 +235,14 @@ export class ThinkingAgent extends Agent {
235
235
  this.setState({
236
236
  ...this.state,
237
237
  insights: [...(this.state.insights || []), newInsight],
238
- understanding: this.state.understanding + 1,
238
+ understanding: this.state.understanding + 1
239
239
  });
240
240
  }
241
241
 
242
242
  onStateUpdate(state, source) {
243
243
  console.log("Understanding deepened:", {
244
244
  newState: state,
245
- origin: source,
245
+ origin: source
246
246
  });
247
247
  }
248
248
  }
@@ -259,7 +259,7 @@ function StateInterface() {
259
259
 
260
260
  const agent = useAgent({
261
261
  agent: "thinking-agent",
262
- onStateUpdate: (newState) => setState(newState),
262
+ onStateUpdate: (newState) => setState(newState)
263
263
  });
264
264
 
265
265
  const increment = () => {
@@ -289,7 +289,7 @@ export class TimeAwareAgent extends Agent {
289
289
 
290
290
  // Daily synthesis
291
291
  this.schedule("0 0 * * *", "dailySynthesis", {
292
- depth: "comprehensive",
292
+ depth: "comprehensive"
293
293
  });
294
294
 
295
295
  // Milestone review
@@ -316,24 +316,20 @@ Create meaningful conversations with intelligence:
316
316
 
317
317
  ```ts
318
318
  import { AIChatAgent } from "agents/ai-chat-agent";
319
- import { createOpenAI } from "@ai-sdk/openai";
319
+ import { openai } from "@ai-sdk/openai";
320
320
 
321
321
  export class DialogueAgent extends AIChatAgent {
322
322
  async onChatMessage(onFinish) {
323
323
  return createDataStreamResponse({
324
324
  execute: async (dataStream) => {
325
- const ai = createOpenAI({
326
- apiKey: this.env.OPENAI_API_KEY,
327
- });
328
-
329
325
  const stream = streamText({
330
- model: ai("gpt-4o"),
326
+ model: openai("gpt-4o"),
331
327
  messages: this.messages,
332
- onFinish, // call onFinish so that messages get saved
328
+ onFinish // call onFinish so that messages get saved
333
329
  });
334
330
 
335
331
  stream.mergeIntoDataStream(dataStream);
336
- },
332
+ }
337
333
  });
338
334
  }
339
335
  }
@@ -350,14 +346,14 @@ import { useAgentChat } from "agents/ai-react";
350
346
  function ChatInterface() {
351
347
  // Connect to the agent
352
348
  const agent = useAgent({
353
- agent: "dialogue-agent",
349
+ agent: "dialogue-agent"
354
350
  });
355
351
 
356
352
  // Set up the chat interaction
357
353
  const { messages, input, handleInputChange, handleSubmit, clearHistory } =
358
354
  useAgentChat({
359
355
  agent,
360
- maxSteps: 5,
356
+ maxSteps: 5
361
357
  });
362
358
 
363
359
  return (
@@ -397,6 +393,112 @@ This creates:
397
393
  - Intuitive input handling
398
394
  - Easy conversation reset
399
395
 
396
+ ### 🔗 MCP (Model Context Protocol) Integration
397
+
398
+ Agents can seamlessly integrate with the Model Context Protocol, allowing them to act as both MCP servers (providing tools to AI assistants) and MCP clients (using tools from other services).
399
+
400
+ #### Creating an MCP Server
401
+
402
+ ```typescript
403
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
404
+ import { McpAgent } from "agents/mcp";
405
+ import { z } from "zod";
406
+
407
+ type Env = {
408
+ MyMCP: DurableObjectNamespace<MyMCP>;
409
+ };
410
+
411
+ type State = { counter: number };
412
+
413
+ export class MyMCP extends McpAgent<Env, State, {}> {
414
+ server = new McpServer({
415
+ name: "Demo",
416
+ version: "1.0.0"
417
+ });
418
+
419
+ initialState: State = {
420
+ counter: 1
421
+ };
422
+
423
+ async init() {
424
+ this.server.resource("counter", "mcp://resource/counter", (uri) => {
425
+ return {
426
+ contents: [{ text: String(this.state.counter), uri: uri.href }]
427
+ };
428
+ });
429
+
430
+ this.server.tool(
431
+ "add",
432
+ "Add to the counter, stored in the MCP",
433
+ { a: z.number() },
434
+ async ({ a }) => {
435
+ this.setState({ ...this.state, counter: this.state.counter + a });
436
+
437
+ return {
438
+ content: [
439
+ {
440
+ text: String(`Added ${a}, total is now ${this.state.counter}`),
441
+ type: "text"
442
+ }
443
+ ]
444
+ };
445
+ }
446
+ );
447
+ }
448
+
449
+ onStateUpdate(state: State) {
450
+ console.log({ stateUpdate: state });
451
+ }
452
+ }
453
+
454
+ // HTTP Streamable transport (recommended)
455
+ export default MyMCP.serve("/mcp", {
456
+ binding: "MyMCP"
457
+ });
458
+
459
+ // Or SSE transport for legacy compatibility
460
+ // export default MyMCP.serveSSE("/mcp", { binding: "MyMCP" });
461
+ ```
462
+
463
+ #### Using MCP Tools
464
+
465
+ ```typescript
466
+ import { MCPClientManager } from "agents/mcp";
467
+
468
+ const client = new MCPClientManager("my-app", "1.0.0");
469
+
470
+ // Connect to an MCP server
471
+ await client.connect("https://weather-service.com/mcp", {
472
+ transport: { type: "streamable-http" }
473
+ });
474
+
475
+ // Use tools from the server
476
+ const weather = await client.callTool({
477
+ serverId: "weather-service",
478
+ name: "getWeather",
479
+ arguments: { location: "San Francisco" }
480
+ });
481
+ ```
482
+
483
+ #### AI SDK Integration
484
+
485
+ ```typescript
486
+ import { generateText } from "ai";
487
+
488
+ // Convert MCP tools for AI use
489
+ const result = await generateText({
490
+ model: openai("gpt-4"),
491
+ tools: client.unstable_getAITools(),
492
+ prompt: "What's the weather in Tokyo?"
493
+ });
494
+ ```
495
+
496
+ **Transport Options:**
497
+
498
+ - **Auto**: Automatically determine the correct transport
499
+ - **HTTP Streamable**: Best performance, batch requests, session management
500
+ - **SSE**: Simple setup, legacy compatibility
501
+
400
502
  ### 💬 The Path Forward
401
503
 
402
504
  We're developing new dimensions of agent capability:
@@ -1,7 +1,18 @@
1
- import { Agent, AgentContext } from "./index.js";
2
1
  import { Message, StreamTextOnFinishCallback, ToolSet } from "ai";
2
+ import { Agent, AgentContext } from "./index.js";
3
3
  import { Connection, WSMessage } from "partyserver";
4
4
  import "cloudflare:workers";
5
+ import "@modelcontextprotocol/sdk/client/index.js";
6
+ import "@modelcontextprotocol/sdk/types.js";
7
+ import "./client-DgyzBU_8.js";
8
+ import "zod";
9
+ import "@modelcontextprotocol/sdk/shared/protocol.js";
10
+ import "@modelcontextprotocol/sdk/client/sse.js";
11
+ import "@modelcontextprotocol/sdk/client/streamableHttp.js";
12
+ import "./mcp/do-oauth-client-provider.js";
13
+ import "@modelcontextprotocol/sdk/client/auth.js";
14
+ import "@modelcontextprotocol/sdk/shared/auth.js";
15
+ import "./observability/index.js";
5
16
 
6
17
  /**
7
18
  * Extension of Agent with built-in chat capabilities
@@ -11,25 +22,63 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
11
22
  Env,
12
23
  State
13
24
  > {
14
- #private;
25
+ /**
26
+ * Map of message `id`s to `AbortController`s
27
+ * useful to propagate request cancellation signals for any external calls made by the agent
28
+ */
29
+ private _chatMessageAbortControllers;
15
30
  /** Array of chat messages for the current conversation */
16
31
  messages: Message[];
17
32
  constructor(ctx: AgentContext, env: Env);
33
+ private _broadcastChatMessage;
18
34
  onMessage(connection: Connection, message: WSMessage): Promise<void>;
19
35
  onRequest(request: Request): Promise<Response>;
36
+ private _tryCatchChat;
20
37
  /**
21
38
  * Handle incoming chat messages and generate a response
22
39
  * @param onFinish Callback to be called when the response is finished
40
+ * @param options.signal A signal to pass to any child requests which can be used to cancel them
23
41
  * @returns Response to send to the client or undefined
24
42
  */
25
43
  onChatMessage(
26
- onFinish: StreamTextOnFinishCallback<ToolSet>
44
+ onFinish: StreamTextOnFinishCallback<ToolSet>,
45
+ options?: {
46
+ abortSignal: AbortSignal | undefined;
47
+ }
27
48
  ): Promise<Response | undefined>;
28
49
  /**
29
50
  * Save messages on the server side and trigger AI response
30
51
  * @param messages Chat messages to save
31
52
  */
32
53
  saveMessages(messages: Message[]): Promise<void>;
54
+ persistMessages(
55
+ messages: Message[],
56
+ excludeBroadcastIds?: string[]
57
+ ): Promise<void>;
58
+ private _reply;
59
+ /**
60
+ * For the given message id, look up its associated AbortController
61
+ * If the AbortController does not exist, create and store one in memory
62
+ *
63
+ * returns the AbortSignal associated with the AbortController
64
+ */
65
+ private _getAbortSignal;
66
+ /**
67
+ * Remove an abort controller from the cache of pending message responses
68
+ */
69
+ private _removeAbortController;
70
+ /**
71
+ * Propagate an abort signal for any requests associated with the given message id
72
+ */
73
+ private _cancelChatRequest;
74
+ /**
75
+ * Abort all pending requests and clear the cache of AbortControllers
76
+ */
77
+ private _destroyAbortControllers;
78
+ /**
79
+ * When the DO is destroyed, cancel all pending requests
80
+ */
81
+ destroy(): Promise<void>;
33
82
  }
34
83
 
35
84
  export { AIChatAgent };