Skip to content

Commit b69219f

Browse files
author
Claude Code
committed
Add comprehensive Agents SDK documentation
Sync documentation from cloudflare/agents PR #812. This update adds extensive documentation covering: - Core concepts: scheduling, routing, state, callable methods, HTTP/WebSockets - Client SDK: React hooks and vanilla JavaScript integration - API reference: getCurrentAgent() context management - Getting started: quickstart guide for building agents - How-to guides: adding agents to existing projects New features documented: - scheduleEvery() for fixed-interval recurring tasks - basePath routing for custom URL patterns - Server-sent identity with onIdentity callbacks - Callable improvements: timeouts, streaming, introspection - MCP client options-based API All documentation follows Cloudflare style guidelines with proper component usage (WranglerConfig, TypeScriptExample, PackageManagers). Source PR: cloudflare/agents#812
1 parent c3ba130 commit b69219f

File tree

11 files changed

+5627
-197
lines changed

11 files changed

+5627
-197
lines changed
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
---
2+
title: getCurrentAgent()
3+
pcx_content_type: concept
4+
sidebar:
5+
order: 14
6+
---
7+
8+
import { TypeScriptExample } from "~/components";
9+
10+
## Automatic Context for Custom Methods
11+
12+
**All custom methods automatically have full agent context.** The framework automatically detects and wraps your custom methods during initialization, ensuring `getCurrentAgent()` works seamlessly everywhere.
13+
14+
## How It Works
15+
16+
<TypeScriptExample>
17+
18+
```typescript
19+
import { AIChatAgent } from "@cloudflare/ai-chat";
20+
import { getCurrentAgent } from "agents";
21+
22+
export class MyAgent extends AIChatAgent {
23+
async customMethod() {
24+
const { agent } = getCurrentAgent<MyAgent>();
25+
// ✅ agent is automatically available
26+
console.log(agent.name);
27+
}
28+
29+
async anotherMethod() {
30+
// ✅ This works too - no setup needed
31+
const { agent } = getCurrentAgent<MyAgent>();
32+
return agent.state;
33+
}
34+
}
35+
```
36+
37+
</TypeScriptExample>
38+
39+
**Zero configuration required.** The framework automatically:
40+
41+
1. Scans your agent class for custom methods
42+
2. Wraps them with agent context during initialization
43+
3. Ensures `getCurrentAgent()` works in all external functions called from your methods
44+
45+
## Real-World Example
46+
47+
<TypeScriptExample>
48+
49+
```typescript
50+
import { AIChatAgent } from "@cloudflare/ai-chat";
51+
import { getCurrentAgent } from "agents";
52+
import { generateText } from "ai";
53+
import { openai } from "@ai-sdk/openai";
54+
55+
// External utility function that needs agent context
56+
async function processWithAI(prompt: string) {
57+
const { agent } = getCurrentAgent<MyAgent>();
58+
// ✅ External functions can access the current agent
59+
60+
return await generateText({
61+
model: openai("gpt-4"),
62+
prompt: `Agent ${agent?.name}: ${prompt}`
63+
});
64+
}
65+
66+
export class MyAgent extends AIChatAgent {
67+
async customMethod(message: string) {
68+
// Use this.* to access agent properties directly
69+
console.log("Agent name:", this.name);
70+
console.log("Agent state:", this.state);
71+
72+
// External functions automatically work
73+
const result = await processWithAI(message);
74+
return result.text;
75+
}
76+
}
77+
```
78+
79+
</TypeScriptExample>
80+
81+
### Built-in vs Custom Methods
82+
83+
- **Built-in methods** (onRequest, onEmail, onStateUpdate): Already have context
84+
- **Custom methods** (your methods): Automatically wrapped during initialization
85+
- **External functions**: Access context through `getCurrentAgent()`
86+
87+
### The Context Flow
88+
89+
```typescript
90+
// When you call a custom method:
91+
agent.customMethod()
92+
automatically wrapped with agentContext.run()
93+
your method executes with full context
94+
external functions can use getCurrentAgent()
95+
```
96+
97+
## Common Use Cases
98+
99+
### Working with AI SDK Tools
100+
101+
<TypeScriptExample>
102+
103+
```typescript
104+
import { AIChatAgent } from "@cloudflare/ai-chat";
105+
import { generateText } from "ai";
106+
import { openai } from "@ai-sdk/openai";
107+
108+
export class MyAgent extends AIChatAgent {
109+
async generateResponse(prompt: string) {
110+
// AI SDK tools automatically work
111+
const response = await generateText({
112+
model: openai("gpt-4"),
113+
prompt,
114+
tools: {
115+
// Tools that use getCurrentAgent() work perfectly
116+
}
117+
});
118+
119+
return response.text;
120+
}
121+
}
122+
```
123+
124+
</TypeScriptExample>
125+
126+
### Calling External Libraries
127+
128+
<TypeScriptExample>
129+
130+
```typescript
131+
import { AIChatAgent } from "@cloudflare/ai-chat";
132+
import { getCurrentAgent } from "agents";
133+
134+
async function saveToDatabase(data: any) {
135+
const { agent } = getCurrentAgent<MyAgent>();
136+
// Can access agent info for logging, context, etc.
137+
console.log(`Saving data for agent: ${agent?.name}`);
138+
}
139+
140+
export class MyAgent extends AIChatAgent {
141+
async processData(data: any) {
142+
// External functions automatically have context
143+
await saveToDatabase(data);
144+
}
145+
}
146+
```
147+
148+
</TypeScriptExample>
149+
150+
## API Reference
151+
152+
The agents package exports one main function for context management:
153+
154+
### `getCurrentAgent<T>()`
155+
156+
Gets the current agent from any context where it is available.
157+
158+
**Returns:**
159+
160+
<TypeScriptExample>
161+
162+
```typescript
163+
{
164+
agent: T | undefined,
165+
connection: Connection | undefined,
166+
request: Request | undefined
167+
}
168+
```
169+
170+
</TypeScriptExample>
171+
172+
**Usage:**
173+
174+
<TypeScriptExample>
175+
176+
```typescript
177+
import { AIChatAgent } from "@cloudflare/ai-chat";
178+
import { getCurrentAgent } from "agents";
179+
180+
export class MyAgent extends AIChatAgent {
181+
async customMethod() {
182+
const { agent, connection, request } = getCurrentAgent<MyAgent>();
183+
// agent is properly typed as MyAgent
184+
// connection and request available if called from a request handler
185+
}
186+
}
187+
```
188+
189+
</TypeScriptExample>

