agents 0.0.0-f973b54 → 0.0.0-fac1fe8

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 (56) hide show
  1. package/README.md +157 -27
  2. package/dist/ai-chat-agent.d.ts +40 -10
  3. package/dist/ai-chat-agent.js +268 -143
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +152 -0
  6. package/dist/ai-chat-v5-migration.js +19 -0
  7. package/dist/ai-react.d.ts +71 -67
  8. package/dist/ai-react.js +160 -54
  9. package/dist/ai-react.js.map +1 -1
  10. package/dist/ai-types.d.ts +36 -19
  11. package/dist/ai-types.js +6 -0
  12. package/dist/chunk-AVYJQSLW.js +17 -0
  13. package/dist/chunk-AVYJQSLW.js.map +1 -0
  14. package/dist/chunk-LL2AFX7V.js +109 -0
  15. package/dist/chunk-LL2AFX7V.js.map +1 -0
  16. package/dist/{chunk-Q5ZBHY4Z.js → chunk-MH46VMM4.js} +209 -53
  17. package/dist/chunk-MH46VMM4.js.map +1 -0
  18. package/dist/chunk-QEVM4BVL.js +116 -0
  19. package/dist/chunk-QEVM4BVL.js.map +1 -0
  20. package/dist/chunk-UJVEAURM.js +150 -0
  21. package/dist/chunk-UJVEAURM.js.map +1 -0
  22. package/dist/chunk-YDUDMOL6.js +1296 -0
  23. package/dist/chunk-YDUDMOL6.js.map +1 -0
  24. package/dist/client-CvaJdLQA.d.ts +5015 -0
  25. package/dist/client.d.ts +16 -2
  26. package/dist/client.js +7 -126
  27. package/dist/client.js.map +1 -1
  28. package/dist/index.d.ts +275 -25
  29. package/dist/index.js +13 -3
  30. package/dist/mcp/client.d.ts +9 -775
  31. package/dist/mcp/client.js +1 -2
  32. package/dist/mcp/do-oauth-client-provider.d.ts +4 -3
  33. package/dist/mcp/do-oauth-client-provider.js +3 -103
  34. package/dist/mcp/do-oauth-client-provider.js.map +1 -1
  35. package/dist/mcp/index.d.ts +73 -50
  36. package/dist/mcp/index.js +878 -661
  37. package/dist/mcp/index.js.map +1 -1
  38. package/dist/observability/index.d.ts +46 -0
  39. package/dist/observability/index.js +11 -0
  40. package/dist/observability/index.js.map +1 -0
  41. package/dist/react.d.ts +89 -5
  42. package/dist/react.js +23 -9
  43. package/dist/react.js.map +1 -1
  44. package/dist/schedule.d.ts +81 -7
  45. package/dist/schedule.js +19 -8
  46. package/dist/schedule.js.map +1 -1
  47. package/dist/serializable.d.ts +32 -0
  48. package/dist/serializable.js +1 -0
  49. package/dist/serializable.js.map +1 -0
  50. package/package.json +86 -67
  51. package/src/index.ts +1164 -157
  52. package/dist/chunk-HMLY7DHA.js +0 -16
  53. package/dist/chunk-HN5JVKAZ.js +0 -606
  54. package/dist/chunk-HN5JVKAZ.js.map +0 -1
  55. package/dist/chunk-Q5ZBHY4Z.js.map +0 -1
  56. /package/dist/{chunk-HMLY7DHA.js.map → ai-chat-v5-migration.js.map} +0 -0
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ### 🧠 `agents` - A Framework for Digital Intelligence
2
2
 
3
- ![agents-header](https://github.com/user-attachments/assets/f6d99eeb-1803-4495-9c5e-3cf07a37b402)
3
+ ![npm install agents](../../assets/npm-install-agents.svg)
4
4
 
5
5
  Welcome to a new chapter in software development, where AI agents persist, think, and act with purpose. The `agents` framework creates an environment where artificial intelligence can flourish - maintaining state, engaging in meaningful interactions, and evolving over time.
6
6
 
@@ -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
  }
@@ -166,7 +166,7 @@ export class DialogueAgent extends Agent {
166
166
  }
167
167
  ```
168
168
 
169
- #### Client Communion
169
+ #### Client Communication
170
170
 
171
171
  For direct connection to your agent:
172
172
 
@@ -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
@@ -317,20 +317,37 @@ Create meaningful conversations with intelligence:
317
317
  ```ts
318
318
  import { AIChatAgent } from "agents/ai-chat-agent";
319
319
  import { openai } from "@ai-sdk/openai";
320
+ import { streamText, generateText, createDataStreamResponse } from "ai";
320
321
 
321
322
  export class DialogueAgent extends AIChatAgent {
322
323
  async onChatMessage(onFinish) {
324
+ // Option 1: Streaming responses (recommended for real-time interaction)
323
325
  return createDataStreamResponse({
324
326
  execute: async (dataStream) => {
325
327
  const stream = streamText({
326
328
  model: openai("gpt-4o"),
327
329
  messages: this.messages,
328
- onFinish, // call onFinish so that messages get saved
330
+ // Optional: onFinish is invoked by the AI SDK when generation completes.
331
+ // Persistence is handled automatically by AIChatAgent after streaming completes.
332
+ onFinish
329
333
  });
330
334
 
331
335
  stream.mergeIntoDataStream(dataStream);
332
- },
336
+ }
333
337
  });
338
+
339
+ // Option 2: Non-streaming responses (simpler, but no real-time updates)
340
+ // const result = await generateText({
341
+ // model: openai("gpt-4o"),
342
+ // messages: this.messages,
343
+ // });
344
+ //
345
+ // // Optional: you can call onFinish here for custom side effects. Message
346
+ // // persistence is still handled automatically by AIChatAgent.
347
+ // await onFinish?.(result);
348
+ // return new Response(result.text, {
349
+ // headers: { 'Content-Type': 'text/plain' }
350
+ // });
334
351
  }
335
352
  }