src/content/docs/agents/concepts/agent-class.mdx

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -341,12 +341,9 @@ Schedules are stored in the `cf_agents_schedules` SQL table. Cron schedules auto
341341
class MyAgent extends Agent {
342342
async onConnect() {
343343
// Add an MCP server
344-
await this.addMcpServer(
345-
"GitHub",
346-
"https://mcp.example.com/mcp",
347-
"https://my-worker.example.workers.dev", // callback host for OAuth
348-
"agents" // routing prefix
349-
);
344+
await this.addMcpServer("GitHub", "https://mcp.example.com/sse", {
345+
callbackHost: "https://my-worker.example.workers.dev"
346+
});
350347
}
351348
}
352349
```
@@ -361,15 +358,10 @@ class MyAgent extends Agent {
361358
console.log("Received email from:", email.from);
362359
console.log("Subject:", email.headers.get("subject"));
363360

364-
const raw = await email.getRaw();
365-
console.log("Raw email size:", raw.length);
366-
367361
// Reply to the email
368362
await this.replyToEmail(email, {
369363
fromName: "My Agent",
370-
subject: "Re: " + email.headers.get("subject"),
371-
body: "Thanks for your email!",
372-
contentType: "text/plain"
364+
body: "Thanks for your email!"
373365
});
374366
}
375367
}
@@ -387,6 +379,8 @@ export default {
387379
};
388380
```
389381

382+
For more details on email routing, resolvers, secure reply flows, and the full API, refer to the [Email Routing guide](/agents/guides/email/).
383+
390384
### Context Management
391385

392386
`agents` wraps all your methods with an `AsyncLocalStorage` to maintain context throughout the request lifecycle. This allows you to access the current agent, connection, request, or email (depending of what event is being handled) from anywhere in your code:

0 commit comments

Comments
 (0)