336
353
  ```
@@ -346,14 +363,14 @@ import { useAgentChat } from "agents/ai-react";
346
363
  function ChatInterface() {
347
364
  // Connect to the agent
348
365
  const agent = useAgent({
349
- agent: "dialogue-agent",
366
+ agent: "dialogue-agent"
350
367
  });
351
368
 
352
369
  // Set up the chat interaction
353
370
  const { messages, input, handleInputChange, handleSubmit, clearHistory } =
354
371
  useAgentChat({
355
372
  agent,
356
- maxSteps: 5,
373
+ maxSteps: 5
357
374
  });
358
375
 
359
376
  return (
@@ -363,7 +380,14 @@ function ChatInterface() {
363
380
  {messages.map((message) => (
364
381
  <div key={message.id} className="message">
365
382
  <div className="role">{message.role}</div>
366
- <div className="content">{message.content}</div>
383
+ <div className="content">
384
+ {message.parts.map((part, i) => {
385
+ if (part.type === "text")
386
+ return <span key={i}>{part.text}</span>;
387
+ // Render other part types (e.g., files, tool calls) as desired
388
+ return null;
389
+ })}
390
+ </div>
367
391
  </div>
368
392
  ))}
369
393
  </div>
@@ -393,6 +417,112 @@ This creates:
393
417
  - Intuitive input handling
394
418
  - Easy conversation reset
395
419
 
420
+ ### 🔗 MCP (Model Context Protocol) Integration
421
+
422
+ 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).
423
+
424
+ #### Creating an MCP Server
425
+
426
+ ```typescript
427
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
428
+ import { McpAgent } from "agents/mcp";
429
+ import { z } from "zod";
430
+
431
+ type Env = {
432
+ MyMCP: DurableObjectNamespace<MyMCP>;
433
+ };
434
+
435
+ type State = { counter: number };
436
+
437
+ export class MyMCP extends McpAgent<Env, State, {}> {
438
+ server = new McpServer({
439
+ name: "Demo",
440
+ version: "1.0.0"
441
+ });
442
+
443
+ initialState: State = {
444
+ counter: 1
445
+ };
446
+
447
+ async init() {
448
+ this.server.resource("counter", "mcp://resource/counter", (uri) => {
449
+ return {
450
+ contents: [{ text: String(this.state.counter), uri: uri.href }]
451
+ };
452
+ });
453
+
454
+ this.server.tool(
455
+ "add",
456
+ "Add to the counter, stored in the MCP",
457
+ { a: z.number() },
458
+ async ({ a }) => {
459
+ this.setState({ ...this.state, counter: this.state.counter + a });
460
+
461
+ return {
462
+ content: [
463
+ {
464
+ text: String(`Added ${a}, total is now ${this.state.counter}`),
465
+ type: "text"
466
+ }
467
+ ]
468
+ };
469
+ }
470
+ );
471
+ }
472
+
473
+ onStateUpdate(state: State) {
474
+ console.log({ stateUpdate: state });
475
+ }
476
+ }
477
+
478
+ // HTTP Streamable transport (recommended)
479
+ export default MyMCP.serve("/mcp", {
480
+ binding: "MyMCP"
481
+ });
482
+
483
+ // Or SSE transport for legacy compatibility
484
+ // export default MyMCP.serveSSE("/mcp", { binding: "MyMCP" });
485
+ ```
486
+
487
+ #### Using MCP Tools
488
+
489
+ ```typescript
490
+ import { MCPClientManager } from "agents/mcp";
491
+
492
+ const client = new MCPClientManager("my-app", "1.0.0");
493
+
494
+ // Connect to an MCP server
495
+ await client.connect("https://weather-service.com/mcp", {
496
+ transport: { type: "streamable-http" }
497
+ });
498
+
499
+ // Use tools from the server
500
+ const weather = await client.callTool({
501
+ serverId: "weather-service",
502
+ name: "getWeather",
503
+ arguments: { location: "San Francisco" }
504
+ });
505
+ ```
506
+
507
+ #### AI SDK Integration
508
+
509
+ ```typescript
510
+ import { generateText } from "ai";
511
+
512
+ // Convert MCP tools for AI use
513
+ const result = await generateText({
514
+ model: openai("gpt-4"),
515
+ tools: client.getAITools(),
516
+ prompt: "What's the weather in Tokyo?"
517
+ });
518
+ ```
519
+
520
+ **Transport Options:**
521
+
522
+ - **Auto**: Automatically determine the correct transport
523
+ - **HTTP Streamable**: Best performance, batch requests, session management
524
+ - **SSE**: Simple setup, legacy compatibility
525
+
396
526
  ### 💬 The Path Forward
397
527
 
398
528
  We're developing new dimensions of agent capability:
@@ -418,8 +548,8 @@ Welcome to the future of intelligent agents. Create something meaningful. 🌟
418
548
  Contributions are welcome, but are especially welcome when:
419
549
 
420
550
  - You have opened an issue as a Request for Comment (RFC) to discuss your proposal, show your thinking, and iterate together.
421
- - Is not "AI slop": LLMs are powerful tools, but contributions entirely authored by vibe coding are unlikely to meet the quality bar, and will be rejected.
422
- - You're willing to accept feedback and make sure the changes fit the goals of the `agents` sdk. Not everything will, and that's OK.
551
+ - Not "AI slop": LLMs are powerful tools, but contributions entirely authored by vibe coding are unlikely to meet the quality bar, and will be rejected.
552
+ - You're willing to accept feedback and make sure the changes fit the goals of the `agents` SDK. Not everything will, and that's OK.
423
553
 
424
554
  Small fixes, type bugs, and documentation improvements can be raised directly as PRs.
425
555
 
@@ -1,15 +1,19 @@
1
+ import { UIMessage, StreamTextOnFinishCallback, ToolSet } from "ai";
1
2
  import { Agent, AgentContext } from "./index.js";
2
- import { Message, StreamTextOnFinishCallback, ToolSet } from "ai";
3
3
  import { Connection, WSMessage } from "partyserver";
4
- import "./mcp/client.js";
5
- import "zod";
6
- import "@modelcontextprotocol/sdk/types.js";
4
+ import "cloudflare:workers";
7
5
  import "@modelcontextprotocol/sdk/client/index.js";
6
+ import "@modelcontextprotocol/sdk/types.js";
7
+ import "./client-CvaJdLQA.js";
8
+ import "zod";
9
+ import "@modelcontextprotocol/sdk/shared/protocol.js";
8
10
  import "@modelcontextprotocol/sdk/client/sse.js";
11
+ import "@modelcontextprotocol/sdk/client/streamableHttp.js";
9
12
  import "./mcp/do-oauth-client-provider.js";
10
13
  import "@modelcontextprotocol/sdk/client/auth.js";
11
14
  import "@modelcontextprotocol/sdk/shared/auth.js";
12
- import "@modelcontextprotocol/sdk/shared/protocol.js";
15
+ import "./observability/index.js";
16
+ import "./ai-types.js";
13
17
 
14
18
  /**
15
19
  * Extension of Agent with built-in chat capabilities
@@ -19,12 +23,18 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
19
23
  Env,
20
24
  State
21
25
  > {
22
- #private;
26
+ /**
27
+ * Map of message `id`s to `AbortController`s
28
+ * useful to propagate request cancellation signals for any external calls made by the agent
29
+ */
30
+ private _chatMessageAbortControllers;
23
31
  /** Array of chat messages for the current conversation */
24
- messages: Message[];
32
+ messages: UIMessage[];
25
33
  constructor(ctx: AgentContext, env: Env);
34
+ private _broadcastChatMessage;
26
35
  onMessage(connection: Connection, message: WSMessage): Promise<void>;
27
36
  onRequest(request: Request): Promise<Response>;
37
+ private _tryCatchChat;
28
38
  /**
29
39
  * Handle incoming chat messages and generate a response
30
40
  * @param onFinish Callback to be called when the response is finished
@@ -38,14 +48,34 @@ declare class AIChatAgent<Env = unknown, State = unknown> extends Agent<
38
48
  }
39
49
  ): Promise<Response | undefined>;
40
50
  /**
41
- * Save messages on the server side and trigger AI response
51
+ * Save messages on the server side
42
52
  * @param messages Chat messages to save
43
53
  */
44
- saveMessages(messages: Message[]): Promise<void>;
54
+ saveMessages(messages: UIMessage[]): Promise<void>;
45
55
  persistMessages(
46
- messages: Message[],
56
+ messages: UIMessage[],
47
57
  excludeBroadcastIds?: string[]
48
58
  ): Promise<void>;
59
+ private _reply;
60
+ /**
61
+ * For the given message id, look up its associated AbortController
62
+ * If the AbortController does not exist, create and store one in memory
63
+ *
64
+ * returns the AbortSignal associated with the AbortController
65
+ */
66
+ private _getAbortSignal;
67
+ /**
68
+ * Remove an abort controller from the cache of pending message responses
69
+ */
70
+ private _removeAbortController;
71
+ /**
72
+ * Propagate an abort signal for any requests associated with the given message id
73
+ */
74
+ private _cancelChatRequest;
75
+ /**
76
+ * Abort all pending requests and clear the cache of AbortControllers
77
+ */
78
+ private _destroyAbortControllers;
49
79
  /**
50
80
  * When the DO is destroyed, cancel all pending requests
51
81
  */